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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
samodom/UIKitSwagger | UIKitSwagger/View/UIViewAdditionSyntax.swift | 1 | 3622 | //
// UIViewAdditionSyntax.swift
// UIKitSwagger
//
// Created by Sam Odom on 12/5/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import UIKit
public protocol UIViewAddable { }
extension UIView: UIViewAddable { }
extension UIMotionEffect: UIViewAddable { }
extension UIGestureRecognizer: UIViewAddable { }
@available(iOS 9.0, *)
extension UILayoutGuide: UIViewAddable { }
public typealias UIViewRemovable = UIViewAddable
/**
An operator used to add a subview, layout guide, motion effect or gesture recognizer to a view.
*/
public func +=(view: UIView, addable: UIViewAddable) {
if #available(iOS 9.0, *) {
if let guide = addable as? UILayoutGuide {
view.addLayoutGuide(guide)
return
}
}
switch addable {
case let subview as UIView:
view.addSubview(subview)
case let effect as UIMotionEffect:
view.addMotionEffect(effect)
case let recognizer as UIGestureRecognizer:
view.addGestureRecognizer(recognizer)
default:
break
}
}
/**
An operator used to add an array of subviews, layout guides, motion effects and gesture recognizers to a view.
- note: The order in which the items are applied is not necessarily the order in which they are provided in the array. This is done to avoid adding modifiers for which the view is unprepared.
*/
public func +=(view: UIView, addables: [UIViewAddable]) {
groupAddables(addables).forEach { view += $0 }
}
/**
An operator used to remove a subview, auto layout constraint, motion effect or gesture recognizer from a view.
*/
public func -=(view: UIView, removable: UIViewRemovable) {
if #available(iOS 9.0, *) {
if let guide = removable as? UILayoutGuide {
view.removeLayoutGuide(guide)
return
}
}
switch removable {
case let subview as UIView:
if subview.superview == view {
subview.removeFromSuperview()
}
case let effect as UIMotionEffect:
view.removeMotionEffect(effect)
case let recognizer as UIGestureRecognizer:
view.removeGestureRecognizer(recognizer)
default:
break
}
}
/**
An operator used to remove an array of subviews, layout guides, motion effects and gesture recognizers from a view.
- note: The order in which the items are removed is not necessarily the order in which they are provided in the array. This is done to avoid leaving invalid modifiers in the view.
*/
public func -=(view: UIView, removables: [UIViewRemovable]) {
groupRemovables(removables).forEach { view -= $0 }
}
////////////////////////////////////////////////////////////////////////////////
private func groupAddables(addables: [UIViewAddable]) -> [UIViewAddable] {
var views = [UIViewAddable]()
var guides = [UIViewAddable]()
var effects = [UIViewAddable]()
var recognizers = [UIViewAddable]()
for addable in addables {
if #available(iOS 9.0, *) {
if let guide = addable as? UILayoutGuide {
guides.append(guide)
continue
}
}
switch addable {
case let view as UIView:
views.append(view)
case let effect as UIMotionEffect:
effects.append(effect)
case let recognizer as UIGestureRecognizer:
recognizers.append(recognizer)
default:
break
}
}
return views + guides + effects + recognizers
}
private func groupRemovables(removables: [UIViewRemovable]) -> [UIViewRemovable] {
return groupAddables(removables).reverse()
}
| mit | 376adb68a9698c9139660bf605eb5b40 | 26.861538 | 192 | 0.650193 | 4.703896 | false | false | false | false |
jimabc/peek-and-pop-example-ios | PeekAndPopExample/PeekAndPopExample/Controller/MainViewController.swift | 1 | 2108 | //
// MainViewController.swift
// PeekAndPopExample
//
// Created by James Matteson on 12/3/16.
// Copyright © 2016 James Matteson. All rights reserved.
//
import UIKit
fileprivate enum SegmentIndex: Int {
case list = 0
case grid
static func displayValues() -> [String] {
return ["List", "Grid"]
}
}
class MainViewController: UIViewController {
fileprivate var gridVC: MessageGridViewController!
fileprivate var listVC: MessageListViewController!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Configure view
view.backgroundColor = UIColor.white
// Configure child views
let data = DataSource()
gridVC = MessageGridViewController(data: data)
listVC = MessageListViewController(data: data)
attachChildViewController(listVC)
attachChildViewController(gridVC)
// Create tabs
let segmentedControl = UISegmentedControl(items: SegmentIndex.displayValues())
segmentedControl.addTarget(
self,
action: #selector(segmentedControlChanged(_:)),
for: .valueChanged)
// Set the default tab
segmentedControl.selectedSegmentIndex = SegmentIndex.list.rawValue
segmentedControlChanged(segmentedControl)
// Add tabs to the navigation bar
navigationItem.titleView = segmentedControl
}
// MARK: - UI
fileprivate func showSubview(_ subview: UIView) {
view.subviews.forEach({
$0.isHidden = true
})
subview.isHidden = false
}
// MARK: - Events
func segmentedControlChanged(_ sender: UISegmentedControl) {
guard let selectedSegmentIndex = SegmentIndex(rawValue: sender.selectedSegmentIndex) else {
return
}
switch selectedSegmentIndex {
case .grid:
showSubview(gridVC.view)
case .list:
showSubview(listVC.view)
}
}
}
| mit | 02f8767b1a483fe772e0296b276d0b12 | 25.012346 | 99 | 0.606075 | 5.544737 | false | false | false | false |
hhsolar/MemoryMaster-iOS | MemoryMaster/Model/BookMark+CoreDataClass.swift | 1 | 2412 | //
// BookMark+CoreDataClass.swift
// MemoryMaster
//
// Created by apple on 17/10/2017.
// Copyright © 2017 greatwall. All rights reserved.
//
//
import Foundation
import CoreData
public class BookMark: NSManagedObject
{
class func findOrCreate(matching bookmark: MyBookmark, in context: NSManagedObjectContext) {
let request: NSFetchRequest<BookMark> = BookMark.fetchRequest()
request.predicate = NSPredicate(format: "name == %@", bookmark.name)
do {
let matches = try context.fetch(request)
if matches.count > 0 {
matches[0].id = Int32(bookmark.id)
matches[0].time = bookmark.time as NSDate
matches[0].readType = bookmark.readType
matches[0].readPage = Int32(bookmark.readPage)
matches[0].readPageStatus = bookmark.readPageStatus
} else {
let newMark = BookMark(context: context)
newMark.name = bookmark.name
newMark.id = Int32(bookmark.id)
newMark.time = bookmark.time as NSDate
newMark.readType = bookmark.readType
newMark.readPage = Int32(bookmark.readPage)
newMark.readPageStatus = bookmark.readPageStatus
}
} catch {
print("BookMark -- findOrCreate -- error: \(error)")
}
try? context.save()
}
class func find(matching name: String, in context: NSManagedObjectContext) throws -> Bool {
let request: NSFetchRequest<BookMark> = BookMark.fetchRequest()
request.predicate = NSPredicate(format: "name == %@", name)
do {
let matches = try context.fetch(request)
if matches.count > 0 {
return true
}
} catch {
throw error
}
return false
}
class func remove(matching id: Int32, in context: NSManagedObjectContext) {
let request: NSFetchRequest<BookMark> = BookMark.fetchRequest()
request.predicate = NSPredicate(format: "id == %d", id)
do {
let matches = try context.fetch(request)
if matches.count > 0 {
for i in matches {
context.delete(i)
}
}
} catch {
print("BookMark -- remove -- error: \(error)")
}
}
}
| mit | 382c8696e2ee9647750d4e66513cf123 | 32.957746 | 96 | 0.560763 | 4.851107 | false | false | false | false |
eaplatanios/jelly-bean-world | api/swift/Sources/JellyBeanWorldExperiments/main.swift | 1 | 10171 | // Copyright 2019, The Jelly Bean World Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import Foundation
import JellyBeanWorld
import Logging
import ReinforcementLearning
import SPMUtility
@usableFromInline let logger = Logger(label: "Jelly Bean World Experiment")
@usableFromInline let rebuttal: Bool = false
public enum Error: Swift.Error {
case invalidCommand, invalidArgument
}
public enum Command: String {
case run, makePlots
}
extension Command: StringEnumArgument {
public static var completion: ShellCompletion {
.values([
(Command.run.rawValue, "Runs a Jelly Bean World experiment."),
(Command.makePlots.rawValue,
"Creates plots for the results of previously run Jelly Bean World experiments.")
])
}
}
public enum Reward: String, CaseIterable, CustomStringConvertible {
case collectJellyBeans,
collectOnions,
collectJellyBeansAvoidOnions,
collectJellyBeansAvoidOnionsLong,
collectJellyBeansAndThenAvoidOnions,
avoidOnionsAndThenCollectJellyBeans,
cyclicalJellyBeansOnions
public var description: String {
switch self {
case .collectJellyBeans: return "CollectJellyBeans"
case .collectOnions: return "CollectOnions"
case .collectJellyBeansAvoidOnions: return "CollectJellyBeansAvoidOnions"
case .collectJellyBeansAvoidOnionsLong: return "CollectJellyBeansAvoidOnionsLong"
case .collectJellyBeansAndThenAvoidOnions: return "CollectJellyBeansAndThenAvoidOnions"
case .avoidOnionsAndThenCollectJellyBeans: return "AvoidOnionsAndThenCollectJellyBeans"
case .cyclicalJellyBeansOnions: return "CyclicalJellyBeansOnions"
}
}
}
extension Reward: StringEnumArgument {
public static var completion: ShellCompletion {
.values([
(Reward.collectJellyBeans.rawValue, "Each collected jelly bean is worth 1 point."),
(Reward.collectOnions.rawValue, "Each collected onion is worth 1 point."),
(Reward.collectJellyBeansAvoidOnions.rawValue, "Each collected jelly bean is worth 1 point and each collected onion -1 point."),
(Reward.collectJellyBeansAvoidOnionsLong.rawValue, "Same as 'CollectJellyBeansAvoidOnions'. Only used for organizing experimental results for the paper."),
(Reward.collectJellyBeansAndThenAvoidOnions.rawValue, "Same as 'CollectJellyBeansAvoidOnions', but with a curriculum schedule."),
(Reward.avoidOnionsAndThenCollectJellyBeans.rawValue, "Same as 'CollectJellyBeansAvoidOnions', but with a curriculum schedule."),
(Reward.cyclicalJellyBeansOnions.rawValue, "Cycle every 100,000 steps between collecting jelly beans and avoiding onions and the opposite.")
])
}
}
public enum Agent: String, CaseIterable, CustomStringConvertible {
case reinforce, a2c, ppo, dqn
public var description: String {
switch self {
case .reinforce: return "REINFORCE"
case .a2c: return "A2C"
case .ppo: return "PPO"
case .dqn: return "DQN"
}
}
}
extension Agent: StringEnumArgument {
public static var completion: ShellCompletion {
return .values([
(Agent.reinforce.rawValue, "REINFORCE agent."),
(Agent.a2c.rawValue, "Advantage Actor Critic (A2C) agent."),
(Agent.ppo.rawValue, "Proximal Policy Optimization (PPO) agent."),
(Agent.dqn.rawValue, "Deep Q-Network (DQN) agent.")
])
}
}
public enum Observation: String, CaseIterable, CustomStringConvertible {
case vision, scent, visionAndScent
public var description: String {
switch self {
case .vision: return "Vision"
case .scent: return "Scent"
case .visionAndScent: return "Vision+Scent"
}
}
}
extension Observation: StringEnumArgument {
public static var completion: ShellCompletion {
.values([
(Observation.vision.rawValue, "Visual field."),
(Observation.scent.rawValue, "Scent vector at the current cell."),
(Observation.visionAndScent.rawValue, "Visual field and scent vector at the current cell.")
])
}
}
public enum Network: String, CaseIterable, CustomStringConvertible {
case plain, rewardAware, rewardContextual
public var description: String {
switch self {
case .plain: return "Plain"
case .rewardAware: return "RewardAware"
case .rewardContextual: return "RewardContextual"
}
}
}
extension Network: StringEnumArgument {
public static var completion: ShellCompletion {
.values([
(Network.plain.rawValue, "Plain network."),
(Network.rewardAware.rawValue, "Reward-aware network."),
(Network.rewardContextual.rawValue, "Reward-contextual network.")
])
}
}
let parser = ArgumentParser(
usage: "<options>",
overview: "This executable can be used to run Jelly Bean World experiments.")
let commandArg: PositionalArgument<Command> = parser.add(
positional: "command",
kind: Command.self,
usage: "Experiment command to invoke. Can be one of: `run` and `makePlots`.")
let rewardArg: OptionArgument<Reward> = parser.add(
option: "--reward",
kind: Reward.self,
usage: "Reward schedule to use. Can be one of: `collectJellyBeans`.")
let agentArg: OptionArgument<Agent> = parser.add(
option: "--agent",
kind: Agent.self,
usage: "Agent to use in the experiments. Can be one of: `reinforce`, `a2c`, `ppo`, and `dqn`.")
let observationArg: OptionArgument<Observation> = parser.add(
option: "--observation",
kind: Observation.self,
usage: "Observations type. Can be one of: `vision`, `scent`, and `visionAndScent`.")
let networkArg: OptionArgument<Network> = parser.add(
option: "--network",
kind: Network.self,
usage: "Network type. Can be one of: `plain`, `rewardAware`, and `rewardContextual`.")
let networkHiddenStateSizeArg: OptionArgument<Int> = parser.add(
option: "--network-hidden-state-size",
kind: Int.self,
usage: "Network hidden state size.")
let agentFieldOfViewArg: OptionArgument<Int> = parser.add(
option: "--agent-field-of-view",
kind: Int.self,
usage: "Agents' field of view. Defaults to 360.")
let noVisualOcclusionArg: OptionArgument<Bool> = parser.add(
option: "--no-visual-occlusion",
kind: Bool.self,
usage: "Disables visual occlusion.")
let batchSizeArg: OptionArgument<Int> = parser.add(
option: "--batch-size",
kind: Int.self,
usage: "Batch size to use for the experiments. Defaults to 32.")
let stepCountArg: OptionArgument<Int> = parser.add(
option: "--step-count",
kind: Int.self,
usage: "Total number of steps to run. Defaults to `10_000_000`.")
let stepCountPerUpdateArg: OptionArgument<Int> = parser.add(
option: "--step-count-per-update",
kind: Int.self,
usage: "Number of steps between model updates. Defaults to 512.")
let rewardRatePeriodArg: OptionArgument<Int> = parser.add(
option: "--reward-rate-period",
kind: Int.self,
usage: "Moving average period used when computing the reward rate. Defaults to `100_000`.")
let resultsDirArg: OptionArgument<PathArgument> = parser.add(
option: "--results-dir",
kind: PathArgument.self,
usage: "Path to the results directory.")
let minimumRunIDArg: OptionArgument<Int> = parser.add(
option: "--minimum-run-id",
kind: Int.self,
usage: "Minimum run ID to use.")
let serverPortsArg: OptionArgument<[Int]> = parser.add(
option: "--server-ports",
kind: [Int].self,
usage: "Ports to use for launching simulation servers.")
// The first argument is always the executable, and so we drop it.
let arguments = Array(ProcessInfo.processInfo.arguments.dropFirst())
let parsedArguments = try parser.parse(arguments)
let currentDir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let resultsDir: Foundation.URL = {
if let argument = parsedArguments.get(resultsDirArg) {
return URL(fileURLWithPath: argument.path.pathString)
}
return currentDir.appendingPathComponent(rebuttal ? "temp-rebuttal/results" : "temp/results")
}()
guard let reward = parsedArguments.get(rewardArg) else { throw Error.invalidArgument }
guard let agent = parsedArguments.get(agentArg) else { throw Error.invalidArgument }
let agentFieldOfView = parsedArguments.get(agentFieldOfViewArg) ?? 360
let enableVisualOcclusion = !(parsedArguments.get(noVisualOcclusionArg) ?? false)
let batchSize = parsedArguments.get(batchSizeArg) ?? 32
let stepCount = parsedArguments.get(stepCountArg) ?? 10_000_000
let stepCountPerUpdate = parsedArguments.get(stepCountPerUpdateArg) ?? 512
let rewardRatePeriod = parsedArguments.get(rewardRatePeriodArg) ?? 100_000
let minimumRunID = parsedArguments.get(minimumRunIDArg) ?? 0
let serverPorts = parsedArguments.get(serverPortsArg)
let experiment = try! Experiment(
reward: reward,
agent: agent,
agentFieldOfView: agentFieldOfView,
enableVisualOcclusion: enableVisualOcclusion,
batchSize: batchSize,
stepCount: stepCount,
stepCountPerUpdate: stepCountPerUpdate,
resultsDir: resultsDir,
minimumRunID: minimumRunID,
serverPorts: serverPorts)
switch parsedArguments.get(commandArg) {
case .run:
guard let observation = parsedArguments.get(observationArg) else { throw Error.invalidArgument }
guard let network = parsedArguments.get(networkArg) else { throw Error.invalidArgument }
let networkHiddenStateSize = parsedArguments.get(networkHiddenStateSizeArg)
try! experiment.run(
observation: observation,
network: network,
networkHiddenStateSize: networkHiddenStateSize,
writeFrequency: 100,
logFrequency: 1000)
case .makePlots:
try! makePlots(resultsDir: resultsDir, rewardRatePeriod: 50000)
// try! experiment.makePlots(
// observations: [Observation](Observation.allCases),
// networks: [Network](Network.allCases),
// rewardRatePeriod: rewardRatePeriod)
case _: throw Error.invalidCommand
}
| apache-2.0 | 11e32f5132bc6e73f8aa904b4866350a | 37.969349 | 161 | 0.745649 | 4.236152 | false | false | false | false |
OscarSwanros/swift | test/SILOptimizer/definite_init_objc_factory_init.swift | 2 | 4141 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -emit-sil -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import ImportAsMember.Class
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So4HiveCSQyABGSQySo3BeeCG5queen_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
func testInstanceTypeFactoryMethod(queen: Bee) {
// CHECK: bb0([[QUEEN:%[0-9]+]] : $Optional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type):
// CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive!, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: release_value [[QUEEN]]
// CHECK-NEXT: return [[HIVE]] : $Optional<Hive>
var hive1 = Hive(queen: queen)
}
extension Hive {
// FIXME: This whole approach is wrong. This should be a factory
// initializer, not a convenience initializer, which means it does
// not have an initializing entry point at all.
// CHECK-LABEL: sil hidden @_T0So4HiveC027definite_init_objc_factory_C0EABSo3BeeC10otherQueen_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive
convenience init(otherQueen other: Bee) {
// CHECK: [[SELF_ADDR:%[0-9]+]] = alloc_stack $Hive
// CHECK: store [[OLD_SELF:%[0-9]+]] to [[SELF_ADDR]]
// CHECK: [[META:%[0-9]+]] = value_metatype $@thick Hive.Type, [[OLD_SELF]] : $Hive
// CHECK: [[FACTORY:%[0-9]+]] = objc_method [[META]] : $@thick Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive!, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: apply [[FACTORY]]([[QUEEN:%[0-9]+]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: store [[NEW_SELF:%[0-9]+]] to [[SELF_ADDR]]
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[OLD_SELF]] : $Hive
// CHECK: dealloc_partial_ref [[OLD_SELF]] : $Hive, [[METATYPE]] : $@thick Hive.Type
// CHECK: dealloc_stack [[SELF_ADDR]]
// CHECK: return [[NEW_SELF]]
self.init(queen: other)
}
convenience init(otherFlakyQueen other: Bee) throws {
try self.init(flakyQueen: other)
}
}
extension SomeClass {
// SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_
// SIL: bb0([[DOUBLE:%[0-9]+]] : $Double
// SIL-NOT: value_metatype
// SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// SIL: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
class SubHive : Hive {
// CHECK-LABEL: sil hidden @_T0027definite_init_objc_factory_B07SubHiveCACyt20delegatesToInherited_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive
convenience init(delegatesToInherited: ()) {
// CHECK: [[UPCAST:%.*]] = upcast %0 : $SubHive to $Hive
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[UPCAST]] : $Hive
// CHECK: [[METHOD:%.*]] = objc_method [[METATYPE]] : $@thick Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive!
// CHECK: [[OBJC:%.*]] = thick_to_objc_metatype [[METATYPE]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: apply [[METHOD]]({{.*}}, [[OBJC]])
// CHECK: [[METATYPE:%.*]] = value_metatype $@thick SubHive.Type, %0 : $SubHive
// CHECK-NEXT: dealloc_partial_ref %0 : $SubHive, [[METATYPE]] : $@thick SubHive.Type
// CHECK: return {{%.*}} : $SubHive
self.init(queen: Bee())
}
}
| apache-2.0 | b444e46831da253d2c4ca411eb5b0125 | 57.323944 | 265 | 0.642598 | 3.355754 | false | false | false | false |
zeroc-ice/ice | swift/src/Ice/Object.swift | 4 | 5120 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import IceImpl
import PromiseKit
/// Request is an opaque type that represents an incoming request.
public typealias Request = Incoming
/// A request dispatcher (Disp) is a helper struct used by object adapters to dispatch
/// requests to servants.
public protocol Disp {
/// Dispatch request to servant.
///
/// - parameter request: `Ice.Request` - The incoming request.
///
/// - parameter current: `Ice.Current` - The Current object for the dispatch.
func dispatch(request: Request, current: Current) throws -> Promise<OutputStream>?
}
/// A SliceTraits struct describes a Slice interface, class or exception.
public protocol SliceTraits {
/// List of all type-ids.
static var staticIds: [String] { get }
/// Most derived type-id.
static var staticId: String { get }
}
/// The base class for servants.
public protocol Object {
/// Returns the Slice type ID of the most-derived interface supported by this object.
///
/// - parameter current: `Ice.Current` - The Current object for the dispatch.
///
/// - returns: `String` - The Slice type ID of the most-derived interface.
func ice_id(current: Current) throws -> String
/// Returns the Slice type IDs of the interfaces supported by this object.
///
/// - parameter current: `Ice.Current` - The Current object for the dispatch.
///
/// - returns: `[String]` The Slice type IDs of the interfaces supported by this object, in base-to-derived
/// order. The first element of the returned array is always `::Ice::Object`.
func ice_ids(current: Current) throws -> [String]
/// Tests whether this object supports a specific Slice interface.
///
/// - parameter s: `String` - The type ID of the Slice interface to test against.
///
/// - parameter current: `Ice.Current` - The Current object for the dispatch.
///
/// - returns: `Bool` - True if this object has the interface specified by s or
/// derives from the interface specified by s.
func ice_isA(id: String, current: Current) throws -> Bool
/// Tests whether this object can be reached.
///
/// - parameter current: The Current object for the dispatch.
func ice_ping(current: Current) throws
}
public extension Object {
func _iceD_ice_id(incoming inS: Incoming, current: Current) throws -> Promise<OutputStream>? {
try inS.readEmptyParams()
let returnValue = try ice_id(current: current)
return inS.setResult { ostr in
ostr.write(returnValue)
}
}
func _iceD_ice_ids(incoming inS: Incoming, current: Current) throws -> Promise<OutputStream>? {
try inS.readEmptyParams()
let returnValue = try ice_ids(current: current)
return inS.setResult { ostr in
ostr.write(returnValue)
}
}
func _iceD_ice_isA(incoming inS: Incoming, current: Current) throws -> Promise<OutputStream>? {
let ident: String = try inS.read { istr in
try istr.read()
}
let returnValue = try ice_isA(id: ident, current: current)
return inS.setResult { ostr in
ostr.write(returnValue)
}
}
func _iceD_ice_ping(incoming inS: Incoming, current: Current) throws -> Promise<OutputStream>? {
try inS.readEmptyParams()
try ice_ping(current: current)
return inS.setResult()
}
}
/// Traits for Object.
public struct ObjectTraits: SliceTraits {
public static let staticIds = ["::Ice::Object"]
public static let staticId = "::Ice::Object"
}
/// class ObjectI provides the default implementation of Object operations (ice_id,
/// ice_ping etc.) for a given Slice interface.
open class ObjectI<T: SliceTraits>: Object {
public init() {}
open func ice_id(current _: Current) throws -> String {
return T.staticId
}
open func ice_ids(current _: Current) throws -> [String] {
return T.staticIds
}
open func ice_isA(id: String, current _: Current) throws -> Bool {
return T.staticIds.contains(id)
}
open func ice_ping(current _: Current) throws {
// Do nothing
}
}
/// Request dispatcher for plain Object servants.
public struct ObjectDisp: Disp {
public let servant: Object
public init(_ servant: Object) {
self.servant = servant
}
public func dispatch(request: Request, current: Current) throws -> Promise<OutputStream>? {
switch current.operation {
case "ice_id":
return try servant._iceD_ice_id(incoming: request, current: current)
case "ice_ids":
return try servant._iceD_ice_ids(incoming: request, current: current)
case "ice_isA":
return try servant._iceD_ice_isA(incoming: request, current: current)
case "ice_ping":
return try servant._iceD_ice_ping(incoming: request, current: current)
default:
throw OperationNotExistException(id: current.id, facet: current.facet, operation: current.operation)
}
}
}
| gpl-2.0 | 45bd09016adfb2d60a8d98b96580af50 | 32.246753 | 112 | 0.647461 | 4.241922 | false | false | false | false |
gearedupcoding/RadioPal | RadioPal/New Group/StationModel.swift | 1 | 2914 | //
// StationModel.swift
// RadioPal
//
// Created by Jami, Dheeraj on 9/20/17.
// Copyright © 2017 Jami, Dheeraj. All rights reserved.
//
import UIKit
import SwiftyJSON
/*
▿ {
"total_listeners" : 81,
"name" : "Arabesk FM",
"updated_at" : "2017-09-18T02:29:00+02:00",
"website" : "http:\/\/www.arabeskfm.biz",
"twitter" : "fmarabesk",
"facebook" : "https:\/\/www.facebook.com\/fmarabesk",
"id" : 57401,
"categories" : [
{
"id" : 18,
"title" : "Classic Rock",
"slug" : "classic-rock",
"description" : "",
"ancestry" : "2"
}
],
"streams" : [
{
"content_type" : "audio\/mpeg",
"status" : 1,
"listeners" : 81,
"stream" : "http:\/\/yayin.arabeskfm.biz:8042",
"bitrate" : 80
}
],
"created_at" : "2017-09-18T02:28:58+02:00",
"image" : {
"url" : "https:\/\/img.dirble.com\/station\/57401\/ce32587e-5df9-41b4-99b7-19f4b0c39d37.jpg",
"thumb" : {
"url" : "https:\/\/img.dirble.com\/station\/57401\/thumb_ce32587e-5df9-41b4-99b7-19f4b0c39d37.jpg"
}
},
"slug" : "arabesk-fm-9c7d6baf-1b74-4d50-aded-83093a97746d",
"country" : "TR"
}
{
"id" : 57400,
"total_listeners" : 0,
"categories" : [
{
"id" : 5,
"title" : "Pop",
"slug" : "pop",
"description" : "stations that normally play pop-music",
"ancestry" : null
}
],
"streams" : [
{
"content_type" : "audio\/mpeg",
"status" : 1,
"listeners" : 0,
"stream" : "http:\/\/server1.usatelk.com:26990\/",
"bitrate" : 64
}
],
"created_at" : "2017-09-17T08:33:47+02:00",
"image" : {
"url" : "https:\/\/img.dirble.com\/station\/57400\/d604bc46-34e7-4acc-9e91-8e485b5710da.jpg",
"thumb" : {
"url" : "https:\/\/img.dirble.com\/station\/57400\/thumb_d604bc46-34e7-4acc-9e91-8e485b5710da.jpg"
}
},
"slug" : "alianza-internacional-de-radio",
"updated_at" : "2017-09-17T08:33:48+02:00",
"facebook" : "https:\/\/www.facebook.com\/AlianzaInternacionaldeRadio\/",
"website" : "http:\/\/alianzainternacionalderadio.com\/",
"country" : "US",
"name" : "Alianza Internacional de Radio",
"twitter" : "https:\/\/twitter.com\/AIRRADIONY"
},
*/
class StationModel: NSObject {
var id: String?
var name: String?
var total_listeners: Int?
var created_at: Date?
var slug: String?
var updatedAt: String?
var country: String?
var stream = [StreamModel]()
var imageUrl: String?
var thumbUrl: String?
init(json: JSON) {
self.id = json["id"].string
self.name = json["name"].string
if let streamArray = json["streams"].array {
for stream in streamArray {
let streamObj = StreamModel(json: stream)
self.stream.append(streamObj)
}
}
if let imageDict = json["image"].dictionary {
self.imageUrl = imageDict["url"]?.string
if let thumbDict = imageDict["thumb"]?.dictionary {
self.thumbUrl = thumbDict["url"]?.string
}
}
}
}
| mit | 31405a5e636a2912b9aed585f55ff5cf | 23.258333 | 99 | 0.589832 | 2.712954 | false | false | false | false |
vlfm/swapi-swift | Source/Parsers/SpeciesParser.swift | 1 | 1587 | import Foundation
final class SpeciesParser {
static func make() -> Parser<Species> {
return { json in
return try Extract.from(jsonDictionary: json) { input in
let identity = try input.identity()
let averageHeight = try input.string(at: "average_height")
let averageLifespan = try input.string(at: "average_lifespan")
let classification = try input.string(at: "classification")
let designation = try input.string(at: "designation")
let eyeColors = try input.string(at: "eye_colors", separator: ",")
let hairColors = try input.string(at: "hair_colors", separator: ",")
let homeworld = try input.url(at: "homeworld")
let language = try input.string(at: "language")
let name = try input.string(at: "name")
let people = try input.urls(at: "people")
let films = try input.urls(at: "films")
let skinColors = try input.string(at: "skin_colors", separator: ",")
return Species(identity: identity, name: name, classification: classification,
designation: designation, averageHeight: averageHeight,
averageLifespan: averageLifespan, eyeColors: eyeColors,
hairColors: hairColors, skinColors: skinColors, language: language,
homeworld: homeworld, people: people, films: films)
}
}
}
}
| apache-2.0 | 3f44980fd622f87248f3862970eacacb | 53.724138 | 98 | 0.556396 | 4.928571 | false | false | false | false |
dwipp/DPImageGenerator | LogoGenerator/ViewController.swift | 1 | 1081 | //
// ViewController.swift
// LogoGenerator
//
// Created by Dwi Putra on 11/10/15.
// Copyright © 2015 dwipp. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var txt_field: UITextField!
@IBOutlet var img_image: UIImageView!
let imageGen:DPImageGenerator = DPImageGenerator()
override func viewDidLoad() {
super.viewDidLoad()
img_image.layer.cornerRadius = 15
imageGen.image_frame = img_image.frame
imageGen.text_font = UIFont(name: "HelveticaNeue", size: 80)
imageGen.text_color = UIColor.whiteColor()
imageGen.max_char = maxCharacter.two
imageGen.dynamic_gradient = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func action_generate(sender: AnyObject) {
self.view.endEditing(true)
if txt_field.text != "" {
img_image.image = imageGen.imageGenerator(txt_field.text!)
}
}
}
| mit | 38ca337e0104f4cb2ed90d7937c1aa18 | 26 | 70 | 0.648148 | 4.32 | false | false | false | false |
cjwirth/Tweets-InteractorExample | Tweets/Controllers/LoginViewController.swift | 1 | 1914 | import UIKit
class LoginViewController: UIViewController {
private let models = ModelProvider()
@IBOutlet var usernameInput: UITextField!
@IBAction func loginButtonWasTapped() {
let inputName = usernameInput.text ?? ""
if let user = models.users[inputName] {
models.currentUser = user
// let interactor = TweetViewStandardInteractor(dataSource: models)
// let controller = TweetViewController(interactor: interactor, dataSource: models)
let controller = TweetViewController(dataSource: models)
controller.title = "\(user.name)'s Feed"
controller.navigationItem.leftBarButtonItem = BarButtonItem.create("Logout", handler: { _ in
self.models.currentUser = nil
self.navigationController?.popToRootViewControllerAnimated(true)
self.navigationController?.setNavigationBarHidden(true, animated: true)
})
navigationController?.pushViewController(controller, animated: true)
controller.navigationController?.setNavigationBarHidden(false, animated: true)
} else {
alert(self, title: "Could not login", message: "User does not exist.")
}
}
@IBAction func previewButtonWasTapped() {
// let interactor = TweetViewLoggedOutInteractor(loginController: self)
// let controller = TweetViewController(interactor: interactor, dataSource: models)
let controller = TweetViewController(dataSource: models)
controller.title = "Preview"
controller.navigationItem.leftBarButtonItem = BarButtonItem.create("Login", handler: { _ in
self.dismissViewControllerAnimated(true, completion: nil)
})
let navControl = UINavigationController(rootViewController: controller)
presentViewController(navControl, animated: true, completion: nil)
}
}
| mit | 6318a389e1fc900feef006d4ab86a28b | 43.511628 | 104 | 0.681296 | 5.646018 | false | false | false | false |
amraboelela/swift-corelibs-foundation | Foundation/NSURL.swift | 1 | 59936 | // 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
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
#if os(OSX) || os(iOS)
internal let kCFURLPOSIXPathStyle = CFURLPathStyle.cfurlposixPathStyle
internal let kCFURLWindowsPathStyle = CFURLPathStyle.cfurlWindowsPathStyle
#endif
private func _standardizedPath(_ path: String) -> String {
if !path.absolutePath {
return path._nsObject.standardizingPath
}
return path
}
internal func _pathComponents(_ path: String?) -> [String]? {
guard let p = path else {
return nil
}
var result = [String]()
if p.length == 0 {
return result
} else {
let characterView = p
var curPos = characterView.startIndex
let endPos = characterView.endIndex
if characterView[curPos] == "/" {
result.append("/")
}
while curPos < endPos {
while curPos < endPos && characterView[curPos] == "/" {
curPos = characterView.index(after: curPos)
}
if curPos == endPos {
break
}
var curEnd = curPos
while curEnd < endPos && characterView[curEnd] != "/" {
curEnd = characterView.index(after: curEnd)
}
result.append(String(characterView[curPos ..< curEnd]))
curPos = curEnd
}
}
if p.length > 1 && p.hasSuffix("/") {
result.append("/")
}
return result
}
public struct URLResourceKey : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: URLResourceKey, rhs: URLResourceKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension URLResourceKey {
public static let keysOfUnsetValuesKey = URLResourceKey(rawValue: "NSURLKeysOfUnsetValuesKey")
public static let nameKey = URLResourceKey(rawValue: "NSURLNameKey")
public static let localizedNameKey = URLResourceKey(rawValue: "NSURLLocalizedNameKey")
public static let isRegularFileKey = URLResourceKey(rawValue: "NSURLIsRegularFileKey")
public static let isDirectoryKey = URLResourceKey(rawValue: "NSURLIsDirectoryKey")
public static let isSymbolicLinkKey = URLResourceKey(rawValue: "NSURLIsSymbolicLinkKey")
public static let isVolumeKey = URLResourceKey(rawValue: "NSURLIsVolumeKey")
public static let isPackageKey = URLResourceKey(rawValue: "NSURLIsPackageKey")
public static let isApplicationKey = URLResourceKey(rawValue: "NSURLIsApplicationKey")
public static let applicationIsScriptableKey = URLResourceKey(rawValue: "NSURLApplicationIsScriptableKey")
public static let isSystemImmutableKey = URLResourceKey(rawValue: "NSURLIsSystemImmutableKey")
public static let isUserImmutableKey = URLResourceKey(rawValue: "NSURLIsUserImmutableKey")
public static let isHiddenKey = URLResourceKey(rawValue: "NSURLIsHiddenKey")
public static let hasHiddenExtensionKey = URLResourceKey(rawValue: "NSURLHasHiddenExtensionKey")
public static let creationDateKey = URLResourceKey(rawValue: "NSURLCreationDateKey")
public static let contentAccessDateKey = URLResourceKey(rawValue: "NSURLContentAccessDateKey")
public static let contentModificationDateKey = URLResourceKey(rawValue: "NSURLContentModificationDateKey")
public static let attributeModificationDateKey = URLResourceKey(rawValue: "NSURLAttributeModificationDateKey")
public static let linkCountKey = URLResourceKey(rawValue: "NSURLLinkCountKey")
public static let parentDirectoryURLKey = URLResourceKey(rawValue: "NSURLParentDirectoryURLKey")
public static let volumeURLKey = URLResourceKey(rawValue: "NSURLVolumeURLKey")
public static let typeIdentifierKey = URLResourceKey(rawValue: "NSURLTypeIdentifierKey")
public static let localizedTypeDescriptionKey = URLResourceKey(rawValue: "NSURLLocalizedTypeDescriptionKey")
public static let labelNumberKey = URLResourceKey(rawValue: "NSURLLabelNumberKey")
public static let labelColorKey = URLResourceKey(rawValue: "NSURLLabelColorKey")
public static let localizedLabelKey = URLResourceKey(rawValue: "NSURLLocalizedLabelKey")
public static let effectiveIconKey = URLResourceKey(rawValue: "NSURLEffectiveIconKey")
public static let customIconKey = URLResourceKey(rawValue: "NSURLCustomIconKey")
public static let fileResourceIdentifierKey = URLResourceKey(rawValue: "NSURLFileResourceIdentifierKey")
public static let volumeIdentifierKey = URLResourceKey(rawValue: "NSURLVolumeIdentifierKey")
public static let preferredIOBlockSizeKey = URLResourceKey(rawValue: "NSURLPreferredIOBlockSizeKey")
public static let isReadableKey = URLResourceKey(rawValue: "NSURLIsReadableKey")
public static let isWritableKey = URLResourceKey(rawValue: "NSURLIsWritableKey")
public static let isExecutableKey = URLResourceKey(rawValue: "NSURLIsExecutableKey")
public static let fileSecurityKey = URLResourceKey(rawValue: "NSURLFileSecurityKey")
public static let isExcludedFromBackupKey = URLResourceKey(rawValue: "NSURLIsExcludedFromBackupKey")
public static let tagNamesKey = URLResourceKey(rawValue: "NSURLTagNamesKey")
public static let pathKey = URLResourceKey(rawValue: "NSURLPathKey")
public static let canonicalPathKey = URLResourceKey(rawValue: "NSURLCanonicalPathKey")
public static let isMountTriggerKey = URLResourceKey(rawValue: "NSURLIsMountTriggerKey")
public static let generationIdentifierKey = URLResourceKey(rawValue: "NSURLGenerationIdentifierKey")
public static let documentIdentifierKey = URLResourceKey(rawValue: "NSURLDocumentIdentifierKey")
public static let addedToDirectoryDateKey = URLResourceKey(rawValue: "NSURLAddedToDirectoryDateKey")
public static let quarantinePropertiesKey = URLResourceKey(rawValue: "NSURLQuarantinePropertiesKey")
public static let fileResourceTypeKey = URLResourceKey(rawValue: "NSURLFileResourceTypeKey")
public static let thumbnailDictionaryKey = URLResourceKey(rawValue: "NSURLThumbnailDictionaryKey")
public static let thumbnailKey = URLResourceKey(rawValue: "NSURLThumbnailKey")
public static let fileSizeKey = URLResourceKey(rawValue: "NSURLFileSizeKey")
public static let fileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLFileAllocatedSizeKey")
public static let totalFileSizeKey = URLResourceKey(rawValue: "NSURLTotalFileSizeKey")
public static let totalFileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLTotalFileAllocatedSizeKey")
public static let isAliasFileKey = URLResourceKey(rawValue: "NSURLIsAliasFileKey")
public static let volumeLocalizedFormatDescriptionKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedFormatDescriptionKey")
public static let volumeTotalCapacityKey = URLResourceKey(rawValue: "NSURLVolumeTotalCapacityKey")
public static let volumeAvailableCapacityKey = URLResourceKey(rawValue: "NSURLVolumeAvailableCapacityKey")
public static let volumeResourceCountKey = URLResourceKey(rawValue: "NSURLVolumeResourceCountKey")
public static let volumeSupportsPersistentIDsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsPersistentIDsKey")
public static let volumeSupportsSymbolicLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSymbolicLinksKey")
public static let volumeSupportsHardLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsHardLinksKey")
public static let volumeSupportsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsJournalingKey")
public static let volumeIsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeIsJournalingKey")
public static let volumeSupportsSparseFilesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSparseFilesKey")
public static let volumeSupportsZeroRunsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsZeroRunsKey")
public static let volumeSupportsCaseSensitiveNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCaseSensitiveNamesKey")
public static let volumeSupportsCasePreservedNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCasePreservedNamesKey")
public static let volumeSupportsRootDirectoryDatesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRootDirectoryDatesKey")
public static let volumeSupportsVolumeSizesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsVolumeSizesKey")
public static let volumeSupportsRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRenamingKey")
public static let volumeSupportsAdvisoryFileLockingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsAdvisoryFileLockingKey")
public static let volumeSupportsExtendedSecurityKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExtendedSecurityKey")
public static let volumeIsBrowsableKey = URLResourceKey(rawValue: "NSURLVolumeIsBrowsableKey")
public static let volumeMaximumFileSizeKey = URLResourceKey(rawValue: "NSURLVolumeMaximumFileSizeKey")
public static let volumeIsEjectableKey = URLResourceKey(rawValue: "NSURLVolumeIsEjectableKey")
public static let volumeIsRemovableKey = URLResourceKey(rawValue: "NSURLVolumeIsRemovableKey")
public static let volumeIsInternalKey = URLResourceKey(rawValue: "NSURLVolumeIsInternalKey")
public static let volumeIsAutomountedKey = URLResourceKey(rawValue: "NSURLVolumeIsAutomountedKey")
public static let volumeIsLocalKey = URLResourceKey(rawValue: "NSURLVolumeIsLocalKey")
public static let volumeIsReadOnlyKey = URLResourceKey(rawValue: "NSURLVolumeIsReadOnlyKey")
public static let volumeCreationDateKey = URLResourceKey(rawValue: "NSURLVolumeCreationDateKey")
public static let volumeURLForRemountingKey = URLResourceKey(rawValue: "NSURLVolumeURLForRemountingKey")
public static let volumeUUIDStringKey = URLResourceKey(rawValue: "NSURLVolumeUUIDStringKey")
public static let volumeNameKey = URLResourceKey(rawValue: "NSURLVolumeNameKey")
public static let volumeLocalizedNameKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedNameKey")
public static let volumeIsEncryptedKey = URLResourceKey(rawValue: "NSURLVolumeIsEncryptedKey")
public static let volumeIsRootFileSystemKey = URLResourceKey(rawValue: "NSURLVolumeIsRootFileSystemKey")
public static let volumeSupportsCompressionKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCompressionKey")
public static let volumeSupportsFileCloningKey = URLResourceKey(rawValue: "NSURLVolumeSupportsFileCloningKey")
public static let volumeSupportsSwapRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSwapRenamingKey")
public static let volumeSupportsExclusiveRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExclusiveRenamingKey")
public static let isUbiquitousItemKey = URLResourceKey(rawValue: "NSURLIsUbiquitousItemKey")
public static let ubiquitousItemHasUnresolvedConflictsKey = URLResourceKey(rawValue: "NSURLUbiquitousItemHasUnresolvedConflictsKey")
public static let ubiquitousItemIsDownloadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsDownloadingKey")
public static let ubiquitousItemIsUploadedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadedKey")
public static let ubiquitousItemIsUploadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadingKey")
public static let ubiquitousItemDownloadingStatusKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingStatusKey")
public static let ubiquitousItemDownloadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingErrorKey")
public static let ubiquitousItemUploadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemUploadingErrorKey")
public static let ubiquitousItemDownloadRequestedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadRequestedKey")
public static let ubiquitousItemContainerDisplayNameKey = URLResourceKey(rawValue: "NSURLUbiquitousItemContainerDisplayNameKey")
}
public struct URLFileResourceType : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: URLFileResourceType, rhs: URLFileResourceType) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension URLFileResourceType {
public static let namedPipe = URLFileResourceType(rawValue: "NSURLFileResourceTypeNamedPipe")
public static let characterSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeCharacterSpecial")
public static let directory = URLFileResourceType(rawValue: "NSURLFileResourceTypeDirectory")
public static let blockSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeBlockSpecial")
public static let regular = URLFileResourceType(rawValue: "NSURLFileResourceTypeRegular")
public static let symbolicLink = URLFileResourceType(rawValue: "NSURLFileResourceTypeSymbolicLink")
public static let socket = URLFileResourceType(rawValue: "NSURLFileResourceTypeSocket")
public static let unknown = URLFileResourceType(rawValue: "NSURLFileResourceTypeUnknown")
}
open class NSURL : NSObject, NSSecureCoding, NSCopying {
typealias CFType = CFURL
internal var _base = _CFInfo(typeID: CFURLGetTypeID())
internal var _flags : UInt32 = 0
internal var _encoding : CFStringEncoding = 0
internal var _string : UnsafeMutablePointer<CFString>? = nil
internal var _baseURL : UnsafeMutablePointer<CFURL>? = nil
internal var _extra : OpaquePointer? = nil
internal var _resourceInfo : OpaquePointer? = nil
internal var _range1 = NSRange(location: 0, length: 0)
internal var _range2 = NSRange(location: 0, length: 0)
internal var _range3 = NSRange(location: 0, length: 0)
internal var _range4 = NSRange(location: 0, length: 0)
internal var _range5 = NSRange(location: 0, length: 0)
internal var _range6 = NSRange(location: 0, length: 0)
internal var _range7 = NSRange(location: 0, length: 0)
internal var _range8 = NSRange(location: 0, length: 0)
internal var _range9 = NSRange(location: 0, length: 0)
internal var _cfObject : CFType {
if type(of: self) === NSURL.self {
return unsafeBitCast(self, to: CFType.self)
} else {
return CFURLCreateWithString(kCFAllocatorSystemDefault, relativeString._cfObject, self.baseURL?._cfObject)
}
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURL else { return false }
return CFEqual(_cfObject, other._cfObject)
}
open override var description: String {
return self.absoluteString
}
deinit {
_CFDeinit(self)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool { return true }
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let base = aDecoder.decodeObject(of: NSURL.self, forKey:"NS.base")?._swiftObject
let relative = aDecoder.decodeObject(of: NSString.self, forKey:"NS.relative")
if relative == nil {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(relative!), relativeTo: base)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.baseURL?._nsObject, forKey:"NS.base")
aCoder.encode(self.relativeString._bridgeToObjectiveC(), forKey:"NS.relative")
}
public init(fileURLWithPath path: String, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
super.init()
let thePath = _standardizedPath(path)
if thePath.length > 0 {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir, baseURL?._cfObject)
} else if let baseURL = baseURL {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, baseURL.path._cfObject, kCFURLPOSIXPathStyle, baseURL.hasDirectoryPath, nil)
}
}
public convenience init(fileURLWithPath path: String, relativeTo baseURL: URL?) {
let thePath = _standardizedPath(path)
var isDir: ObjCBool = false
if thePath.hasSuffix("/") {
isDir = true
} else {
let absolutePath: String
if let absPath = baseURL?.appendingPathComponent(path).path {
absolutePath = absPath
} else {
absolutePath = path
}
let _ = FileManager.default.fileExists(atPath: absolutePath, isDirectory: &isDir)
}
self.init(fileURLWithPath: thePath, isDirectory: isDir.boolValue, relativeTo: baseURL)
}
public convenience init(fileURLWithPath path: String, isDirectory isDir: Bool) {
self.init(fileURLWithPath: path, isDirectory: isDir, relativeTo: nil)
}
public init(fileURLWithPath path: String) {
let thePath: String
let pathString = NSString(string: path)
if !pathString.isAbsolutePath {
thePath = pathString.standardizingPath
} else {
thePath = path
}
var isDir: ObjCBool = false
if thePath.hasSuffix("/") {
isDir = true
} else {
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
isDir = false
}
}
super.init()
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir.boolValue, nil)
}
public convenience init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
let pathString = String(cString: path)
self.init(fileURLWithPath: pathString, isDirectory: isDir, relativeTo: baseURL)
}
public convenience init?(string URLString: String) {
self.init(string: URLString, relativeTo:nil)
}
public init?(string URLString: String, relativeTo baseURL: URL?) {
super.init()
if !_CFURLInitWithURLString(_cfObject, URLString._cfObject, true, baseURL?._cfObject) {
return nil
}
}
public init(dataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
// _CFURLInitWithURLString does not fail if checkForLegalCharacters == false
data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else {
fatalError()
}
}
}
public init(absoluteURLWithDataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), baseURL?._cfObject) {
return
}
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), baseURL?._cfObject) {
return
}
fatalError()
}
}
/* Returns the data representation of the URL's relativeString. If the URL was initialized with -initWithData:relativeTo:, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the relativeString encoded with NSUTF8StringEncoding.
*/
open var dataRepresentation: Data {
let bytesNeeded = CFURLGetBytes(_cfObject, nil, 0)
assert(bytesNeeded > 0)
let buffer = malloc(bytesNeeded)!.bindMemory(to: UInt8.self, capacity: bytesNeeded)
let bytesFilled = CFURLGetBytes(_cfObject, buffer, bytesNeeded)
if bytesFilled == bytesNeeded {
return Data(bytesNoCopy: buffer, count: bytesNeeded, deallocator: .free)
} else {
fatalError()
}
}
open var absoluteString: String {
if let absURL = CFURLCopyAbsoluteURL(_cfObject) {
return CFURLGetString(absURL)._swiftObject
}
return CFURLGetString(_cfObject)._swiftObject
}
// The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString
open var relativeString: String {
return CFURLGetString(_cfObject)._swiftObject
}
open var baseURL: URL? {
return CFURLGetBaseURL(_cfObject)?._swiftObject
}
// if the receiver is itself absolute, this will return self.
open var absoluteURL: URL? {
return CFURLCopyAbsoluteURL(_cfObject)?._swiftObject
}
/* Any URL is composed of these two basic pieces. The full URL would be the concatenation of [myURL scheme], ':', [myURL resourceSpecifier]
*/
open var scheme: String? {
return CFURLCopyScheme(_cfObject)?._swiftObject
}
internal var _isAbsolute : Bool {
return self.baseURL == nil && self.scheme != nil
}
open var resourceSpecifier: String? {
// Note that this does NOT have the same meaning as CFURL's resource specifier, which, for decomposeable URLs is merely that portion of the URL which comes after the path. NSURL means everything after the scheme.
if !_isAbsolute {
return self.relativeString
} else {
let cf = _cfObject
guard CFURLCanBeDecomposed(cf) else {
return CFURLCopyResourceSpecifier(cf)?._swiftObject
}
guard baseURL == nil else {
return CFURLGetString(cf)?._swiftObject
}
let netLoc = CFURLCopyNetLocation(cf)?._swiftObject
let path = CFURLCopyPath(cf)?._swiftObject
let theRest = CFURLCopyResourceSpecifier(cf)?._swiftObject
if let netLoc = netLoc {
let p = path ?? ""
let rest = theRest ?? ""
return "//\(netLoc)\(p)\(rest)"
} else if let path = path {
let rest = theRest ?? ""
return "\(path)\(rest)"
} else {
return theRest
}
}
}
/* If the URL conforms to rfc 1808 (the most common form of URL), the following accessors will return the various components; otherwise they return nil. The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is @"//". In all cases, they return the component's value after resolving the receiver against its base URL.
*/
open var host: String? {
return CFURLCopyHostName(_cfObject)?._swiftObject
}
open var port: NSNumber? {
let port = CFURLGetPortNumber(_cfObject)
if port == -1 {
return nil
} else {
return NSNumber(value: port)
}
}
open var user: String? {
return CFURLCopyUserName(_cfObject)?._swiftObject
}
open var password: String? {
let absoluteURL = CFURLCopyAbsoluteURL(_cfObject)
#if os(Linux) || os(Android) || CYGWIN
let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, kCFURLComponentPassword, nil)
#else
let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, .password, nil)
#endif
guard passwordRange.location != kCFNotFound else {
return nil
}
// For historical reasons, the password string should _not_ have its percent escapes removed.
let bufSize = CFURLGetBytes(absoluteURL, nil, 0)
var buf = [UInt8](repeating: 0, count: bufSize)
guard CFURLGetBytes(absoluteURL, &buf, bufSize) >= 0 else {
return nil
}
let passwordBuf = buf[passwordRange.location ..< passwordRange.location+passwordRange.length]
return passwordBuf.withUnsafeBufferPointer { ptr in
NSString(bytes: ptr.baseAddress!, length: passwordBuf.count, encoding: String.Encoding.utf8.rawValue)?._swiftObject
}
}
open var path: String? {
let absURL = CFURLCopyAbsoluteURL(_cfObject)
return CFURLCopyFileSystemPath(absURL, kCFURLPOSIXPathStyle)?._swiftObject
}
open var fragment: String? {
return CFURLCopyFragment(_cfObject, nil)?._swiftObject
}
open var parameterString: String? {
return CFURLCopyParameterString(_cfObject, nil)?._swiftObject
}
open var query: String? {
return CFURLCopyQueryString(_cfObject, nil)?._swiftObject
}
// The same as path if baseURL is nil
open var relativePath: String? {
return CFURLCopyFileSystemPath(_cfObject, kCFURLPOSIXPathStyle)?._swiftObject
}
/* Determines if a given URL string's path represents a directory (i.e. the path component in the URL string ends with a '/' character). This does not check the resource the URL refers to.
*/
open var hasDirectoryPath: Bool {
return CFURLHasDirectoryPath(_cfObject)
}
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding.
*/
open func getFileSystemRepresentation(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferLength: Int) -> Bool {
return buffer.withMemoryRebound(to: UInt8.self, capacity: maxBufferLength) {
CFURLGetFileSystemRepresentation(_cfObject, true, $0, maxBufferLength)
}
}
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength: if it needs to store the representation outside of the autorelease context in which the representation is created.
*/
// Memory leak. See https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/Issues.md
open var fileSystemRepresentation: UnsafePointer<Int8> {
let bufSize = Int(PATH_MAX + 1)
let _fsrBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: bufSize)
for i in 0..<bufSize {
_fsrBuffer.advanced(by: i).initialize(to: 0)
}
if getFileSystemRepresentation(_fsrBuffer, maxLength: bufSize) {
return UnsafePointer(_fsrBuffer)
}
// FIXME: This used to return nil, but the corresponding Darwin
// implementation is marked as non-nullable.
fatalError("URL cannot be expressed in the filesystem representation;" +
"use getFileSystemRepresentation to handle this case")
}
// Whether the scheme is file:; if myURL.isFileURL is true, then myURL.path is suitable for input into FileManager or NSPathUtilities.
open var isFileURL: Bool {
return _CFURLIsFileURL(_cfObject)
}
/* A string constant for the "file" URL scheme. If you are using this to compare to a URL's scheme to see if it is a file URL, you should instead use the NSURL fileURL property -- the fileURL property is much faster. */
open var standardized: URL? {
guard (path != nil) else {
return nil
}
let URLComponents = NSURLComponents(string: relativeString)
guard ((URLComponents != nil) && (URLComponents!.path != nil)) else {
return nil
}
guard (URLComponents!.path!.contains("..") || URLComponents!.path!.contains(".")) else{
return URLComponents!.url(relativeTo: baseURL)
}
URLComponents!.path! = _pathByRemovingDots(pathComponents!)
return URLComponents!.url(relativeTo: baseURL)
}
/* Returns whether the URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. If this method returns NO, the optional error is populated. This method is currently applicable only to URLs for file system resources. For other URL types, NO is returned. Symbol is present in iOS 4, but performs no operation.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
// TODO: should be `checkResourceIsReachableAndReturnError` with autoreleased error parameter.
// Currently Autoreleased pointers is not supported on Linux.
open func checkResourceIsReachable() throws -> Bool {
guard isFileURL,
let path = path else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileNoSuchFile.rawValue)
//return false
}
guard FileManager.default.fileExists(atPath: path) else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileReadNoSuchFile.rawValue,
userInfo: [
"NSURL" : self,
"NSFilePath" : path])
//return false
}
return true
}
/* Returns a file path URL that refers to the same resource as a specified URL. File path URLs use a file system style path. An error will occur if the url parameter is not a file URL. A file reference URL's resource must exist and be reachable to be converted to a file path URL. Symbol is present in iOS 4, but performs no operation.
*/
open var filePathURL: URL? {
guard isFileURL else {
return nil
}
return URL(string: absoluteString)
}
override open var _cfTypeID: CFTypeID {
return CFURLGetTypeID()
}
open func removeAllCachedResourceValues() { NSUnimplemented() }
open func removeCachedResourceValue(forKey key: URLResourceKey) { NSUnimplemented() }
open func resourceValues(forKeys keys: [URLResourceKey]) throws -> [URLResourceKey : Any] { NSUnimplemented() }
open func setResourceValue(_ value: Any?, forKey key: URLResourceKey) throws { NSUnimplemented() }
open func setResourceValues(_ keyedValues: [URLResourceKey : Any]) throws { NSUnimplemented() }
open func setTemporaryResourceValue(_ value: Any?, forKey key: URLResourceKey) { NSUnimplemented() }
}
extension NSCharacterSet {
// Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.
// Returns a character set containing the characters allowed in an URL's user subcomponent.
open class var urlUserAllowed: CharacterSet {
return _CFURLComponentsGetURLUserAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's password subcomponent.
open class var urlPasswordAllowed: CharacterSet {
return _CFURLComponentsGetURLPasswordAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's host subcomponent.
open class var urlHostAllowed: CharacterSet {
return _CFURLComponentsGetURLHostAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's path component. ';' is a legal path character, but it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet).
open class var urlPathAllowed: CharacterSet {
return _CFURLComponentsGetURLPathAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's query component.
open class var urlQueryAllowed: CharacterSet {
return _CFURLComponentsGetURLQueryAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's fragment component.
open class var urlFragmentAllowed: CharacterSet {
return _CFURLComponentsGetURLFragmentAllowedCharacterSet()._swiftObject
}
}
extension NSString {
// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
open func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String? {
return _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, self._cfObject, allowedCharacters._cfObject)._swiftObject
}
// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
open var removingPercentEncoding: String? {
return _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, self._cfObject)?._swiftObject
}
}
extension NSURL {
/* The following methods work on the path portion of a URL in the same manner that the NSPathUtilities methods on NSString do.
*/
open class func fileURL(withPathComponents components: [String]) -> URL? {
let path = NSString.pathWithComponents(components)
if components.last == "/" {
return URL(fileURLWithPath: path, isDirectory: true)
} else {
return URL(fileURLWithPath: path)
}
}
internal func _pathByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String? {
guard let p = path else {
return nil
}
if p == "/" {
return p
}
var result = p
if compress {
let startPos = result.startIndex
var endPos = result.endIndex
var curPos = startPos
while curPos < endPos {
if result[curPos] == "/" {
var afterLastSlashPos = curPos
while afterLastSlashPos < endPos && result[afterLastSlashPos] == "/" {
afterLastSlashPos = result.index(after: afterLastSlashPos)
}
if afterLastSlashPos != result.index(after: curPos) {
result.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"])
endPos = result.endIndex
}
curPos = afterLastSlashPos
} else {
curPos = result.index(after: curPos)
}
}
}
if stripTrailing && result.hasSuffix("/") {
result.remove(at: result.index(before: result.endIndex))
}
return result
}
open var pathComponents: [String]? {
return _pathComponents(path)
}
open var lastPathComponent: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return fixedSelf
}
return String(fixedSelf.suffix(from: fixedSelf._startOfLastPathComponent))
}
open var pathExtension: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return ""
}
if let extensionPos = fixedSelf._startOfPathExtension {
return String(fixedSelf.suffix(from: extensionPos))
} else {
return ""
}
}
open func appendingPathComponent(_ pathComponent: String) -> URL? {
var result : URL? = appendingPathComponent(pathComponent, isDirectory: false)
if !pathComponent.hasSuffix("/") && isFileURL {
if let urlWithoutDirectory = result {
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: urlWithoutDirectory.path, isDirectory: &isDir) && isDir.boolValue {
result = self.appendingPathComponent(pathComponent, isDirectory: true)
}
}
}
return result
}
open func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL? {
return CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, _cfObject, pathComponent._cfObject, isDirectory)?._swiftObject
}
open var deletingLastPathComponent: URL? {
return CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
open func appendingPathExtension(_ pathExtension: String) -> URL? {
return CFURLCreateCopyAppendingPathExtension(kCFAllocatorSystemDefault, _cfObject, pathExtension._cfObject)?._swiftObject
}
open var deletingPathExtension: URL? {
return CFURLCreateCopyDeletingPathExtension(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
/* The following methods work only on `file:` scheme URLs; for non-`file:` scheme URLs, these methods return the URL unchanged.
*/
open var standardizingPath: URL? {
// Documentation says it should expand initial tilde, but it does't do this on OS X.
// In remaining cases it works just like URLByResolvingSymlinksInPath.
return resolvingSymlinksInPath
}
open var resolvingSymlinksInPath: URL? {
return _resolveSymlinksInPath(excludeSystemDirs: true)
}
internal func _resolveSymlinksInPath(excludeSystemDirs: Bool) -> URL? {
guard isFileURL else {
return URL(string: absoluteString)
}
guard let selfPath = path else {
return URL(string: absoluteString)
}
let absolutePath: String
if selfPath.hasPrefix("/") {
absolutePath = selfPath
} else {
let workingDir = FileManager.default.currentDirectoryPath
absolutePath = workingDir._bridgeToObjectiveC().appendingPathComponent(selfPath)
}
var components = URL(fileURLWithPath: absolutePath).pathComponents
guard !components.isEmpty else {
return URL(string: absoluteString)
}
var resolvedPath = components.removeFirst()
for component in components {
switch component {
case "", ".":
break
case "..":
resolvedPath = resolvedPath._bridgeToObjectiveC().deletingLastPathComponent
default:
resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component)
if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) {
resolvedPath = destination
}
}
}
// It might be a responsibility of NSURL(fileURLWithPath:). Check it.
var isExistingDirectory: ObjCBool = false
let _ = FileManager.default.fileExists(atPath: resolvedPath, isDirectory: &isExistingDirectory)
if excludeSystemDirs {
resolvedPath = resolvedPath._tryToRemovePathPrefix("/private") ?? resolvedPath
}
if isExistingDirectory.boolValue && !resolvedPath.hasSuffix("/") {
resolvedPath += "/"
}
return URL(fileURLWithPath: resolvedPath)
}
fileprivate func _pathByRemovingDots(_ comps: [String]) -> String {
var components = comps
if(components.last == "/") {
components.removeLast()
}
guard !components.isEmpty else {
return self.path!
}
let isAbsolutePath = components.first == "/"
var result : String = components.removeFirst()
for component in components {
switch component {
case ".":
break
case ".." where isAbsolutePath:
result = result._bridgeToObjectiveC().deletingLastPathComponent
default:
result = result._bridgeToObjectiveC().appendingPathComponent(component)
}
}
if(self.path!.hasSuffix("/")) {
result += "/"
}
return result
}
}
// NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property.
open class NSURLQueryItem : NSObject, NSSecureCoding, NSCopying {
public init(name: String, value: String?) {
self.name = name
self.value = value
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
required public init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let encodedName = aDecoder.decodeObject(forKey: "NS.name") as! NSString
self.name = encodedName._swiftObject
let encodedValue = aDecoder.decodeObject(forKey: "NS.value") as? NSString
self.value = encodedValue?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.name._bridgeToObjectiveC(), forKey: "NS.name")
aCoder.encode(self.value?._bridgeToObjectiveC(), forKey: "NS.value")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLQueryItem else { return false }
return other === self
|| (other.name == self.name
&& other.value == self.value)
}
open let name: String
open let value: String?
}
open class NSURLComponents: NSObject, NSCopying {
private let _components : CFURLComponentsRef!
deinit {
if let component = _components {
__CFURLComponentsDeallocate(component)
}
}
open override func copy() -> Any {
return copy(with: nil)
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLComponents else { return false }
return self === other
|| (scheme == other.scheme
&& user == other.user
&& password == other.password
&& host == other.host
&& port == other.port
&& path == other.path
&& query == other.query
&& fragment == other.fragment)
}
open func copy(with zone: NSZone? = nil) -> Any {
let copy = NSURLComponents()
copy.scheme = self.scheme
copy.user = self.user
copy.password = self.password
copy.host = self.host
copy.port = self.port
copy.path = self.path
copy.query = self.query
copy.fragment = self.fragment
return copy
}
// Initialize a NSURLComponents with the components of a URL. If resolvingAgainstBaseURL is YES and url is a relative URL, the components of [url absoluteURL] are used. If the url string from the NSURL is malformed, nil is returned.
public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {
_components = _CFURLComponentsCreateWithURL(kCFAllocatorSystemDefault, url._cfObject, resolve)
super.init()
if _components == nil {
return nil
}
}
// Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned.
public init?(string URLString: String) {
_components = _CFURLComponentsCreateWithString(kCFAllocatorSystemDefault, URLString._cfObject)
super.init()
if _components == nil {
return nil
}
}
public override init() {
_components = _CFURLComponentsCreate(kCFAllocatorSystemDefault)
}
// Returns a URL created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var url: URL? {
guard let result = _CFURLComponentsCopyURL(_components) else { return nil }
return unsafeBitCast(result, to: URL.self)
}
// Returns a URL created from the NSURLComponents relative to a base URL. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open func url(relativeTo baseURL: URL?) -> URL? {
if let componentString = string {
return URL(string: componentString, relativeTo: baseURL)
}
return nil
}
// Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var string: String? {
return _CFURLComponentsCopyString(_components)?._swiftObject
}
// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
// Getting these properties removes any percent encoding these components may have (if the component allows percent encoding). Setting these properties assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
// Attempting to set the scheme with an invalid scheme string will cause an exception.
open var scheme: String? {
get {
return _CFURLComponentsCopyScheme(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetScheme(_components, new?._cfObject) {
fatalError()
}
}
}
open var user: String? {
get {
return _CFURLComponentsCopyUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var password: String? {
get {
return _CFURLComponentsCopyPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var host: String? {
get {
return _CFURLComponentsCopyHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetHost(_components, new?._cfObject) {
fatalError()
}
}
}
// Attempting to set a negative port number will cause an exception.
open var port: NSNumber? {
get {
if let result = _CFURLComponentsCopyPort(_components) {
return unsafeBitCast(result, to: NSNumber.self)
} else {
return nil
}
}
set(new) {
if !_CFURLComponentsSetPort(_components, new?._cfObject) {
fatalError()
}
}
}
open var path: String? {
get {
return _CFURLComponentsCopyPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var query: String? {
get {
return _CFURLComponentsCopyQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var fragment: String? {
get {
return _CFURLComponentsCopyFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetFragment(_components, new?._cfObject) {
fatalError()
}
}
}
// Getting these properties retains any percent encoding these components may have. Setting these properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause an exception. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the urlPathAllowed).
open var percentEncodedUser: String? {
get {
return _CFURLComponentsCopyPercentEncodedUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPassword: String? {
get {
return _CFURLComponentsCopyPercentEncodedPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedHost: String? {
get {
return _CFURLComponentsCopyPercentEncodedHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedHost(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPath: String? {
get {
return _CFURLComponentsCopyPercentEncodedPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedQuery: String? {
get {
return _CFURLComponentsCopyPercentEncodedQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedFragment: String? {
get {
return _CFURLComponentsCopyPercentEncodedFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedFragment(_components, new?._cfObject) {
fatalError()
}
}
}
/* These properties return the character range of a component in the URL string returned by -[NSURLComponents string]. If the component does not exist in the NSURLComponents object, {NSNotFound, 0} is returned. Note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
*/
open var rangeOfScheme: NSRange {
return NSRange(_CFURLComponentsGetRangeOfScheme(_components))
}
open var rangeOfUser: NSRange {
return NSRange(_CFURLComponentsGetRangeOfUser(_components))
}
open var rangeOfPassword: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPassword(_components))
}
open var rangeOfHost: NSRange {
return NSRange(_CFURLComponentsGetRangeOfHost(_components))
}
open var rangeOfPort: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPort(_components))
}
open var rangeOfPath: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPath(_components))
}
open var rangeOfQuery: NSRange {
return NSRange(_CFURLComponentsGetRangeOfQuery(_components))
}
open var rangeOfFragment: NSRange {
return NSRange(_CFURLComponentsGetRangeOfFragment(_components))
}
// The getter method that underlies the queryItems property parses the query string based on these delimiters and returns an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string. Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the NSURLComponents object has an empty query component, queryItems returns an empty NSArray. If the NSURLComponents object has no query component, queryItems returns nil.
// The setter method that underlies the queryItems property combines an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, into a query string and sets the NSURLComponents' query property. Passing an empty NSArray to setQueryItems sets the query component of the NSURLComponents object to an empty string. Passing nil to setQueryItems removes the query component of the NSURLComponents object.
// Note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a NSURLQueryItem with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
open var queryItems: [URLQueryItem]? {
get {
// This CFURL implementation returns a CFArray of CFDictionary; each CFDictionary has an entry for name and optionally an entry for value
guard let queryArray = _CFURLComponentsCopyQueryItems(_components) else {
return nil
}
let count = CFArrayGetCount(queryArray)
return (0..<count).map { idx in
let oneEntry = unsafeBitCast(CFArrayGetValueAtIndex(queryArray, idx), to: NSDictionary.self)
let swiftEntry = oneEntry._swiftObject
let entryName = swiftEntry["name"] as! String
let entryValue = swiftEntry["value"] as? String
return URLQueryItem(name: entryName, value: entryValue)
}
}
set(new) {
guard let new = new else {
self.percentEncodedQuery = nil
return
}
// The CFURL implementation requires two CFArrays, one for names and one for values
var names = [CFTypeRef]()
var values = [CFTypeRef]()
for entry in new {
names.append(entry.name._cfObject)
if let v = entry.value {
values.append(v._cfObject)
} else {
values.append(kCFNull)
}
}
_CFURLComponentsSetQueryItems(_components, names._cfObject, values._cfObject)
}
}
}
extension NSURL: _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = URL
internal var _swiftObject: SwiftType { return URL(reference: self) }
}
extension CFURL : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSURL
typealias SwiftType = URL
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
internal var _swiftObject: SwiftType { return _nsObject._swiftObject }
}
extension URL : _NSBridgeable, _CFBridgeable {
typealias NSType = NSURL
typealias CFType = CFURL
internal var _nsObject: NSType { return self.reference }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
extension NSURL : _StructTypeBridgeable {
public typealias _StructType = URL
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLComponents : _StructTypeBridgeable {
public typealias _StructType = URLComponents
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLQueryItem : _StructTypeBridgeable {
public typealias _StructType = URLQueryItem
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 4f4b8ea2d8a917ffe593ae5780ab4640 | 44.303099 | 740 | 0.675087 | 5.550144 | false | false | false | false |
manuelbl/WirekiteMac | WirekiteMacTest/Controllers/OLEDDisplay.swift | 1 | 6955 | //
// Wirekite for MacOS
//
// Copyright (c) 2017 Manuel Bleichenbacher
// Licensed under MIT License
// https://opensource.org/licenses/MIT
//
import CoreFoundation
import Cocoa
/**
OLED display with SH1306 or SH1106 chip and I2C communication.
*/
class OLEDDisplay {
private static let SetContrast: UInt8 = 0x81
private static let OutputRAMToDisplay: UInt8 = 0xA4
private static let SetDisplayOn: UInt8 = 0xA5
private static let SetNormalDisplay: UInt8 = 0xA6
private static let SetInvertedDisplay: UInt8 = 0xA7
private static let DisplayOff: UInt8 = 0xAE
private static let DisplayOn: UInt8 = 0xAF
private static let SetDisplayOffset: UInt8 = 0xD3
private static let SetComPin: UInt8 = 0xDA
private static let SetVCOMH: UInt8 = 0xDB
private static let SetClockDivideRatio: UInt8 = 0xD5
private static let SetPrecharge: UInt8 = 0xD9
private static let SetMultiplexRatio: UInt8 = 0xA8
private static let SetColumnAddressLow: UInt8 = 0x00
private static let SetColumnAddressHigh: UInt8 = 0x10
private static let SetPageAddress: UInt8 = 0xb0
private static let SetStartLineBase: UInt8 = 0x40
private static let PageAddressingMode: UInt8 = 0x20
private static let ScanDirectionIncreasing: UInt8 = 0xC0
private static let ScanDirectionDecreasing: UInt8 = 0xC8
private static let SegmentRampBase: UInt8 = 0xA0
private static let ChargePump: UInt8 = 0x8D
private static let DeactivateScroll: UInt8 = 0x2E
private let device: WirekiteDevice?
private let i2cPort: PortID
private var isInitialized = false
private var offset = 0
/** I2C slave address */
var displayAddress: Int = 0x3C
/** Display width (in pixel) */
let Width = 128
/** Display height (in pixel) */
let Height = 64
/**
Horizontal display offset (in pixel)
Use 0 for SH1306 chip, 2 for SH1106 chip.
*/
var DisplayOffset = 0
private var graphics: GraphicsBuffer?
init(device: WirekiteDevice, i2cPort: PortID) {
self.device = device
self.i2cPort = i2cPort
}
private func initSensor(retries: Int) {
// Init sequence
let initSequence: [UInt8] = [
0x80, OLEDDisplay.DisplayOff,
0x80, OLEDDisplay.SetClockDivideRatio, 0x80, 0x80,
0x80, OLEDDisplay.SetMultiplexRatio, 0x80, 0x3f,
0x80, OLEDDisplay.SetDisplayOffset, 0x80, 0x0,
0x80, OLEDDisplay.SetStartLineBase + 0,
0x80, OLEDDisplay.ChargePump, 0x80, 0x14,
0x80, OLEDDisplay.PageAddressingMode, 0x80, 0x00,
0x80, OLEDDisplay.SegmentRampBase + 0x1,
0x80, OLEDDisplay.ScanDirectionDecreasing,
0x80, OLEDDisplay.SetComPin, 0x80, 0x12,
0x80, OLEDDisplay.SetContrast, 0x80, 0xcf,
0x80, OLEDDisplay.SetPrecharge, 0x80, 0xF1,
0x80, OLEDDisplay.SetVCOMH, 0x80, 0x40,
0x80, OLEDDisplay.DeactivateScroll,
0x80, OLEDDisplay.OutputRAMToDisplay,
0x80, OLEDDisplay.SetNormalDisplay,
0x80, OLEDDisplay.DisplayOn
]
let initSequenceData = Data(bytes: initSequence)
let numBytesSent = device!.send(onI2CPort: i2cPort, data: initSequenceData, toSlave: displayAddress)
if Int(numBytesSent) != initSequenceData.count {
let result = device!.lastResult(onI2CPort: i2cPort)
if result == .busBusy && retries > 0 {
NSLog("OLED initialization: bus busy")
device!.resetBus(onI2CPort: i2cPort)
if device!.lastResult(onI2CPort: i2cPort) != .OK {
NSLog("Resetting bus failed")
}
initSensor(retries: retries - 1)
} else {
NSLog("OLED initialization failed: \(result.rawValue)")
}
return
}
graphics = GraphicsBuffer(width: Width, height: Height, isColor: false)
}
func draw(offset: Int) {
let gc = graphics!.prepareForDrawing()
gc.setFillColor(CGColor.black)
gc.fill(CGRect(x: 0, y: 0, width: 128, height: 64))
let ngc = NSGraphicsContext(cgContext: gc, flipped: false)
NSGraphicsContext.setCurrent(ngc)
let font = NSFont(name: "Helvetica", size: 64)!
let attr: [String: Any] = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: NSColor.white
]
let s = "😱✌️🎃🐢☠️😨💩😱✌️" as NSString
s.draw(at: NSMakePoint(CGFloat(offset), -10), withAttributes: attr)
}
func showTile() {
if !isInitialized {
initSensor(retries: 1)
isInitialized = true
}
draw(offset: -offset)
offset += 1
if offset >= 448 {
offset = 0
}
let pixels = graphics!.finishDrawing(format: .blackAndWhiteDithered)
var tile = [UInt8](repeating: 0, count: Width + 7)
for page in 0 ..< 8 {
tile[0] = 0x80
tile[1] = OLEDDisplay.SetPageAddress + UInt8(page)
tile[2] = 0x80
tile[3] = OLEDDisplay.SetColumnAddressLow | UInt8(DisplayOffset & 0x0f)
tile[4] = 0x80
tile[5] = OLEDDisplay.SetColumnAddressHigh | UInt8((DisplayOffset >> 4) & 0x0f)
tile[6] = 0x40
let index = page * 8 * Width
for i in 0 ..< Width {
var byte = 0
var bit = 1
var p = index + i
for _ in 0 ..< 8 {
if pixels[p] != 0 {
byte |= bit
}
bit <<= 1
p += Width
}
tile[i + 7] = UInt8(byte)
}
let data = Data(bytes: tile)
device!.submit(onI2CPort: i2cPort, data: data, toSlave: displayAddress)
}
/*
// Just for the fun of it: read back some of the data
// It's unclear why the data is offset by 1 pixel and the first byte is garbage
let cmd: [UInt8] = [
0x80, OLEDDisplay.SetPageAddress + UInt8(7),
0x80, OLEDDisplay.SetColumnAddressLow | UInt8((DisplayOffset + 1) & 0x0f),
0x80, OLEDDisplay.SetColumnAddressHigh | UInt8(((DisplayOffset + 1) >> 4) & 0x0f),
0x40
]
let cmdData = Data(bytes: cmd)
let response = device!.sendAndRequest(onI2CPort: i2cPort, data: cmdData, toSlave: displayAddress, receiveLength: Width)!
let responseBytes = [UInt8](response)
// compare data
for i in 1 ..< Width {
assert(tile[i + 7] == responseBytes[i])
}
*/
}
}
| mit | 9dce8ab84bd8ffc8d9d7eb87d78535f3 | 33.798995 | 128 | 0.579495 | 4.09279 | false | false | false | false |
Jauzee/showroom | Showroom/ViewControllers/NavigationStack/ThirdViewController/ThirdViewController.swift | 2 | 1472 | //
// ThirdViewController.swift
// NavigationStackDemo
//
// Created by Alex K. on 29/02/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class ThirdViewController: UITableViewController {
var hideNavBar = false
@IBInspectable var navbarColor: UIColor = .black
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if hideNavBar == false { return }
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
}
@IBAction func backHandler(_ sender: AnyObject) {
let _ = navigationController?.popViewController(animated: true)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "push", sender: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
_ = MenuPopUpViewController.showPopup(on: self, url: "https://github.com/Ramotion/navigation-stack") { [weak self] in
self?.hideNavBar = true
self?.navigationController?.dismiss(animated: true, completion: nil)
self?.navigationController?.dismiss(animated: true, completion: nil)
}
}
override open var shouldAutorotate: Bool {
return false
}
}
| gpl-3.0 | 474cbdb8b55ef9517de14710b2e8acba | 27.288462 | 121 | 0.709721 | 4.775974 | false | false | false | false |
dreamsxin/swift | test/Generics/deduction.swift | 3 | 9578 | // RUN: %target-parse-verify-swift
//===----------------------------------------------------------------------===//
// Deduction of generic arguments
//===----------------------------------------------------------------------===//
func identity<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> Int { return 0 }
struct X { }
struct Y { }
func useIdentity(_ x: Int, y: Float, i32: Int32) {
var x2 = identity(x)
var y2 = identity(y)
// Deduction that involves the result type
x2 = identity(17)
var i32_2 : Int32 = identity(17)
// Deduction where the result type and input type can get different results
var xx : X, yy : Y
xx = identity(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}}
xx = identity2(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}}
}
// FIXME: Crummy diagnostic!
func twoIdentical<T>(_ x: T, _ y: T) -> T {}
func useTwoIdentical(_ xi: Int, yi: Float) {
var x = xi, y = yi
x = twoIdentical(x, x)
y = twoIdentical(y, y)
x = twoIdentical(x, 1)
x = twoIdentical(1, x)
y = twoIdentical(1.0, y)
y = twoIdentical(y, 1.0)
twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func mySwap<T>(_ x: inout T,
_ y: inout T) {
let tmp = x
x = y
y = tmp
}
func useSwap(_ xi: Int, yi: Float) {
var x = xi, y = yi
mySwap(&x, &x)
mySwap(&y, &y)
mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
// expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}}
mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func takeTuples<T, U>(_: (T, U), _: (U, T)) {
}
func useTuples(_ x: Int, y: Float, z: (Float, Int)) {
takeTuples((x, y), (y, x))
takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}}
// FIXME: Use 'z', which requires us to fix our tuple-conversion
// representation.
}
func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {}
func passFunction(_ f: (Int) -> Float, x: Int, y: Float) {
acceptFunction(f, x, y)
acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}}
func testReturnTuple(_ x: Int, y: Float) {
returnTuple(x) // expected-error{{generic parameter 'T' could not be inferred}}
var _ : (Int, Float) = returnTuple(x)
var _ : (Float, Float) = returnTuple(y)
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) {
confusingArgAndParam(g, f)
confusingArgAndParam(f, g)
}
func acceptUnaryFn<T, U>(_ f: (T) -> U) { }
func acceptUnaryFnSame<T>(_ f: (T) -> T) { }
func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { }
func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { }
func unaryFnIntInt(_: Int) -> Int {}
func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}}
func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}}
// Variable forms of the above functions
var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt
func passOverloadSet() {
// Passing a non-generic function to a generic function
acceptUnaryFn(unaryFnIntInt)
acceptUnaryFnSame(unaryFnIntInt)
// Passing an overloaded function set to a generic function
// FIXME: Yet more terrible diagnostics.
acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}}
acceptUnaryFnSame(unaryFnOvl)
// Passing a variable of function type to a generic function
acceptUnaryFn(unaryFnIntIntVar)
acceptUnaryFnSame(unaryFnIntIntVar)
// Passing a variable of function type to a generic function to an inout parameter
acceptUnaryFnRef(&unaryFnIntIntVar)
acceptUnaryFnSameRef(&unaryFnIntIntVar)
acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
}
func acceptFnFloatFloat(_ f: (Float) -> Float) {}
func acceptFnDoubleDouble(_ f: (Double) -> Double) {}
func passGeneric() {
acceptFnFloatFloat(identity)
acceptFnFloatFloat(identity2)
}
//===----------------------------------------------------------------------===//
// Simple deduction for generic member functions
//===----------------------------------------------------------------------===//
struct SomeType {
func identity<T>(_ x: T) -> T { return x }
func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}}
func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}}
func returnAs<T>() -> T {}
}
func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) {
var st = sti, i = ii, f = fi
i = st.identity(i)
f = st.identity(f)
i = st.identity2(i)
f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}}
i = st.returnAs()
f = st.returnAs()
acceptFnFloatFloat(st.identity)
acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}}
acceptFnDoubleDouble(st.identity2)
}
struct StaticFuncs {
static func chameleon<T>() -> T {}
func chameleon2<T>() -> T {}
}
struct StaticFuncsGeneric<U> {
// FIXME: Nested generics are very broken
// static func chameleon<T>() -> T {}
}
func chameleon<T>() -> T {}
func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) {
var x: Int16
x = StaticFuncs.chameleon()
x = sf.chameleon2()
// FIXME: Nested generics are very broken
// x = sfi.chameleon()
// typealias SFI = StaticFuncsGeneric<Int>
// x = SFI.chameleon()
_ = x
}
//===----------------------------------------------------------------------===//
// Deduction checking for constraints
//===----------------------------------------------------------------------===//
protocol IsBefore {
func isBefore(_ other: Self) -> Bool
}
func min2<T : IsBefore>(_ x: T, _ y: T) -> T {
if y.isBefore(x) { return y }
return x
}
extension Int : IsBefore {
func isBefore(_ other: Int) -> Bool { return self < other }
}
func callMin(_ x: Int, y: Int, a: Float, b: Float) {
_ = min2(x, y)
min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}}
}
func rangeOfIsBefore<
R : IteratorProtocol where R.Element : IsBefore
>(_ range: R) { }
func callRangeOfIsBefore(_ ia: [Int], da: [Double]) {
rangeOfIsBefore(ia.makeIterator())
rangeOfIsBefore(da.makeIterator()) // expected-error{{ambiguous reference to member 'makeIterator()'}}
}
//===----------------------------------------------------------------------===//
// Deduction for member operators
//===----------------------------------------------------------------------===//
protocol Addable {
func +(x: Self, y: Self) -> Self
}
func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T {
u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
return x+y
}
//===----------------------------------------------------------------------===//
// Deduction for bound generic types
//===----------------------------------------------------------------------===//
struct MyVector<T> { func size() -> Int {} }
func getVectorSize<T>(_ v: MyVector<T>) -> Int {
return v.size()
}
func ovlVector<T>(_ v: MyVector<T>) -> X {}
func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {}
func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) {
var i : Int
i = getVectorSize(vi)
i = getVectorSize(vf)
getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}}
var x : X, y : Y
x = ovlVector(vi)
x = ovlVector(vf)
var vvi : MyVector<MyVector<Int>>
y = ovlVector(vvi)
var yy = ovlVector(vvi)
yy = y
y = yy
}
// <rdar://problem/15104554>
postfix operator <*> {}
protocol MetaFunction {
associatedtype Result
postfix func <*> (_: Self) -> Result?
}
protocol Bool_ {}
struct False : Bool_ {}
struct True : Bool_ {}
postfix func <*> <B:Bool_>(_: Test<B>) -> Int? { return .none }
postfix func <*> (_: Test<True>) -> String? { return .none }
class Test<C: Bool_> : MetaFunction {
typealias Result = Int
} // picks first <*>
typealias Inty = Test<True>.Result
var iy : Inty = 5 // okay, because we picked the first <*>
var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}}
// rdar://problem/20577950
class DeducePropertyParams {
let badSet: Set = ["Hello"]
}
// SR-69
struct A {}
func foo() {
for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}}
}
let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}}
let oi : Int? = 5
let l = min(3, oi) // expected-error{{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?}}
}
| apache-2.0 | c29ac7d5f928f7ef9299eb53b785f772 | 30.926667 | 150 | 0.596158 | 3.757552 | false | false | false | false |
AaronMT/firefox-ios | Client/Frontend/Settings/WebsiteDataSearchResultsViewController.swift | 5 | 4079 | /* 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 SnapKit
import Shared
import WebKit
protocol WebsiteDataSearchResultsViewControllerDelegate: class {
func websiteDataSearchResultsViewController(_ viewController: WebsiteDataSearchResultsViewController, didDeleteRecord record: WKWebsiteDataRecord)
}
private let SectionHeaderFooterIdentifier = "SectionHeaderFooterIdentifier"
class WebsiteDataSearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
weak var delegate: WebsiteDataSearchResultsViewControllerDelegate?
private var tableView: UITableView!
var siteRecords = [WKWebsiteDataRecord]()
private var filteredSiteRecords = [WKWebsiteDataRecord]()
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.separatorColor = UIColor.theme.tableView.separator
tableView.backgroundColor = UIColor.theme.tableView.headerBackground
tableView.isEditing = true
tableView.register(ThemedTableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.register(ThemedTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderFooterIdentifier)
view.addSubview(tableView)
let footer = ThemedTableSectionHeaderFooterView(frame: CGRect(width: tableView.bounds.width, height: SettingsUX.TableViewHeaderFooterHeight))
footer.showBorder(for: .top, true)
tableView.tableFooterView = footer
tableView.snp.makeConstraints { make in
make.edges.equalTo(view)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredSiteRecords.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if let record = filteredSiteRecords[safe: indexPath.row] {
cell.textLabel?.text = record.displayName
}
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard editingStyle == UITableViewCell.EditingStyle.delete, let record = filteredSiteRecords[safe: indexPath.row] else {
return
}
let types = WKWebsiteDataStore.allWebsiteDataTypes()
WKWebsiteDataStore.default().removeData(ofTypes: types, for: [record]) {
self.delegate?.websiteDataSearchResultsViewController(self, didDeleteRecord: record)
self.filteredSiteRecords.remove(at: indexPath.row)
self.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderFooterIdentifier) as? ThemedTableSectionHeaderFooterView
headerView?.titleLabel.text = Strings.SettingsWebsiteDataTitle
headerView?.showBorder(for: .top, section != 0)
headerView?.showBorder(for: .bottom, true)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return SettingsUX.TableViewHeaderFooterHeight
}
func filterContentForSearchText(_ searchText: String) {
filteredSiteRecords = siteRecords.filter({ siteRecord in
return siteRecord.displayName.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
}
extension WebsiteDataSearchResultsViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
| mpl-2.0 | 3b720d760493ccb53ce0777ef237af72 | 41.051546 | 152 | 0.73621 | 5.84384 | false | false | false | false |
NathanE73/Blackboard | Sources/BlackboardFramework/Image Assets/AssetImageSet.swift | 1 | 1960 | //
// Copyright (c) 2022 Nathan E. Walczak
//
// MIT License
//
// 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
struct AssetImageSet: Decodable {
var info: AssetInfo
var images: [Image]
}
extension AssetImageSet {
struct Image: Decodable {
var idiom: AssetIdiom
var scale: Scale?
enum CodingKeys: String, CodingKey {
case idiom
case scale
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
idiom = try container.decodeIfPresent(AssetIdiom.self, forKey: .idiom) ?? .universal
scale = try container.decodeIfPresent(Scale.self, forKey: .scale)
}
}
}
extension AssetImageSet.Image {
enum Scale: String, Decodable {
case one = "1x"
case two = "2x"
case three = "3x"
}
}
| mit | 0ab42ce223ff71dd6e55bfbaa165894d | 31.666667 | 96 | 0.681633 | 4.505747 | false | false | false | false |
Swinject/SwinjectMVVMExample | SwinjectMVVMExample/AppDelegate.swift | 2 | 4175 | //
// AppDelegate.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 8/20/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import UIKit
import Swinject
import SwinjectStoryboard
import ExampleModel
import ExampleViewModel
import ExampleView
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let container = Container() { container in
// Models
container.register(Networking.self) { _ in Network() }
container.register(ImageSearching.self) { r in ImageSearch(network: r.resolve(Networking.self)!) }
container.register(ExternalAppChanneling.self) { _ in ExternalAppChannel() }
// View models
container.register(ImageSearchTableViewModeling.self) { r in
let viewModel = ImageSearchTableViewModel(imageSearch: r.resolve(ImageSearching.self)!, network: r.resolve(Networking.self)!)
viewModel.imageDetailViewModel = r.resolve(ImageDetailViewModelModifiable.self)!
return viewModel
}.inObjectScope(.container)
container.register(ImageDetailViewModelModifiable.self) { _ in
ImageDetailViewModel(
network: container.resolve(Networking.self)!,
externalAppChannel: container.resolve(ExternalAppChanneling.self)!)
}.inObjectScope(.container)
container.register(ImageDetailViewModeling.self) { r in
r.resolve(ImageDetailViewModelModifiable.self)!
}
// Views
container.registerForStoryboard(ImageSearchTableViewController.self) { r, c in
c.viewModel = r.resolve(ImageSearchTableViewModeling.self)!
}
container.registerForStoryboard(ImageDetailViewController.self) { r, c in
c.viewModel = r.resolve(ImageDetailViewModeling.self)!
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let window = UIWindow(frame: UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
self.window = window
let bundle = Bundle(for: ImageSearchTableViewController.self)
let storyboard = SwinjectStoryboard.create(name: "Main", bundle: bundle, container: container)
window.rootViewController = storyboard.instantiateInitialViewController()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | a9a7ab0ae1f1b6f3163de82598bfc81d | 47.534884 | 285 | 0.719454 | 5.499341 | false | false | false | false |
auth0/Lock.iOS-OSX | Lock/Logger.swift | 2 | 3782 | // Logger.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public class Logger {
static let sharedInstance = Logger()
var level: LoggerLevel = .off
var output: LoggerOutput = DefaultLoggerOutput()
func debug(_ message: String, filename: String = #file, line: Int = #line) {
guard self.level >= .debug else { return }
output.message(message, level: .debug, filename: filename, line: line)
}
func info(_ message: String, filename: String = #file, line: Int = #line) {
guard self.level >= .info else { return }
output.message(message, level: .info, filename: filename, line: line)
}
func error(_ message: String, filename: String = #file, line: Int = #line) {
guard self.level >= .error else { return }
output.message(message, level: .error, filename: filename, line: line)
}
func warn(_ message: String, filename: String = #file, line: Int = #line) {
guard self.level >= .warn else { return }
output.message(message, level: .warn, filename: filename, line: line)
}
func verbose(_ message: String, filename: String = #file, line: Int = #line) {
guard self.level >= .verbose else { return }
output.message(message, level: .verbose, filename: filename, line: line)
}
}
// MARK: - Level
public enum LoggerLevel: Int {
case off = 0
case error
case warn
case info
case debug
case verbose
case all
var label: String {
switch self {
case .error:
return "ERROR"
case .warn:
return "WARN"
case .info:
return "INFO"
case .debug:
return "DEBUG"
case .verbose:
return "VERBOSE"
default:
return "INVALID"
}
}
}
func >= (lhs: LoggerLevel, rhs: LoggerLevel) -> Bool {
return lhs.rawValue >= rhs.rawValue
}
// MARK: - Loggable
protocol Loggable { }
extension Loggable {
var logger: Logger {
return Logger.sharedInstance
}
}
// MARK: - LoggerOutput
public protocol LoggerOutput {
func message(_ message: String, level: LoggerLevel, filename: String, line: Int)
}
struct DefaultLoggerOutput: LoggerOutput {
func message(_ message: String, level: LoggerLevel, filename: String, line: Int) {
trace("\(heading(forFile: filename, line: line))", level, message)
}
var trace: (String, LoggerLevel, String) -> Void = { print("\($1.label) | \($0) - \($2)") }
private func heading(forFile file: String, line: Int) -> String {
let filename = URL(fileURLWithPath: file).lastPathComponent
return "\(filename):\(line)"
}
}
| mit | de6e12474a05bf407621c24e759eb5e5 | 31.050847 | 95 | 0.650714 | 4.192905 | false | false | false | false |
BenjyAir/PDEXChart | PDEXChart/Lib/ColorSet.swift | 2 | 1480 | //
// ColorSet.swift
// PDEXChart
//
// Created by KokerWang on 15/3/18.
// Copyright (c) 2015年 KokerWang. All rights reserved.
//
import UIKit
let red = UIColor.redColor();
//let yellow = UIColor.yellowColor()
let darkGray = UIColor.darkGrayColor() // 0.333 white
let lightGray = UIColor.lightGrayColor() // 0.667 white
let gray = UIColor.grayColor() // 0.5 white
let green = UIColor.greenColor() // 0.0, 1.0, 0.0 RGB
let blue = UIColor.blueColor() // 0.0, 0.0, 1.0 RGB
let cyan = UIColor.cyanColor() // 0.0, 1.0, 1.0 RGB
let magenta = UIColor.magentaColor() // 1.0, 0.0, 1.0 RGB
let orange = UIColor.orangeColor() // 1.0, 0.5, 0.0 RGB
let purple = UIColor.purpleColor() // 0.5, 0.0, 0.5 RGB
let brown = UIColor.brownColor() // 0.6, 0.4, 0.2 RGB
var colors = [red, darkGray, lightGray, gray, green, blue, cyan, magenta, orange, purple, brown]
func getColors(size : Int) -> Array<UIColor> {
var array = Array<UIColor>()
var set = Array<Int>()
for var i = 0; i < size; i++ {
var index : Int
do{
index = Int(arc4random_uniform(UInt32(colors.count)))
}while(contains(set, index))
set.append(index)
array.append(colors[index])
}
return array
}
func contains(list : Array<Int>, data : Int ) ->Bool {
if list.count == 0{
return false
}
for var i = 0; i<list.count; i++ {
if data == list[i]{
return true
}
}
return false
}
| mit | ac55a5b7dffab2d830a21e649fe148a7 | 26.886792 | 96 | 0.597429 | 3.164882 | false | false | false | false |
X-my/MYCycleScrollView | Sources/MYCycleScrollView.swift | 1 | 9523 | //
// MYCycleScrollView.swift
// MYCycleScrollView
//
// Created by Obj on 2017/2/4.
// Copyright © 2017年 梦阳 许. All rights reserved.
//
import UIKit
import Kingfisher
private let kCellReuseIdentifier = "MYCollectionViewCell"
public enum PageContolAliment {
case center
case right
}
@objc public protocol MYCycleScrollViewDelegate: NSObjectProtocol {
@objc optional func cycleScrollView(_ cycleScrollView: MYCycleScrollView, didSelectItemAt index: Int)
@objc optional func cycleScrollView(_ cycleScrollView: MYCycleScrollView, didScrollTo index: Int)
}
open class MYCycleScrollView: UIView {
// MARK: - Public Properties
public var imageURLs = [String]() {
didSet {
if imageURLs.count < oldValue.count {
collectionView.setContentOffset(CGPoint.zero, animated: false)
}
totalItemsCount = isInfiniteLoop ? imageURLs.count * 100 : imageURLs.count
invalidateTimer()
if imageURLs.count == 1 {
collectionView.isScrollEnabled = false
}else {
collectionView.isScrollEnabled = true
if isAutoScroll {
setupTimer()
}
}
setupPageControl()
collectionView.reloadData()
self.setNeedsLayout()
}
}
public var isAutoScroll = true {
didSet {
invalidateTimer()
if isAutoScroll {
setupTimer()
}
}
}
public var placehoder: UIImage?
public var imageTransition = ImageTransition.fade(0.3)
public var imageViewContentMode: UIViewContentMode = .scaleToFill
public weak var delegate: MYCycleScrollViewDelegate?
public private (set) var pageControl: UIPageControl = UIPageControl()
public var isInfiniteLoop = true
public var autoScrollTimeInterval: TimeInterval = 3.0
public var pageContolAliment: PageContolAliment = .right
// MARK: - Private Properties
fileprivate var totalItemsCount = 0
fileprivate var currentIndex: Int {
if collectionView.frame.width == 0 || collectionView.frame.height == 0 {
return 0
}
var index = 0
switch flowLayout.scrollDirection {
case .horizontal:
index = Int((collectionView.contentOffset.x + flowLayout.itemSize.width * 0.5) / flowLayout.itemSize.width)
case.vertical:
index = Int((collectionView.contentOffset.y + flowLayout.itemSize.height * 0.5) / flowLayout.itemSize.height)
}
return max(0, index)
}
private weak var timer: Timer?
// MARK: - 初始化方法
override public init(frame: CGRect) {
super.init(frame: frame)
setupSubview()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubview()
}
override open func willMove(toSuperview newSuperview: UIView?) {
if newSuperview == nil {
self.invalidateTimer()
}
}
deinit {
collectionView.delegate = nil
collectionView.dataSource = nil
}
override open func layoutSubviews() {
super.layoutSubviews()
flowLayout.itemSize = collectionView.bounds.size
if collectionView.contentOffset.x == 0 && totalItemsCount > 0 {
var targetIndex = 0
if self.isInfiniteLoop {
targetIndex = totalItemsCount / 2
}
collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: .init(rawValue: 0), animated: false)
}
pageControl.frame.size = pageControl.size(forNumberOfPages: imageURLs.count)
var x: CGFloat = 0
switch pageContolAliment {
case .center:
x = (self.bounds.width - pageControl.bounds.width) / 2
case .right:
x = self.bounds.width - pageControl.bounds.width - 10
}
let y = self.bounds.height - pageControl.bounds.height
pageControl.frame.origin = CGPoint(x: x, y: y)
}
// MARK: - Private Methods
private func setupSubview() {
self.backgroundColor = UIColor.lightGray
self.addSubview(collectionView)
self.addSubview(pageControl)
pageControl.hidesForSinglePage = true
pageControl.isUserInteractionEnabled = false
}
private func setupPageControl() {
pageControl.numberOfPages = imageURLs.count
pageControl.currentPage = self.currentIndex % self.imageURLs.count
}
fileprivate func invalidateTimer() {
self.timer?.invalidate()
self.timer = nil
}
fileprivate func setupTimer() {
let timer = Timer(timeInterval: autoScrollTimeInterval, target: self, selector: #selector(automaticScroll), userInfo: nil, repeats: true)
self.timer = timer
RunLoop.main.add(timer, forMode: .commonModes)
}
@objc private func automaticScroll() {
if totalItemsCount == 0 { return }
var targetIndex = self.currentIndex + 1
if targetIndex >= totalItemsCount {
if self.isInfiniteLoop {
targetIndex = totalItemsCount/2
collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: .init(rawValue: 0), animated: false)
}
return
}
collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: .init(rawValue: 0), animated: true)
}
// MARK: - Lazy Properties
lazy var flowLayout: UICollectionViewFlowLayout = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = 0
flowLayout.scrollDirection = .horizontal
return flowLayout
}()
public private(set) lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: self.flowLayout)
collectionView.backgroundColor = UIColor.clear
collectionView.isPagingEnabled = true
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(MYCollectionViewCell.self, forCellWithReuseIdentifier: kCellReuseIdentifier)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.scrollsToTop = false
return collectionView
}()
}
// MARK: - UICollectionViewDataSource & UICollectionViewDelegate
extension MYCycleScrollView: UICollectionViewDataSource, UICollectionViewDelegate{
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return self.totalItemsCount
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellReuseIdentifier, for: indexPath) as! MYCollectionViewCell
let index = indexPath.item % self.imageURLs.count
cell.imageView.kf.setImage(with: URL(string: self.imageURLs[index]), placeholder:self.placehoder, options: [.transition(self.imageTransition)])
cell.imageView.contentMode = self.imageViewContentMode
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let delegate = self.delegate,
delegate.responds(to: #selector(MYCycleScrollViewDelegate.cycleScrollView(_:didSelectItemAt:))) else {
return
}
delegate.cycleScrollView!(self, didSelectItemAt: indexPath.item % self.imageURLs.count)
}
}
// MARK: - UIScrollViewDelegate
public extension MYCycleScrollView {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard self.imageURLs.count > 0 else { return }
guard !self.pageControl.isHidden else { return }
self.pageControl.currentPage = self.currentIndex % self.imageURLs.count
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if self.isAutoScroll {
self.invalidateTimer()
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if self.isAutoScroll {
self.setupTimer()
}
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
guard self.imageURLs.count > 0 else { return }
guard let delegate = self.delegate,
delegate.responds(to: #selector(MYCycleScrollViewDelegate.cycleScrollView(_:didScrollTo:))) else {
return
}
let index = self.currentIndex % self.imageURLs.count
delegate.cycleScrollView!(self, didScrollTo: index)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.scrollViewDidEndScrollingAnimation(self.collectionView)
}
}
fileprivate class MYCollectionViewCell: UICollectionViewCell {
var imageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
imageView.clipsToBounds = true
}
}
| mit | 9ed3484bf795603d3d34e46fffd9cb59 | 37.322581 | 151 | 0.658144 | 5.40922 | false | false | false | false |
LeeKahSeng/KSImageCarousel | KSImageCarousel/KSImageCarouselTests/KSICFakeScrollerViewController.swift | 1 | 2073 | //
// KSICFakeScrollerViewController.swift
// KSImageCarousel
//
// Created by Lee Kah Seng on 23/07/2017.
// Copyright © 2017 Lee Kah Seng. All rights reserved.
//
import Foundation
@testable import KSImageCarousel
class KSICFakeScrollerViewController: KSICScrollerViewController {
var scrollToCenterSubviewCalled: Bool
var scrollToFirstSubviewCalled: Bool
var scrollToLastSubviewCalled: Bool
init(withViewModel vm: [KSImageCarouselDisplayable]) {
scrollToCenterSubviewCalled = false
scrollToFirstSubviewCalled = false
scrollToLastSubviewCalled = false
super.init(withViewModel: vm, placeholderImage: nil, delegate: KSICFakeScrollerViewControllerDelegate())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func scrollToCenterSubview(_ animated: Bool) {
scrollToCenterSubviewCalled = true
}
override func scrollToFirstSubview(_ animated: Bool) {
scrollToFirstSubviewCalled = true
}
override func scrollToLastSubview(_ animated: Bool) {
scrollToLastSubviewCalled = true
}
func resetStatus() {
scrollToCenterSubviewCalled = false
scrollToFirstSubviewCalled = false
scrollToLastSubviewCalled = false
}
}
class KSICFakeScrollerViewControllerDelegate: KSICScrollerViewControllerDelegate {
func scrollerViewControllerDidGotoNextPage(_ viewController: KSICScrollerViewController) { }
func scrollerViewControllerDidGotoPreviousPage(_ viewController: KSICScrollerViewController) { }
func scrollerViewControllerDidFinishLayoutSubviews(_ viewController: KSICScrollerViewController) { }
func scrollerViewControllerDidTappedImageView(at index: Int, viewController: KSICScrollerViewController) { }
func scrollerViewControllerShouldShowActivityIndicator() -> Bool { return true }
func scrollerViewControllerShowActivityIndicatorStyle() -> UIActivityIndicatorViewStyle { return .gray }
}
| mit | 5fe32fcf136eb74f3dbfbbc5740e673c | 34.724138 | 112 | 0.741313 | 6.076246 | false | false | false | false |
devpunk/velvet_room | Source/View/Connected/VConnectedOnEventsCell.swift | 1 | 2691 | import UIKit
class VConnectedOnEventsCell:UICollectionViewCell
{
let lineBreak:NSAttributedString
let attributesTimestamp:[NSAttributedStringKey:Any]
private weak var label:UILabel!
private weak var layoutLabelHeight:NSLayoutConstraint!
private let options:NSStringDrawingOptions
private let boundingSize:CGSize
private let kLineBreak:String = "\n"
private let kMaxTextHeight:CGFloat = 1000
private let kLabelTop:CGFloat = 5
private let kTimestampFontSize:CGFloat = 13
override init(frame:CGRect)
{
attributesTimestamp = [
NSAttributedStringKey.foregroundColor:
UIColor(white:0.7, alpha:1),
NSAttributedStringKey.font:
UIFont.regular(size:kTimestampFontSize)]
lineBreak = NSAttributedString(
string:kLineBreak)
let width:CGFloat = frame.width
let labelTop:CGFloat = width + kLabelTop
options = NSStringDrawingOptions([
NSStringDrawingOptions.usesLineFragmentOrigin,
NSStringDrawingOptions.usesFontLeading])
boundingSize = CGSize(
width:width,
height:kMaxTextHeight)
super.init(frame:frame)
backgroundColor = UIColor.clear
clipsToBounds = true
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
self.label = label
addSubview(label)
NSLayoutConstraint.topToTop(
view:label,
toView:self,
constant:labelTop)
layoutLabelHeight = NSLayoutConstraint.height(
view:label)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func heightForString(string:NSAttributedString) -> CGFloat
{
let stringRect:CGRect = string.boundingRect(
with:boundingSize,
options:options,
context:nil)
let height:CGFloat = ceil(stringRect.height)
return height
}
//MARK: internal
final func configText(string:NSAttributedString)
{
let stringHeight:CGFloat = heightForString(
string:string)
label.attributedText = string
layoutLabelHeight.constant = stringHeight
}
func config(model:MConnectedEventProtocol) { }
}
| mit | 1fd8f91123feb40a221a5e6b45a86b7d | 28.571429 | 70 | 0.628391 | 5.824675 | false | false | false | false |
xivol/MCS-V3-Mobile | examples/graphics/ViewAnimation.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift | 1 | 2610 | // https://github.com/shu223/iOS-10-Sampler/blob/master/iOS-10-Sampler/Samples/PropertyAnimatorViewController.swift
//
// PropertyAnimatorViewController.swift
// Created by Shuichi Tsutsumi on 9/10/16.
// Copyright © 2016 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import PlaygroundSupport
class PropertyAnimatorViewController: UIViewController {
private var targetLocation: CGPoint!
private var objectView: UIView!
private let spring = true
override func viewDidLoad() {
super.viewDidLoad()
objectView = UIView(frame: CGRect(origin: view.bounds.origin, size: CGSize(width: 50, height: 50)))
objectView.backgroundColor = colorAt(location: objectView.center)
view.addSubview(objectView)
targetLocation = objectView.center
}
private func colorAt(location: CGPoint) -> UIColor {
let hue: CGFloat = (location.x / UIScreen.main.bounds.width + location.y / UIScreen.main.bounds.height) / 2
return UIColor(hue: hue, saturation: 0.78, brightness: 0.75, alpha: 1)
}
private func processTouches(_ touches: Set<UITouch>) {
guard let touch = touches.first else {return}
let loc = touch.location(in: view)
if loc == targetLocation {
return
}
animateTo(location: loc)
}
private func animateTo(location: CGPoint) {
var duration: TimeInterval
var timing: UITimingCurveProvider
if !spring {
duration = 0.4
timing = UICubicTimingParameters(animationCurve: .easeOut)
} else {
duration = 0.6
timing = UISpringTimingParameters(dampingRatio: 0.5)
}
let animator = UIViewPropertyAnimator(
duration: duration,
timingParameters: timing)
animator.addAnimations {
self.objectView.center = location
self.objectView.backgroundColor = self.colorAt(location: location)
}
animator.startAnimation()
targetLocation = location
}
// =========================================================================
// MARK: - Touch handlers
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
processTouches(touches)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
processTouches(touches)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = PropertyAnimatorViewController()
| mit | ccdcfde97a1e742b6407724e6d50bb38 | 32.448718 | 116 | 0.620161 | 5.03668 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Client/Graph.Task.swift | 1 | 11841 | //
// Graph.Task.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
/// Provides an interface for managing the `URLSessionDataTask` created by `Graph.Client`. Since the
/// underlying `URLSessionDataTask` can change (in the case of retried requests), `Task` provides
/// a single place to `cancel()` or `resume()` this underlying task.
///
public protocol Task {
/// Starts the underlying task
func resume()
/// Cancel the underlying task
func cancel()
}
extension URLSessionDataTask: Task {}
internal extension Graph {
class InternalTask<R: GraphQL.AbstractResponse>: Task {
typealias TaskCompletion = (R?, QueryError?) -> Void
internal private(set) var isResumed: Bool = false
internal private(set) var isCancelled: Bool = false
internal let cache: Cache
internal let session: URLSession
internal let request: URLRequest
internal let cachePolicy: CachePolicy
internal let retryHandler: RetryHandler<R>?
internal let completion: TaskCompletion
internal var task: URLSessionDataTask?
// ----------------------------------
// MARK: - Init -
//
internal init(session: URLSession, cache: Cache, request: URLRequest, cachePolicy: CachePolicy, retryHandler: RetryHandler<R>? = nil, completion: @escaping TaskCompletion) {
self.cache = cache
self.session = session
self.request = request
self.cachePolicy = retryHandler == nil ? cachePolicy : .networkOnly
self.retryHandler = retryHandler
self.completion = completion
}
// ----------------------------------
// MARK: - Control -
//
func resume() {
self.isResumed = true
self.resume(using: self.cachePolicy)
}
private func resume(using cachePolicy: CachePolicy) {
let completion = self.completion
let hash = self.request.hash
switch cachePolicy {
case .cacheFirst(let expireIn):
Log("Exercising cache policy: CACHE_FIRST(\(expireIn))")
self.cachedModelFor(hash, expireIn: expireIn) { response in
if let response = response {
completion(response, nil)
return
} else {
self.resume(using: .networkOnly)
}
}
case .cacheOnly:
Log("Exercising cache policy: CACHE_ONLY")
self.cachedModelFor(hash) { response in
completion(response, nil)
return
}
case .networkFirst(let expireIn):
Log("Exercising cache policy: NETWORK_FIRST(\(expireIn))")
self.task = self.graphTaskWith(self.request, retryHandler: self.retryHandler) { response, data, error in
if let _ = response, let data = data {
self.cache(data, for: hash)
completion(response, error)
} else {
self.cachedModelFor(hash, expireIn: expireIn) { response in
if let response = response {
completion(response, nil)
} else {
completion(nil, error)
}
}
}
}
self.task?.resume()
case .networkOnly:
Log("Exercising cache policy: NETWORK_ONLY")
self.task = self.graphTaskWith(self.request, retryHandler: self.retryHandler) { response, data, error in
if let _ = response, let data = data {
self.cache(data, for: hash)
}
completion(response, error)
}
self.task?.resume()
}
}
func cancel() {
self.isCancelled = true
self.task?.cancel()
}
// ----------------------------------
// MARK: - Cache -
//
private func cache(_ data: Data, for hash: Hash) {
let cacheItem = CacheItem(hash: hash, data: data)
self.cache.set(cacheItem)
}
private func cachedModelFor(_ hash: Hash, expireIn: Int? = nil, completion: @escaping (R?) -> Void) {
guard let item = self.cache.item(for: hash) else {
completion(nil)
return
}
/* ---------------------------------
** If the expiry is provided, we'll
** need to validated that cached
** date isn't older than the allowed
** interval, otherwise return nil.
*/
if let expireIn = expireIn {
Log("Cache expiry interval set to: \(expireIn)")
let now = Int(Date().timeIntervalSince1970)
let timestamp = Int(item.timestamp)
guard timestamp + expireIn > now else {
Log("Cached item expiry exceeded by: Now: \(timestamp + expireIn - now)")
/* ----------------------------------
** Purge any expired items from disk
** to avoid the overhead of loading
** them just to find out they have
** already expired.
*/
self.cache.remove(for: hash)
completion(nil)
return
}
Log("Cached item is still valid. Time remaining Now: \(timestamp + expireIn - now)")
} else {
Log("No cache expiry set.")
}
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: "HTTP/1.1",
headerFields: nil
)
let (model, _) = self.processResponse(item.data, response, nil)
completion(model)
}
// ----------------------------------
// MARK: - Session -
//
private func graphTaskWith(_ request: URLRequest, retryHandler: RetryHandler<R>? = nil, completion: @escaping (R?, Data?, QueryError?) -> Void) -> URLSessionDataTask {
return self.session.dataTask(with: request) { data, response, error in
let (model, error) = self.processResponse(data, response, error)
DispatchQueue.main.async {
guard self.isCancelled == false else {
return
}
if var retryHandler = retryHandler, retryHandler.canRetry, retryHandler.condition(model, error) == true {
/* ---------------------------------
** A retry handler was provided and
** the condition evaluated to true,
** we have to retry the request.
*/
retryHandler.repeatCount += 1
self.task = self.graphTaskWith(request, retryHandler: retryHandler, completion: completion)
DispatchQueue.main.asyncAfter(deadline: .now() + retryHandler.interval) {
if self.task!.state == .suspended {
self.task!.resume()
}
}
} else {
completion(model, data, error)
}
}
}
}
private func processResponse(_ data: Data?, _ response: URLResponse?, _ error: Error?) -> (model: R?, error: Graph.QueryError?) {
guard let response = response as? HTTPURLResponse, error == nil else {
return (nil, .request(error: error))
}
guard response.statusCode >= 200 && response.statusCode < 300 else {
return (nil, .http(statusCode: response.statusCode))
}
guard let data = data else {
return (nil, .noData)
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
return (nil, .jsonDeserializationFailed(data: data))
}
let graphResponse = json as? JSON
let graphErrors = graphResponse?["errors"] as? [JSON]
let graphJson = graphResponse?["data"] as? JSON
/* ----------------------------------
** This should never happen. A valid
** GraphQL response will have either
** data or errors.
*/
guard graphJson != nil || graphErrors != nil else {
return (nil, .invalidJson(json: json))
}
/* ---------------------------------
** Extract any GraphQL errors found
** during execution of the query.
*/
var queryError: Graph.QueryError?
if let graphErrors = graphErrors {
queryError = .invalidQuery(reasons: graphErrors.map {
Graph.QueryError.Reason(json: $0)
})
}
if let json = graphJson {
var model: R?
do {
model = try R(fields: json)
} catch let error {
queryError = Graph.QueryError.schemaViolation(violation: error as! SchemaViolationError)
}
return (model, queryError)
} else {
return (nil, queryError)
}
}
}
}
| mit | 6e811117e29b56ba22ad748e4bffe572 | 38.33887 | 182 | 0.470822 | 5.83588 | false | false | false | false |
rymcol/PerfectPress | Sources/routing.swift | 3 | 1839 | //
// routing.swift
// PerfectPress
//
// Created by Ryan Collins on 6/9/16.
// Copyright (C) 2016 Ryan M. Collins.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the PerfectPress open source blog project
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
import PerfectHTTP
func makeRoutes() -> Routes {
var routes = Routes()
routes.add(method: .get, uris: ["/", "index.html"], handler: indexHandler)
routes.add(method: .get, uris: ["blog"], handler: blogHandler)
routes.add(method: .get, uris: ["json"], handler: JSONHandler)
return routes
}
func indexHandler(request: HTTPRequest, _ response: HTTPResponse) {
let header = CommonHandler().getHeader()
let footer = CommonHandler().getFooter()
let body = IndexHandler().loadPageContent()
let indexPage = header + body + footer
response.setHeader(.contentType, value: "text/html; charset=utf-8")
response.appendBody(string: indexPage)
response.completed()
}
func blogHandler(request: HTTPRequest, _ response: HTTPResponse) {
let header = CommonHandler().getHeader()
let footer = CommonHandler().getFooter()
let body = BlogPageHandler().loadPageContent()
let blogPage = header + body + footer
response.setHeader(.contentType, value: "text/html; charset=utf-8")
response.appendBody(string: blogPage)
response.completed()
}
func JSONHandler(request: HTTPRequest, _ response: HTTPResponse) {
let JSONData = JSONCreator().generateJSON()
do {
response.setHeader(.contentType, value: "application/json; charset=utf-8")
try response.setBody(json: JSONData)
} catch {
response.appendBody(string: "JSON Failed")
}
response.completed()
}
| apache-2.0 | 4a1ed2add54eb7be72733cd9d2f6ad2f | 27.734375 | 82 | 0.623165 | 4.378571 | false | false | false | false |
lemberg/connfa-ios | Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/RelativeFormatter.swift | 1 | 15097 | //
// RelativeFormatter.swift
// SwiftDate
//
// Created by Daniele Margutti on 08/06/2018.
// Copyright © 2018 SwiftDate. All rights reserved.
//
import Foundation
public class RelativeFormatter: DateToStringTrasformable {
/// Private singleton for relative formatter
private static let shared = RelativeFormatter()
/// A cache with all loaded languagues
private var languagesCache: [String: RelativeFormatterLang] = [:]
/// Mapping for languages file to be loaded. Languages table are
/// loaded only upon request.
private var languagesMap: [String: RelativeFormatterLang.Type] = [
lang_af.identifier: lang_af.self,
lang_en.identifier: lang_en.self,
lang_am.identifier: lang_am.self,
lang_ar.identifier: lang_ar.self,
lang_arAE.identifier: lang_arAE.self,
lang_as.identifier: lang_as.self,
lang_be.identifier: lang_be.self,
lang_bg.identifier: lang_bg.self,
lang_bn.identifier: lang_bn.self,
lang_br.identifier: lang_br.self,
lang_bs.identifier: lang_bs.self,
lang_bsCyrl.identifier: lang_bsCyrl.self,
lang_ca.identifier: lang_ca.self,
lang_cs.identifier: lang_cs.self,
lang_cy.identifier: lang_cy.self,
lang_da.identifier: lang_da.self,
lang_de.identifier: lang_de.self,
lang_dsb.identifier: lang_dsb.self,
lang_dz.identifier: lang_dz.self,
lang_ee.identifier: lang_ee.self,
lang_el.identifier: lang_el.self,
lang_es.identifier: lang_es.self,
lang_esAR.identifier: lang_esAR.self,
lang_esMX.identifier: lang_esMX.self,
lang_esPY.identifier: lang_esPY.self,
lang_esUS.identifier: lang_esUS.self,
lang_et.identifier: lang_et.self,
lang_eu.identifier: lang_eu.self,
lang_fa.identifier: lang_fa.self,
lang_fi.identifier: lang_fi.self,
lang_fil.identifier: lang_fil.self,
lang_fo.identifier: lang_fo.self,
lang_fr.identifier: lang_fr.self,
lang_frCA.identifier: lang_frCA.self,
lang_fur.identifier: lang_fur.self,
lang_fy.identifier: lang_fy.self,
lang_ga.identifier: lang_ga.self,
lang_gd.identifier: lang_gd.self,
lang_gl.identifier: lang_gl.self,
lang_gu.identifier: lang_gu.self,
lang_he.identifier: lang_he.self,
lang_hi.identifier: lang_hi.self,
lang_hr.identifier: lang_hr.self,
lang_hsb.identifier: lang_hsb.self,
lang_hu.identifier: lang_hu.self,
lang_hy.identifier: lang_hy.self,
lang_id.identifier: lang_id.self,
lang_is.identifier: lang_is.self,
lang_it.identifier: lang_it.self,
lang_ja.identifier: lang_ja.self,
lang_jgo.identifier: lang_jgo.self,
lang_ka.identifier: lang_ka.self,
lang_kea.identifier: lang_kea.self,
lang_kk.identifier: lang_kk.self,
lang_kl.identifier: lang_kl.self,
lang_km.identifier: lang_km.self,
lang_kn.identifier: lang_kn.self,
lang_ko.identifier: lang_ko.self,
lang_kok.identifier: lang_kok.self,
lang_ksh.identifier: lang_ksh.self,
lang_ky.identifier: lang_ky.self,
lang_lb.identifier: lang_lb.self,
lang_lkt.identifier: lang_lkt.self,
lang_lo.identifier: lang_lo.self,
lang_lt.identifier: lang_lt.self,
lang_lv.identifier: lang_lv.self,
lang_mk.identifier: lang_mk.self,
lang_ml.identifier: lang_ml.self,
lang_mn.identifier: lang_mn.self,
lang_mr.identifier: lang_mr.self,
lang_ms.identifier: lang_ms.self,
lang_mt.identifier: lang_mt.self,
lang_my.identifier: lang_my.self,
lang_mzn.identifier: lang_mzn.self,
lang_nb.identifier: lang_nb.self,
lang_ne.identifier: lang_ne.self,
lang_nl.identifier: lang_nl.self,
lang_nn.identifier: lang_nn.self,
lang_or.identifier: lang_or.self,
lang_pa.identifier: lang_pa.self,
lang_pl.identifier: lang_pl.self,
lang_ps.identifier: lang_ps.self,
lang_pt.identifier: lang_pt.self,
lang_ro.identifier: lang_ro.self,
lang_ru.identifier: lang_ru.self,
lang_sah.identifier: lang_sah.self,
lang_sd.identifier: lang_sd.self,
lang_seFI.identifier: lang_seFI.self,
lang_se.identifier: lang_se.self,
lang_si.identifier: lang_si.self,
lang_sk.identifier: lang_sk.self,
lang_sl.identifier: lang_sl.self,
lang_sq.identifier: lang_sq.self,
lang_srLatn.identifier: lang_srLatn.self,
lang_sv.identifier: lang_sv.self,
lang_sw.identifier: lang_sw.self,
lang_ta.identifier: lang_ta.self,
lang_te.identifier: lang_te.self,
lang_th.identifier: lang_th.self,
lang_ti.identifier: lang_ti.self,
lang_tk.identifier: lang_tk.self,
lang_to.identifier: lang_to.self,
lang_tr.identifier: lang_tr.self,
lang_ug.identifier: lang_ug.self,
lang_uk.identifier: lang_uk.self,
lang_urIN.identifier: lang_urIN.self,
lang_ur.identifier: lang_ur.self,
lang_uz.identifier: lang_uz.self,
lang_uzCyrl.identifier: lang_uzCyrl.self,
lang_vi.identifier: lang_vi.self,
lang_wae.identifier: lang_wae.self,
lang_yi.identifier: lang_yi.self,
lang_zh.identifier: lang_zh.self,
lang_zhHansHK.identifier: lang_zhHansHK.self,
lang_yueHans.identifier: lang_yueHans.self,
lang_yueHant.identifier: lang_yueHant.self,
lang_zhHansMO.identifier: lang_zhHansMO.self,
lang_zhHansSG.identifier: lang_zhHansSG.self,
lang_zhHantHK.identifier: lang_zhHantHK.self,
lang_zhHant.identifier: lang_zhHant.self,
lang_zu.identifier: lang_zu.self
]
/// Return all languages supported by the library for relative date formatting
public static var allLanguages: [RelativeFormatterLang.Type] {
return Array(RelativeFormatter.shared.languagesMap.values)
}
private init() {}
/// Add/replace a new language table.
///
/// - Parameter lang: language file type
public static func addLanguage(_ lang: RelativeFormatterLang.Type) {
self.shared.languagesMap[lang.identifier] = lang // replace or add
self.shared.languagesCache.removeValue(forKey: lang.identifier) // cleanup cache
}
/// Return the language table for a specified locale.
/// If not loaded yet a new instance of the table is loaded and cached.
///
/// - Parameter locale: locale to load
/// - Returns: language table
private func language(forLocale locale: Locale) -> RelativeFormatterLang {
let localeId = (locale.collatorIdentifier ?? Locales.english.toLocale().collatorIdentifier!)
guard let table = self.languagesCache[localeId] else {
var tableType = self.languagesMap[localeId]
if tableType == nil {
tableType = self.languagesMap[localeId.components(separatedBy: "-").first!]
if tableType == nil {
return language(forLocale: Locales.english.toLocale())
}
}
let instanceOfTable = tableType!.init()
self.languagesCache[localeId] = instanceOfTable
return instanceOfTable
}
return table
}
/// Implementation of the protocol for DateToStringTransformable.
public static func format(_ date: DateRepresentable, options: Any?) -> String {
let dateToFormat = (date as? DateInRegion ?? DateInRegion(date.date, region: SwiftDate.defaultRegion))
return RelativeFormatter.format(date: dateToFormat, style: (options as? Style), locale: date.region.locale)
}
/// Return relative formatted string result of comparison of two passed dates.
///
/// - Parameters:
/// - date: date to compare
/// - toDate: date to compare against for (if `nil` current date in the same region of `date` is used)
/// - style: style of the relative formatter.
/// - locale: locale to use; if not passed the `date`'s region locale is used.
/// - Returns: formatted string, empty string if formatting fails
public static func format(date: DateRepresentable, to toDate: DateRepresentable? = nil,
style: Style?, locale fixedLocale: Locale? = nil) -> String {
let refDate = (toDate ?? date.region.nowInThisRegion()) // a now() date is created if no reference is passed
let options = (style ?? RelativeFormatter.defaultStyle()) // default style if not used
let locale = (fixedLocale ?? date.region.locale) // date's locale is used if no value is forced
// how much time elapsed (in seconds)
let elapsed = (refDate.date.timeIntervalSince1970 - date.date.timeIntervalSince1970)
// get first suitable flavour for a given locale
let (flavour, localeData) = suitableFlavour(inList: options.flavours, forLocale: locale)
// get all units which can be represented by the locale data for required style
let allUnits = suitableUnits(inLocaleData: localeData, requiredUnits: options.allowedUnits)
guard allUnits.count > 0 else {
debugPrint("Required units in style were not found in locale spec. Returning empty string")
return ""
}
guard let suitableRule = ruleToRepresent(timeInterval: abs(elapsed),
referenceInterval: refDate.date.timeIntervalSince1970,
units: allUnits,
gradation: options.gradation) else {
// If no time unit is suitable, just output an empty string.
// E.g. when "now" unit is not available
// and "second" has a threshold of `0.5`
// (e.g. the "canonical" grading scale).
return ""
}
if let customFormat = suitableRule.customFormatter {
return customFormat(date)
}
var amount = (abs(elapsed) / suitableRule.unit.factor)
// Apply granularity to the time amount
// (and fallback to the previous step
// if the first level of granularity
// isn't met by this amount)
if let granularity = suitableRule.granularity {
// Recalculate the elapsed time amount based on granularity
amount = round(amount / granularity) * granularity
}
let value: Double = -1.0 * Double(elapsed.sign) * round(amount)
let formatString = relativeFormat(locale: locale, flavour: flavour, value: value, unit: suitableRule.unit)
return formatString.replacingOccurrences(of: "{0}", with: String(Int(abs(value))))
}
private static func relativeFormat(locale: Locale, flavour: Flavour, value: Double, unit: Unit) -> String {
let table = RelativeFormatter.shared.language(forLocale: locale)
guard let styleTable = table.flavours[flavour.rawValue] as? [String: Any] else {
return ""
}
if let fixedValue = styleTable[unit.rawValue] as? String {
return fixedValue
}
guard let unitRules = styleTable[unit.rawValue] as? [String: Any] else {
return ""
}
// Choose either "past" or "future" based on time `value` sign.
// If "past" is same as "future" then they're stored as "other".
// If there's only "other" then it's being collapsed.
let quantifierKey = (value <= 0 ? "past" : "future")
if let fixedValue = unitRules[quantifierKey] as? String {
return fixedValue
} else if let quantifierRules = unitRules[quantifierKey] as? [String: Any] {
// plurar/translations forms
// "other" rule is supposed to always be present.
// If only "other" rule is present then "rules" is not an object and is a string.
let quantifier = (table.quantifyKey(forValue: abs(value)) ?? .other).rawValue
return (quantifierRules[quantifier] as? String ?? "")
} else {
return ""
}
}
/// Return the first suitable flavour into the list which is available for a given locale.
///
/// - Parameters:
/// - flavours: ordered flavours.
/// - locale: locale to use.
/// - Returns: a pair of found flavor and locale table
private static func suitableFlavour(inList flavours: [Flavour], forLocale locale: Locale) -> (flavour: Flavour, locale: [String: Any]) {
let localeData = RelativeFormatter.shared.language(forLocale: locale) // get the locale table
for flavour in flavours {
if let flavourData = localeData.flavours[flavour.rawValue] as? [String: Any] {
return (flavour, flavourData) // found our required flavor in passed locale
}
}
// long must be always present
// swiftlint:disable force_cast
return (.long, localeData.flavours[Flavour.long.rawValue] as! [String: Any])
}
/// Return a list of available time units in locale filtered by required units of style.
/// If resulting array if empty there is not any time unit which can be rapresented with given locale
/// so formatting fails.
///
/// - Parameters:
/// - localeData: local table.
/// - styleUnits: required time units.
/// - Returns: available units.
private static func suitableUnits(inLocaleData localeData: [String: Any], requiredUnits styleUnits: [Unit]?) -> [Unit] {
let localeUnits: [Unit] = localeData.keys.compactMap { Unit(rawValue: $0) }
guard let restrictedStyleUnits = styleUnits else { return localeUnits } // no restrictions
return localeUnits.filter({ restrictedStyleUnits.contains($0) })
}
/// Return the best rule in gradation to represent given time interval.
///
/// - Parameters:
/// - elapsed: elapsed interval to represent
/// - referenceInterval: reference interval
/// - units: units
/// - gradation: gradation
/// - Returns: best rule to represent
private static func ruleToRepresent(timeInterval elapsed: TimeInterval, referenceInterval: TimeInterval, units: [Unit], gradation: Gradation) -> Gradation.Rule? {
// Leave only allowed time measurement units.
// E.g. omit "quarter" unit.
let filteredGradation = gradation.filtered(byUnits: units)
// If no steps of gradation fit the conditions
// then return nothing.
guard gradation.count > 0 else {
return nil
}
// Find the most appropriate gradation step
let i = findGradationStep(elapsed: elapsed, now: referenceInterval, gradation: filteredGradation)
guard i >= 0 else {
return nil
}
let step = filteredGradation[i]!
// Apply granularity to the time amount
// (and fall back to the previous step
// if the first level of granularity
// isn't met by this amount)
if let granurality = step.granularity {
// Recalculate the elapsed time amount based on granularity
let amount = round( (elapsed / step.unit.factor) / granurality) * granurality
// If the granularity for this step
// is too high, then fallback
// to the previous step of gradation.
// (if there is any previous step of gradation)
if amount == 0 && i > 0 {
return filteredGradation[i - 1]
}
}
return step
}
private static func findGradationStep(elapsed: TimeInterval, now: TimeInterval, gradation: Gradation, step: Int = 0) -> Int {
// If the threshold for moving from previous step
// to this step is too high then return the previous step.
let fromGradation = gradation[step - 1]
let currentGradation = gradation[step]!
let thresholdValue = threshold(from: fromGradation, to: currentGradation, now: now)
if let t = thresholdValue, elapsed < t {
return step - 1
}
// If it's the last step of gradation then return it.
if step == (gradation.count - 1) {
return step
}
// Move to the next step.
return findGradationStep(elapsed: elapsed, now: now, gradation: gradation, step: step + 1)
}
/// Evaluate threshold.
private static func threshold(from fromRule: Gradation.Rule?, to toRule: Gradation.Rule, now: TimeInterval) -> Double? {
var threshold: Double? = nil
// Allows custom thresholds when moving
// from a specific step to a specific step.
if let fromStepUnit = fromRule?.unit {
threshold = toRule.thresholdPrevious?[fromStepUnit]
}
// If no custom threshold is set for this transition
// then use the usual threshold for the next step.
if threshold == nil {
threshold = toRule.threshold?.evaluateForTimeInterval(now)
}
return threshold
}
}
| apache-2.0 | 580f5d15c3ff1ce5e09bf627233923dd | 37.608696 | 163 | 0.718336 | 3.356905 | false | false | false | false |
szpnygo/firefox-ios | Storage/Clients.swift | 20 | 2185 | /* 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 Shared
public struct RemoteClient: Equatable {
public let guid: GUID?
public let modified: Timestamp
public let name: String
public let type: String?
let version: String?
let protocols: [String]?
let os: String?
let appPackage: String?
let application: String?
let formfactor: String?
let device: String?
// Requires a valid ClientPayload (: CleartextPayloadJSON: JSON).
public init(json: JSON, modified: Timestamp) {
self.guid = json["id"].asString!
self.modified = modified
self.name = json["name"].asString!
self.type = json["type"].asString
self.version = json["version"].asString
self.protocols = jsonsToStrings(json["protocols"].asArray)
self.os = json["os"].asString
self.appPackage = json["appPackage"].asString
self.application = json["application"].asString
self.formfactor = json["formfactor"].asString
self.device = json["device"].asString
}
public init(guid: GUID?, name: String, modified: Timestamp, type: String?, formfactor: String?, os: String?) {
self.guid = guid
self.name = name
self.modified = modified
self.type = type
self.formfactor = formfactor
self.os = os
self.device = nil
self.appPackage = nil
self.application = nil
self.version = nil
self.protocols = nil
}
}
// TODO: should this really compare tabs?
public func ==(lhs: RemoteClient, rhs: RemoteClient) -> Bool {
return lhs.guid == rhs.guid &&
lhs.name == rhs.name &&
lhs.modified == rhs.modified &&
lhs.type == rhs.type &&
lhs.formfactor == rhs.formfactor &&
lhs.os == rhs.os
}
extension RemoteClient: Printable {
public var description: String {
return "<RemoteClient GUID: \(guid), name: \(name), modified: \(modified), type: \(type), formfactor: \(formfactor), OS: \(os)>"
}
} | mpl-2.0 | 9ff89d3a6097a5dac2cf051e064ff89d | 30.681159 | 136 | 0.624256 | 4.27593 | false | false | false | false |
facetdigital/QuiltView | QuiltView/Classes/Constants.swift | 1 | 659 | //
// Constants.swift
// QuiltView
//
// Created by Jeremy Groh on 01/09/17
// Copyright © 2017 Facet Digital, LLC. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
struct String {
static let CollectionViewInsetsForItem = "collectionView:layout:insetsForItemAtIndexPath:";
static let CollectionViewBlockSizeForItem = "collectionView:layout:blockSizeForItemAtIndexPath:";
}
struct ImageCollection {
// The numbers below represent the minimum image size in the collection view
static let ImageWidth = 314
static let ImageHeight = 314
}
struct Int {
static let BaseZIndex = 5000;
}
}
| mit | 712d2c8b9efe4a3d7c17334354efb213 | 23.37037 | 101 | 0.721884 | 4.416107 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Utility/XmlParser.swift | 1 | 3174 | import Foundation
internal struct XmlElement {
internal var attributes: [String: String]
internal var children: [XmlElement]
internal var path: [String]
internal var text: String
internal var name: String {
return path.last ?? ""
}
internal init(attributes: [String: String], children: [XmlElement], path: [String], text: String) {
self.attributes = attributes
self.children = children
self.path = path
self.text = text
}
}
internal final class XmlParser {
internal func parse(xml data: Data) throws -> XmlElement {
let parser = try ActualParser(xml: data)
return parser.rootElement
}
}
private final class ActualParser: NSObject {
fileprivate var currentText = ""
fileprivate var elementBuilder: ElementBuilder?
fileprivate var elementBuilderStack = [ElementBuilder]()
fileprivate var elementPath = [String]()
fileprivate var error: Error?
fileprivate let parser: XMLParser
fileprivate var rootElement: XmlElement!
fileprivate init(xml data: Data) throws {
self.parser = XMLParser(data: data)
super.init()
parser.delegate = self
parser.parse()
parser.delegate = nil
if let error = self.error {
throw error
}
if self.rootElement == nil {
throw TrackerError(message: "Configuration xml is invalid. Its probably don't have xml content to parce")
}
}
fileprivate final class ElementBuilder {
fileprivate let attributes: [String: String]
fileprivate var children = [XmlElement]()
fileprivate let path: [String]
fileprivate var text = ""
fileprivate init(attributes: [String: String], path: [String]) {
self.attributes = attributes
self.path = path
}
fileprivate func build() -> XmlElement {
return XmlElement(attributes: attributes, children: children, path: path, text: text)
}
}
}
extension ActualParser: XMLParserDelegate {
@objc
fileprivate func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName: String?) {
guard let elementBuilder = elementBuilder else {
fatalError()
}
currentText = currentText.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
elementBuilder.text = currentText
let element = elementBuilder.build()
if let parentElementBuilder = elementBuilderStack.popLast() {
parentElementBuilder.children.append(element)
self.elementBuilder = parentElementBuilder
} else {
rootElement = element
self.elementBuilder = nil
}
currentText = ""
elementPath.removeLast()
}
@objc
fileprivate func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName: String?, attributes: [String: String]) {
currentText = ""
elementPath.append(elementName)
if let elementBuilder = elementBuilder {
elementBuilderStack.append(elementBuilder)
}
elementBuilder = ElementBuilder(attributes: attributes, path: elementPath)
}
@objc
fileprivate func parser(_ parser: XMLParser, foundCharacters string: String) {
currentText += string
}
@objc
fileprivate func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
if error == nil {
error = parseError
}
}
}
| mit | 82ffea2d2ead5f6e370791846486c736 | 23.604651 | 161 | 0.727473 | 4.100775 | false | false | false | false |
KikurageChan/SimpleConsoleView | SimpleConsoleView/Classes/Views/SimpleConsoleView.swift | 1 | 5233 | //
// SimpleConsoleView.swift
// SimpleConsoleView
//
// Created by 木耳ちゃん on 2017/01/12.
// Copyright © 2017年 木耳ちゃん. All rights reserved.
//
import UIKit
final public class SimpleConsoleView: UIView {
class var getInstance : SimpleConsoleView {
struct Static {
static let instance : SimpleConsoleView = SimpleConsoleView()
}
return Static.instance
}
private(set) var screenSize: CGSize!
private(set) var defaultFrame: CGRect!
private(set) var minSize: CGSize!
private(set) var hideFrame: CGRect!
private(set) var lastFrame: CGRect!
private(set) var isAnimating = false
@IBOutlet weak var topLineView: UIView!
@IBOutlet weak var bottomLineView: UIView!
@IBOutlet weak var hideButton: HideButton!
@IBOutlet weak var dotImageView: DotImageView!
@IBOutlet weak var swipeableView: SwipeableView!
@IBOutlet weak var trashButton: TrashButton!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var toolBar: UIView!
public static var backColor = UIColor.white {
didSet { getInstance.textView.backgroundColor = backColor }
}
public static var barColor = UIColor(hex: 0xEBEBF1) {
didSet { getInstance.toolBar.backgroundColor = barColor }
}
public static var barLineColor = UIColor(hex: 0x979797) {
didSet {
getInstance.topLineView.backgroundColor = barLineColor
getInstance.bottomLineView.backgroundColor = barLineColor
}
}
public static var barTintColor = UIColor(hex: 0x979797) {
didSet {
getInstance.hideButton.tintColor = barTintColor
getInstance.dotImageView.tintColor = barTintColor
getInstance.trashButton.tintColor = barTintColor
}
}
public static var textColor = UIColor.black {
didSet { getInstance.textView.textColor = textColor }
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private init() {
screenSize = UIScreen.main.bounds.size
defaultFrame = CGRect(x: 0, y: screenSize.height - 150, width: screenSize.width, height: 150)
minSize = CGSize(width: UIScreen.main.bounds.width, height: 44)
hideFrame = CGRect(origin: CGPoint(x: 0, y: screenSize.height - minSize.height), size: minSize)
lastFrame = defaultFrame
super.init(frame: defaultFrame)
let pod = Bundle(for: self.classForCoder)
let path = pod.path(forResource: "SimpleConsoleView", ofType: "bundle")!
let bundle = Bundle(path: path)
let view = UINib(nibName: "SimpleConsoleView", bundle: bundle).instantiate(withOwner: self, options: nil).first as! UIView
autoresizesSubviews = true
view.frame = bounds
addSubview(view)
swipeableView.delegate = self
}
@IBAction func hideAction(_ sender: Any) {
if !hideButton.isPressed {
isAnimating = true
hideButton.isPressed = true
lastFrame = frame
UIView.animate(withDuration: 0.5, animations: {
self.frame.origin = self.hideFrame.origin
}, completion: { finish in
self.frame.size = self.hideFrame.size
self.isAnimating = false
})
}else {
isAnimating = true
hideButton.isPressed = false
UIView.animate(withDuration: 0.5, animations: {
self.frame = self.lastFrame
}, completion: { finish in
self.isAnimating = false
})
}
}
@IBAction func trashAction(_ sender: Any) {
textView.text = ""
}
public func display(_ text: String) {
textView.text = textView.text + text
if textView.frame.size.height <= textView.sizeThatFits(textView.frame.size).height {
textView.contentOffset = CGPoint(x: 0, y: textView.contentSize.height - textView.frame.size.height)
}
}
public func display(atNewLine text: String) {
textView.text = textView.text + text
if textView.frame.size.height <= textView.sizeThatFits(textView.frame.size).height {
textView.contentOffset = CGPoint(x: 0, y: textView.contentSize.height - textView.frame.size.height)
}
textView.text = textView.text + "\n"
}
override public var canBecomeFirstResponder: Bool {
return true
}
override public func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == UIEventSubtype.motionShake {
isHidden ? fadeIn() : fadeOut()
}
}
}
extension SimpleConsoleView: SwipeableViewDelegate {
func touch() {
becomeFirstResponder()
}
func swipe(vertical d: CGFloat) {
if isAnimating { return }
//over top
if frame.origin.y + d < minSize.height { return }
//over down
if frame.origin.y + d > UIScreen.main.bounds.height - minSize.height { return }
frame.origin.y += d
frame.size.height -= d
hideButton.isPressed = frame.size.height <= minSize.height
}
}
| mit | bb5fbdf840bfafa701350e3b1e99516f | 34.684932 | 130 | 0.629942 | 4.706414 | false | false | false | false |
imeraj/TestApp-Vapor1.0 | Sources/App/Controllers/AuthController.swift | 1 | 1924 | import Vapor
import HTTP
import SwiftyBeaverVapor
import SwiftyBeaver
import Auth
import Foundation
final class AuthController: ResourceRepresentable {
let drop: Droplet
let log: SwiftyBeaverVapor
init(droplet: Droplet) {
self.drop = droplet
self.log = droplet.log as! SwiftyBeaverVapor
}
func login(request: Request) throws -> ResponseRepresentable {
log.debug("Request: \(request.headers)")
guard let credentials = request.auth.header?.basic else {
throw Abort.badRequest
}
try request.auth.login(credentials, persist: true)
try request.session().data["timestamp"] = Node(Int(NSDate().timeIntervalSince1970.doubleValue))
return JSON(["message": "Login successful!"])
}
func logout(request: Request) throws -> ResponseRepresentable {
log.debug("Request: \(request.headers)")
// workaround for strage cookie set during logout: remove cookies from request
try request.session().destroy()
request.cookies.removeAll()
guard let _ = try request.auth.user() as? User else {
throw UserError.noSuchUser
}
try request.auth.logout()
if request.accept.prefers("html") {
let response = Response(redirect: "/")
return response
} else {
return JSON(["message": "Logout successful!"])
}
}
func register(request: Request) throws -> ResponseRepresentable {
log.debug("Request: \(request.headers)")
guard let credentials = request.auth.header?.basic else {
throw Abort.badRequest
}
_ = try User.register(credentials: credentials)
return JSON(["message": "Registration successful!"])
}
func makeResource() -> Resource<User> {
return Resource()
}
}
| mit | ba6c333b45493ee76474e9795bfe8c6e | 27.716418 | 103 | 0.608628 | 5.144385 | false | false | false | false |
myfreeweb/freepass | ios/Freepass/Freepass/RxStuff.swift | 1 | 1074 | import Foundation
import RxSwift
import RxCocoa
// https://github.com/ReactiveX/RxSwift/blob/master/RxExample/RxExample/Operators.swift#L20
// Two way binding operator between control property and variable, that's all it takes
infix operator <-> {}
func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
let bindToUIDisposable = variable.asObservable().bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return StableCompositeDisposable.create(bindToUIDisposable, bindToVariable)
}
func transformBind<T1, T2>(property: ControlProperty<T1>, variable: Variable<T2>, propToVar: T1 -> T2, varToProp: T2 -> T1) -> Disposable {
let bindToUIDisposable = variable.asObservable().map(varToProp).bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = propToVar(n)
}, onCompleted: {
bindToUIDisposable.dispose()
})
return StableCompositeDisposable.create(bindToUIDisposable, bindToVariable)
} | unlicense | 2afdc64cdabd84c15f2bd4b2b8db34b0 | 34.833333 | 139 | 0.75419 | 3.835714 | false | false | false | false |
fttios/PrcticeSwift3.0 | Program/day01/Swift3.0-011-字典/Swift3.0-011-字典/ViewController.swift | 1 | 3573 | //
// ViewController.swift
// Swift3.0-011-字典
//
// Created by tan on 2017/2/28.
// Copyright © 2017年 tantan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
demo3()
}
// MARK: - 定义
func demo() {
// OC 定义字典使用 {}
// Swift 中同样使用 []
// [KEY: VALUE] -> [String: NSObject]
let dict = ["name": "张","age": 18] as [String : Any]
print(dict)
// 定义字典的数组 -- 提示:这种格式在开发中使用的最多!
/**
An object that may be converted to JSON must have the following properties:
所有对象能够被转换成 JSON(字典或数组)必须遵守以下规则
- Top level object is an NSArray or NSDictionary
- 顶级节点是数组 / 字典
- All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
- 所有的对象必须是 NSString, NSNumber or NSNull
- NSArray, NSDictionary 可以嵌套使用
- All dictionary keys are NSStrings
- 所有的 key 都是 NSStrings
- NSNumbers are not NaN or infinity
- NSNumbers 不能为 nil 或者无穷大
*/
// 定义字典的数组 -- 提示:这种格式在开发中使用的最多!
let array: [[String: Any]] = [
["name": "张","age": 18],
["name": "李","age": 100]
]
print(array)
}
// MARK: - 增删改
func demo1() {
// 可变/不可变
var dict = ["name": "张","age": 18] as [String : Any]
// 新增 - 如果 Key 不存在,就是新增
dict["title"] = "大哥"
print(dict)
// 修改 - 字典中,是通过 Key 取值,key 在字典中必须是唯一的!
// 如果 Key 存在,就是修改
dict["name"] = "大西瓜"
print(dict)
// 删除 - 直接给定 Key
// *** 科普,字典是通过 Key 来定位值的,Key 必须是可以 ‘hash 哈希’ MD5一种
// hash 就是将字符串变成唯一的‘整数’,便于查找,提高字典遍历的速度
dict.removeValue(forKey: "age")
print(dict)
}
// MARK: - 遍历
func demo2() {
let dict = ["name": "张","age": 18,"title": "老板"] as [String : Any]
// 元组 (key: String, value: Any)
for e in dict {
print(e)
print("\(e.key) \(e.value)")
}
print("------")
/**
前面的是 key
后面的是 value
具体的名字可以随便
OC 遍历 for in 只能获取到 KEY
*/
for (key,value) in dict {
print("\(key) \(value)")
}
}
// MARK: - 合并
func demo3() {
var dict1 = ["name": "张","age": 18,"title": "老板"] as [String : Any]
let dict2 = ["name": "大瓜","height": 1.9] as [String : Any]
// 将 dict2 合并到 dict1
// 提示:字典不能直接相加 dict1 = dict1 + dict2
// 思路:遍历 dict2 依次设置
// 如果 key 存在,会改变,不存在会新增!
for e in dict2 {
dict1[e.key] = dict2[e.key]
}
}
}
| mit | aef54e0b2fccf7725973ceebe1387948 | 22.376 | 84 | 0.448323 | 3.675472 | false | false | false | false |
kevin4thenguyen/socialCalendar | socialCalendar/AppDelegate.swift | 1 | 6712 | //
// AppDelegate.swift
// socialCalendar
//
// Created by Kevin Nguyen on 12/2/14.
// Copyright (c) 2014 AIT. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
class var sharedAppDelegate: AppDelegate {
return UIApplication.sharedApplication().delegate as AppDelegate
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// CRASH WHEN UNCOMMENTED
// Parse.enableLocalDatastore()
Parse.errorMessagesEnabled(true)
Parse.setApplicationId("aT9n1CHI0uX8lRxWi4OWRLXZ6etXGw3QebXFZuqt", clientKey: "eGTFi656tRFn3zG5Sv9HPqB0ovP4AJrDLYcSAEYk")
PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
saveContext()
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "hu.ait.socialCalendar" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("friends", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("socialCalendar.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| gpl-2.0 | 0b53d104945d158faa0d1c5be843decb | 53.569106 | 290 | 0.707986 | 5.664135 | false | false | false | false |
victorlin/ReactiveCocoa | ReactiveCocoa/Swift/Signal.swift | 1 | 60041 | import Foundation
import Result
/// A push-driven stream that sends Events over time, parameterized by the type
/// of values being sent (`Value`) and the type of failure that can occur
/// (`Error`). If no failures should be possible, NoError can be specified for
/// `Error`.
///
/// An observer of a Signal will see the exact same sequence of events as all
/// other observers. In other words, events will be sent to all observers at the
/// same time.
///
/// Signals are generally used to represent event streams that are already “in
/// progress,” like notifications, user input, etc. To represent streams that
/// must first be _started_, see the SignalProducer type.
///
/// A Signal is kept alive until either of the following happens:
/// 1. its input observer receives a terminating event; or
/// 2. it has no active observers, and is not being retained.
public final class Signal<Value, Error: Swift.Error> {
public typealias Observer = ReactiveCocoa.Observer<Value, Error>
/// The disposable returned by the signal generator. It would be disposed of
/// when the signal terminates.
private var generatorDisposable: Disposable?
/// The state of the signal. `nil` if the signal has terminated.
private let state: Atomic<SignalState<Value, Error>?>
/// Initialize a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// - note: The disposable returned from the closure will be automatically
/// disposed if a terminating event is sent to the observer. The
/// Signal itself will remain alive until the observer is released.
///
/// - parameters:
/// - generator: A closure that accepts an implicitly created observer
/// that will act as an event emitter for the signal.
public init(_ generator: (Observer) -> Disposable?) {
state = Atomic(SignalState())
/// Used to ensure that events are serialized during delivery to observers.
let sendLock = NSLock()
sendLock.name = "org.reactivecocoa.ReactiveCocoa.Signal"
/// When set to `true`, the Signal should interrupt as soon as possible.
let interrupted = Atomic(false)
let observer = Observer { [weak self] event in
guard let signal = self else {
return
}
func interrupt() {
if let state = signal.state.swap(nil) {
for observer in state.observers {
observer.sendInterrupted()
}
}
}
if case .interrupted = event {
// Normally we disallow recursive events, but `interrupted` is
// kind of a special snowflake, since it can inadvertently be
// sent by downstream consumers.
//
// So we'll flag Interrupted events specially, and if it
// happened to occur while we're sending something else, we'll
// wait to deliver it.
interrupted.value = true
if sendLock.try() {
interrupt()
sendLock.unlock()
signal.generatorDisposable?.dispose()
}
} else {
if let state = (event.isTerminating ? signal.state.swap(nil) : signal.state.value) {
sendLock.lock()
for observer in state.observers {
observer.action(event)
}
let shouldInterrupt = !event.isTerminating && interrupted.value
if shouldInterrupt {
interrupt()
}
sendLock.unlock()
if event.isTerminating || shouldInterrupt {
// Dispose only after notifying observers, so disposal
// logic is consistently the last thing to run.
signal.generatorDisposable?.dispose()
}
}
}
}
generatorDisposable = generator(observer)
}
deinit {
if state.swap(nil) != nil {
// As the signal can deinitialize only when it has no observers attached,
// only the generator disposable has to be disposed of at this point.
generatorDisposable?.dispose()
}
}
/// A Signal that never sends any events to its observers.
public static var never: Signal {
return self.init { _ in nil }
}
/// A Signal that completes immediately without emitting any value.
public static var empty: Signal {
return self.init { observer in
observer.sendCompleted()
return nil
}
}
/// Create a Signal that will be controlled by sending events to the given
/// observer.
///
/// - note: The Signal will remain alive until a terminating event is sent
/// to the observer.
///
/// - returns: A tuple made of signal and observer.
public static func pipe() -> (Signal, Observer) {
var observer: Observer!
let signal = self.init { innerObserver in
observer = innerObserver
return nil
}
return (signal, observer)
}
/// Observe the Signal by sending any future events to the given observer.
///
/// - note: If the Signal has already terminated, the observer will
/// immediately receive an `interrupted` event.
///
/// - parameters:
/// - observer: An observer to forward the events to.
///
/// - returns: An optional `Disposable` which can be used to disconnect the
/// observer.
@discardableResult
public func observe(_ observer: Observer) -> Disposable? {
var token: RemovalToken?
state.modify {
$0?.retainedSignal = self
token = $0?.observers.insert(observer)
}
if let token = token {
return ActionDisposable { [weak self] in
if let strongSelf = self {
strongSelf.state.modify { state in
state?.observers.remove(using: token)
if state?.observers.isEmpty ?? false {
state!.retainedSignal = nil
}
}
}
}
} else {
observer.sendInterrupted()
return nil
}
}
}
private struct SignalState<Value, Error: Swift.Error> {
var observers: Bag<Signal<Value, Error>.Observer> = Bag()
var retainedSignal: Signal<Value, Error>?
}
public protocol SignalProtocol {
/// The type of values being sent on the signal.
associatedtype Value
/// The type of error that can occur on the signal. If errors aren't
/// possible then `NoError` can be used.
associatedtype Error: Swift.Error
/// Extracts a signal from the receiver.
var signal: Signal<Value, Error> { get }
/// Observes the Signal by sending any future events to the given observer.
@discardableResult
func observe(_ observer: Signal<Value, Error>.Observer) -> Disposable?
}
extension Signal: SignalProtocol {
public var signal: Signal {
return self
}
}
extension SignalProtocol {
/// Convenience override for observe(_:) to allow trailing-closure style
/// invocations.
///
/// - parameters:
/// - action: A closure that will accept an event of the signal
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observe(_ action: Signal<Value, Error>.Observer.Action) -> Disposable? {
return observe(Observer(action))
}
/// Observe the `Signal` by invoking the given callback when `next` or
/// `failed` event are received.
///
/// - parameters:
/// - result: A closure that accepts instance of `Result<Value, Error>`
/// enum that contains either a `Success(Value)` or
/// `Failure<Error>` case.
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeResult(_ result: @escaping (Result<Value, Error>) -> Void) -> Disposable? {
return observe(
Observer(
next: { result(.success($0)) },
failed: { result(.failure($0)) }
)
)
}
/// Observe the `Signal` by invoking the given callback when a `completed`
/// event is received.
///
/// - parameters:
/// - completed: A closure that is called when `completed` event is
/// received.
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeCompleted(_ completed: @escaping () -> Void) -> Disposable? {
return observe(Observer(completed: completed))
}
/// Observe the `Signal` by invoking the given callback when a `failed`
/// event is received.
///
/// - parameters:
/// - error: A closure that is called when failed event is received. It
/// accepts an error parameter.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
@discardableResult
public func observeFailed(_ error: @escaping (Error) -> Void) -> Disposable? {
return observe(Observer(failed: error))
}
/// Observe the `Signal` by invoking the given callback when an
/// `interrupted` event is received. If the Signal has already terminated,
/// the callback will be invoked immediately.
///
/// - parameters:
/// - interrupted: A closure that is invoked when `interrupted` event is
/// received
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeInterrupted(_ interrupted: @escaping () -> Void) -> Disposable? {
return observe(Observer(interrupted: interrupted))
}
}
extension SignalProtocol where Error == NoError {
/// Observe the Signal by invoking the given callback when `next` events are
/// received.
///
/// - parameters:
/// - next: A closure that accepts a value when `next` event is received.
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeNext(_ next: @escaping (Value) -> Void) -> Disposable? {
return observe(Observer(next: next))
}
}
extension SignalProtocol {
/// Map each value in the signal to a new value.
///
/// - parameters:
/// - transform: A closure that accepts a value from the `next` event and
/// returns a new value.
///
/// - returns: A signal that will send new values.
public func map<U>(_ transform: @escaping (Value) -> U) -> Signal<U, Error> {
return Signal { observer in
return self.observe { event in
observer.action(event.map(transform))
}
}
}
/// Map errors in the signal to a new error.
///
/// - parameters:
/// - transform: A closure that accepts current error object and returns
/// a new type of error object.
///
/// - returns: A signal that will send new type of errors.
public func mapError<F>(_ transform: @escaping (Error) -> F) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
observer.action(event.mapError(transform))
}
}
}
/// Preserve only the values of the signal that pass the given predicate.
///
/// - parameters:
/// - predicate: A closure that accepts value and returns `Bool` denoting
/// whether value has passed the test.
///
/// - returns: A signal that will send only the values passing the given
/// predicate.
public func filter(_ predicate: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { (event: Event<Value, Error>) -> Void in
guard let value = event.value else {
observer.action(event)
return
}
if predicate(value) {
observer.sendNext(value)
}
}
}
}
}
extension SignalProtocol where Value: OptionalProtocol {
/// Unwrap non-`nil` values and forward them on the returned signal, `nil`
/// values are dropped.
///
/// - returns: A signal that sends only non-nil values.
public func skipNil() -> Signal<Value.Wrapped, Error> {
return filter { $0.optional != nil }.map { $0.optional! }
}
}
extension SignalProtocol {
/// Take up to `n` values from the signal and then complete.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to take from the signal.
///
/// - returns: A signal that will yield the first `count` values from `self`
public func take(first count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
return Signal { observer in
if count == 0 {
observer.sendCompleted()
return nil
}
var taken = 0
return self.observe { event in
guard let value = event.value else {
observer.action(event)
return
}
if taken < count {
taken += 1
observer.sendNext(value)
}
if taken == count {
observer.sendCompleted()
}
}
}
}
}
/// A reference type which wraps an array to auxiliate the collection of values
/// for `collect` operator.
private final class CollectState<Value> {
var values: [Value] = []
/// Collects a new value.
func append(_ value: Value) {
values.append(value)
}
/// Check if there are any items remaining.
///
/// - note: This method also checks if there weren't collected any values
/// and, in that case, it means an empty array should be sent as the
/// result of collect.
var isEmpty: Bool {
/// We use capacity being zero to determine if we haven't collected any
/// value since we're keeping the capacity of the array to avoid
/// unnecessary and expensive allocations). This also guarantees
/// retro-compatibility around the original `collect()` operator.
return values.isEmpty && values.capacity > 0
}
/// Removes all values previously collected if any.
func flush() {
// Minor optimization to avoid consecutive allocations. Can
// be useful for sequences of regular or similar size and to
// track if any value was ever collected.
values.removeAll(keepingCapacity: true)
}
}
extension SignalProtocol {
/// Collect all values sent by the signal then forward them as a single
/// array and complete.
///
/// - note: When `self` completes without collecting any value, it will send
/// an empty array of values.
///
/// - returns: A signal that will yield an array of values when `self`
/// completes.
public func collect() -> Signal<[Value], Error> {
return collect { _,_ in false }
}
/// Collect at most `count` values from `self`, forward them as a single
/// array and complete.
///
/// - note: When the count is reached the array is sent and the signal
/// starts over yielding a new array of values.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not have `count` values. Alternatively, if were
/// not collected any values will sent an empty array of values.
///
/// - precondition: `count` should be greater than zero.
///
public func collect(count: Int) -> Signal<[Value], Error> {
precondition(count > 0)
return collect { values in values.count == count }
}
/// Collect values that pass the given predicate then forward them as a
/// single array and complete.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not match `predicate`. Alternatively, if were not
/// collected any values will sent an empty array of values.
///
/// ````
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .observeNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(3)
/// observer.sendNext(4)
/// observer.sendNext(7)
/// observer.sendNext(1)
/// observer.sendNext(5)
/// observer.sendNext(6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
/// ````
///
/// - parameters:
/// - predicate: Predicate to match when values should be sent (returning
/// `true`) or alternatively when they should be collected
/// (where it should return `false`). The most recent value
/// (`next`) is included in `values` and will be the end of
/// the current array of values if the predicate returns
/// `true`.
///
/// - returns: A signal that collects values passing the predicate and, when
/// `self` completes, forwards them as a single array and
/// complets.
public func collect(_ predicate: @escaping (_ values: [Value]) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .next(value):
state.append(value)
if predicate(state.values) {
observer.sendNext(state.values)
state.flush()
}
case .completed:
if !state.isEmpty {
observer.sendNext(state.values)
}
observer.sendCompleted()
case let .failed(error):
observer.sendFailed(error)
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Repeatedly collect an array of values up to a matching `next` value.
/// Then forward them as single array and wait for next events.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not match `predicate`. Alternatively, if no
/// values were collected an empty array will be sent.
///
/// ````
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values, next in next == 7 }
/// .observeNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(1)
/// observer.sendNext(7)
/// observer.sendNext(7)
/// observer.sendNext(5)
/// observer.sendNext(6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
/// ````
///
/// - parameters:
/// - predicate: Predicate to match when values should be sent (returning
/// `true`) or alternatively when they should be collected
/// (where it should return `false`). The most recent value
/// (`next`) is not included in `values` and will be the
/// start of the next array of values if the predicate
/// returns `true`.
///
/// - returns: A signal that will yield an array of values based on a
/// predicate which matches the values collected and the next
/// value.
public func collect(_ predicate: @escaping (_ values: [Value], _ next: Value) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .next(value):
if predicate(state.values, value) {
observer.sendNext(state.values)
state.flush()
}
state.append(value)
case .completed:
if !state.isEmpty {
observer.sendNext(state.values)
}
observer.sendCompleted()
case let .failed(error):
observer.sendFailed(error)
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forward all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal that will yield `self` values on provided scheduler.
public func observe(on scheduler: SchedulerProtocol) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
scheduler.schedule {
observer.action(event)
}
}
}
}
}
private final class CombineLatestState<Value> {
var latestValue: Value?
var isCompleted = false
}
extension SignalProtocol {
private func observeWithStates<U>(_ signalState: CombineLatestState<Value>, _ otherState: CombineLatestState<U>, _ lock: NSLock, _ observer: Signal<(), Error>.Observer) -> Disposable? {
return self.observe { event in
switch event {
case let .next(value):
lock.lock()
signalState.latestValue = value
if otherState.latestValue != nil {
observer.sendNext()
}
lock.unlock()
case let .failed(error):
observer.sendFailed(error)
case .completed:
lock.lock()
signalState.isCompleted = true
if otherState.isCompleted {
observer.sendCompleted()
}
lock.unlock()
case .interrupted:
observer.sendInterrupted()
}
}
}
/// Combine the latest value of the receiver with the latest value from the
/// given signal.
///
/// - note: The returned signal will not send a value until both inputs have
/// sent at least one value each.
///
/// - note: If either signal is interrupted, the returned signal will also
/// be interrupted.
///
/// - parameters:
/// - otherSignal: A signal to combine `self`'s value with.
///
/// - returns: A signal that will yield a tuple containing values of `self`
/// and given signal.
public func combineLatest<U>(with other: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let lock = NSLock()
lock.name = "org.reactivecocoa.ReactiveCocoa.combineLatestWith"
let signalState = CombineLatestState<Value>()
let otherState = CombineLatestState<U>()
let onBothNext = {
observer.sendNext((signalState.latestValue!, otherState.latestValue!))
}
let observer = Signal<(), Error>.Observer(next: onBothNext, failed: observer.sendFailed, completed: observer.sendCompleted, interrupted: observer.sendInterrupted)
let disposable = CompositeDisposable()
disposable += self.observeWithStates(signalState, otherState, lock, observer)
disposable += other.observeWithStates(otherState, signalState, lock, observer)
return disposable
}
}
/// Delay `next` and `completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// - note: failed and `interrupted` events are always scheduled
/// immediately.
///
/// - parameters:
/// - interval: Interval to delay `next` and `completed` events by.
/// - scheduler: A scheduler to deliver delayed events on.
///
/// - returns: A signal that will delay `next` and `completed` events and
/// will yield them on given scheduler.
public func delay(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
return self.observe { event in
switch event {
case .failed, .interrupted:
scheduler.schedule {
observer.action(event)
}
case .next, .completed:
let date = scheduler.currentDate.addingTimeInterval(interval)
scheduler.schedule(after: date) {
observer.action(event)
}
}
}
}
}
/// Skip first `count` number of values then act as usual.
///
/// - parameters:
/// - count: A number of values to skip.
///
/// - returns: A signal that will skip the first `count` values, then
/// forward everything afterward.
public func skip(first count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
if count == 0 {
return signal
}
return Signal { observer in
var skipped = 0
return self.observe { event in
if case .next = event, skipped < count {
skipped += 1
} else {
observer.action(event)
}
}
}
}
/// Treat all Events from `self` as plain values, allowing them to be
/// manipulated just like any other value.
///
/// In other words, this brings Events “into the monad”.
///
/// - note: When a Completed or Failed event is received, the resulting
/// signal will send the Event itself and then complete. When an
/// Interrupted event is received, the resulting signal will send
/// the Event itself and then interrupt.
///
/// - returns: A signal that sends events as its values.
public func materialize() -> Signal<Event<Value, Error>, NoError> {
return Signal { observer in
return self.observe { event in
observer.sendNext(event)
switch event {
case .interrupted:
observer.sendInterrupted()
case .completed, .failed:
observer.sendCompleted()
case .next:
break
}
}
}
}
}
extension SignalProtocol where Value: EventProtocol, Error == NoError {
/// Translate a signal of `Event` _values_ into a signal of those events
/// themselves.
///
/// - returns: A signal that sends values carried by `self` events.
public func dematerialize() -> Signal<Value.Value, Value.Error> {
return Signal<Value.Value, Value.Error> { observer in
return self.observe { event in
switch event {
case let .next(innerEvent):
observer.action(innerEvent.event)
case .failed:
fatalError("NoError is impossible to construct")
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
}
extension SignalProtocol {
/// Inject side effects to be performed upon the specified signal events.
///
/// - parameters:
/// - event: A closure that accepts an event and is invoked on every
/// received event.
/// - next: A closure that accepts a value from `next` event.
/// - failed: A closure that accepts error object and is invoked for
/// failed event.
/// - completed: A closure that is invoked for `completed` event.
/// - interrupted: A closure that is invoked for `interrupted` event.
/// - terminated: A closure that is invoked for any terminating event.
/// - disposed: A closure added as disposable when signal completes.
///
/// - returns: A signal with attached side-effects for given event cases.
public func on(
event: ((Event<Value, Error>) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil,
terminated: (() -> Void)? = nil,
disposed: (() -> Void)? = nil,
next: ((Value) -> Void)? = nil
) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
_ = disposed.map(disposable.add)
disposable += signal.observe { receivedEvent in
event?(receivedEvent)
switch receivedEvent {
case let .next(value):
next?(value)
case let .failed(error):
failed?(error)
case .completed:
completed?()
case .interrupted:
interrupted?()
}
if receivedEvent.isTerminating {
terminated?()
}
observer.action(receivedEvent)
}
return disposable
}
}
}
private struct SampleState<Value> {
var latestValue: Value? = nil
var isSignalCompleted: Bool = false
var isSamplerCompleted: Bool = false
}
extension SignalProtocol {
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when`sampler` sends a `next` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A signal that will trigger the delivery of `next` event
/// from `self`.
///
/// - returns: A signal that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input signals have completed, or interrupt if
/// either input signal is interrupted.
public func sample<T>(with sampler: Signal<T, NoError>) -> Signal<(Value, T), Error> {
return Signal { observer in
let state = Atomic(SampleState<Value>())
let disposable = CompositeDisposable()
disposable += self.observe { event in
switch event {
case let .next(value):
state.modify {
$0.latestValue = value
}
case let .failed(error):
observer.sendFailed(error)
case .completed:
let shouldComplete: Bool = state.modify {
$0.isSignalCompleted = true
return $0.isSamplerCompleted
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
}
}
disposable += sampler.observe { event in
switch event {
case .next(let samplerValue):
if let value = state.value.latestValue {
observer.sendNext((value, samplerValue))
}
case .completed:
let shouldComplete: Bool = state.modify {
$0.isSamplerCompleted = true
return $0.isSignalCompleted
}
if shouldComplete {
observer.sendCompleted()
}
case .interrupted:
observer.sendInterrupted()
case .failed:
break
}
}
return disposable
}
}
/// Forward the latest value from `self` whenever `sampler` sends a `next`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A signal that will trigger the delivery of `next` event
/// from `self`.
///
/// - returns: A signal that will send values from `self`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input
/// signals have completed, or interrupt if either input signal
/// is interrupted.
public func sample(on sampler: Signal<(), NoError>) -> Signal<Value, Error> {
return sample(with: sampler)
.map { $0.0 }
}
/// Forwards events from `self` until `lifetime` ends, at which point the
/// returned signal will complete.
///
/// - parameters:
/// - lifetime: A lifetime whose `ended` signal will cause the returned
/// signal to complete.
///
/// - returns: A signal that will deliver events until `lifetime` ends.
public func take(during lifetime: Lifetime) -> Signal<Value, Error> {
return take(until: lifetime.ended)
}
/// Forward events from `self` until `trigger` sends a `next` or
/// `completed` event, at which point the returned signal will complete.
///
/// - parameters:
/// - trigger: A signal whose `next` or `completed` events will stop the
/// delivery of `next` events from `self`.
///
/// - returns: A signal that will deliver events until `trigger` sends
/// `next` or `completed` events.
public func take(until trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
disposable += self.observe(observer)
disposable += trigger.observe { event in
switch event {
case .next, .completed:
observer.sendCompleted()
case .failed, .interrupted:
break
}
}
return disposable
}
}
/// Do not forward any values from `self` until `trigger` sends a `next` or
/// `completed` event, at which point the returned signal behaves exactly
/// like `signal`.
///
/// - parameters:
/// - trigger: A signal whose `next` or `completed` events will start the
/// deliver of events on `self`.
///
/// - returns: A signal that will deliver events once the `trigger` sends
/// `next` or `completed` events.
public func skip(until trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = SerialDisposable()
disposable.innerDisposable = trigger.observe { event in
switch event {
case .next, .completed:
disposable.innerDisposable = self.observe(observer)
case .failed, .interrupted:
break
}
}
return disposable
}
}
/// Forward events from `self` with history: values of the returned signal
/// are a tuples whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A signal that sends tuples that contain previous and current
/// sent values of `self`.
public func combinePrevious(_ initial: Value) -> Signal<(Value, Value), Error> {
return scan((initial, initial)) { previousCombinedValues, newValue in
return (previousCombinedValues.1, newValue)
}
}
/// Send only the final value and then immediately completes.
///
/// - parameters:
/// - initial: Initial value for the accumulator.
/// - combine: A closure that accepts accumulator and sent value of
/// `self`.
///
/// - returns: A signal that sends accumulated value after `self` completes.
public func reduce<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> Signal<U, Error> {
// We need to handle the special case in which `signal` sends no values.
// We'll do that by sending `initial` on the output signal (before
// taking the last value).
let (scannedSignalWithInitialValue, outputSignalObserver) = Signal<U, Error>.pipe()
let outputSignal = scannedSignalWithInitialValue.take(last: 1)
// Now that we've got takeLast() listening to the piped signal, send
// that initial value.
outputSignalObserver.sendNext(initial)
// Pipe the scanned input signal into the output signal.
self.scan(initial, combine)
.observe(outputSignalObserver)
return outputSignal
}
/// Aggregate values into a single combined value. When `self` emits its
/// first value, `combine` is invoked with `initial` as the first argument
/// and that emitted value as the second argument. The result is emitted
/// from the signal returned from `scan`. That result is then passed to
/// `combine` as the first argument when the next value is emitted, and so
/// on.
///
/// - parameters:
/// - initial: Initial value for the accumulator.
/// - combine: A closure that accepts accumulator and sent value of
/// `self`.
///
/// - returns: A signal that sends accumulated value each time `self` emits
/// own value.
public func scan<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> Signal<U, Error> {
return Signal { observer in
var accumulator = initial
return self.observe { event in
observer.action(event.map { value in
accumulator = combine(accumulator, value)
return accumulator
})
}
}
}
}
extension SignalProtocol where Value: Equatable {
/// Forward only those values from `self` which are not duplicates of the
/// immedately preceding value.
///
/// - note: The first value is always forwarded.
///
/// - returns: A signal that does not send two equal values sequentially.
public func skipRepeats() -> Signal<Value, Error> {
return skipRepeats(==)
}
}
extension SignalProtocol {
/// Forward only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value.
///
/// - note: The first value is always forwarded.
///
/// - parameters:
/// - isRepeate: A closure that accepts previous and current values of
/// `self` and returns `Bool` whether these values are
/// repeating.
///
/// - returns: A signal that forwards only those values that fail given
/// `isRepeat` predicate.
public func skipRepeats(_ isRepeat: @escaping (Value, Value) -> Bool) -> Signal<Value, Error> {
return self
.scan((nil, false)) { (accumulated: (Value?, Bool), next: Value) -> (value: Value?, repeated: Bool) in
switch accumulated.0 {
case nil:
return (next, false)
case let prev? where isRepeat(prev, next):
return (prev, true)
case _?:
return (Optional(next), false)
}
}
.filter { !$0.repeated }
.map { $0.value }
.skipNil()
}
/// Do not forward any values from `self` until `predicate` returns false,
/// at which point the returned signal behaves exactly like `signal`.
///
/// - parameters:
/// - predicate: A closure that accepts a value and returns whether `self`
/// should still not forward that value to a `signal`.
///
/// - returns: A signal that sends only forwarded values from `self`.
public func skip(while predicate: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return Signal { observer in
var shouldSkip = true
return self.observe { event in
switch event {
case let .next(value):
shouldSkip = shouldSkip && predicate(value)
if !shouldSkip {
fallthrough
}
case .failed, .completed, .interrupted:
observer.action(event)
}
}
}
}
/// Forward events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A signal to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A signal which passes through `next`, failed, and
/// `interrupted` events from `self` until `replacement` sends
/// an event, at which point the returned signal will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement signal: Signal<Value, Error>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
let signalDisposable = self.observe { event in
switch event {
case .completed:
break
case .next, .failed, .interrupted:
observer.action(event)
}
}
disposable += signalDisposable
disposable += signal.observe { event in
signalDisposable?.dispose()
observer.action(event)
}
return disposable
}
}
/// Wait until `self` completes and then forward the final `count` values
/// on the returned signal.
///
/// - parameters:
/// - count: Number of last events to send after `self` completes.
///
/// - returns: A signal that receives up to `count` values from `self`
/// after `self` completes.
public func take(last count: Int) -> Signal<Value, Error> {
return Signal { observer in
var buffer: [Value] = []
buffer.reserveCapacity(count)
return self.observe { event in
switch event {
case let .next(value):
// To avoid exceeding the reserved capacity of the buffer,
// we remove then add. Remove elements until we have room to
// add one more.
while (buffer.count + 1) > count {
buffer.remove(at: 0)
}
buffer.append(value)
case let .failed(error):
observer.sendFailed(error)
case .completed:
buffer.forEach(observer.sendNext)
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forward any values from `self` until `predicate` returns false, at which
/// point the returned signal will complete.
///
/// - parameters:
/// - predicate: A closure that accepts value and returns `Bool` value
/// whether `self` should forward it to `signal` and continue
/// sending other events.
///
/// - returns: A signal that sends events until the values sent by `self`
/// pass the given `predicate`.
public func take(while predicate: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
if let value = event.value, !predicate(value) {
observer.sendCompleted()
} else {
observer.action(event)
}
}
}
}
}
private struct ZipState<Left, Right> {
var values: (left: [Left], right: [Right]) = ([], [])
var isCompleted: (left: Bool, right: Bool) = (false, false)
var isFinished: Bool {
return (isCompleted.left && values.left.isEmpty) || (isCompleted.right && values.right.isEmpty)
}
}
extension SignalProtocol {
/// Zip elements of two signals into pairs. The elements of any Nth pair
/// are the Nth elements of the two input signals.
///
/// - parameters:
/// - otherSignal: A signal to zip values with.
///
/// - returns: A signal that sends tuples of `self` and `otherSignal`.
public func zip<U>(with other: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let state = Atomic(ZipState<Value, U>())
let disposable = CompositeDisposable()
let flush = {
var tuple: (Value, U)?
var isFinished = false
state.modify { state in
guard !state.values.left.isEmpty && !state.values.right.isEmpty else {
isFinished = state.isFinished
return
}
tuple = (state.values.left.removeFirst(), state.values.right.removeFirst())
isFinished = state.isFinished
}
if let tuple = tuple {
observer.sendNext(tuple)
}
if isFinished {
observer.sendCompleted()
}
}
let onFailed = observer.sendFailed
let onInterrupted = observer.sendInterrupted
disposable += self.observe { event in
switch event {
case let .next(value):
state.modify {
$0.values.left.append(value)
}
flush()
case let .failed(error):
onFailed(error)
case .completed:
state.modify {
$0.isCompleted.left = true
}
flush()
case .interrupted:
onInterrupted()
}
}
disposable += other.observe { event in
switch event {
case let .next(value):
state.modify {
$0.values.right.append(value)
}
flush()
case let .failed(error):
onFailed(error)
case .completed:
state.modify {
$0.isCompleted.right = true
}
flush()
case .interrupted:
onInterrupted()
}
}
return disposable
}
}
/// Apply `operation` to values from `self` with `Success`ful results
/// forwarded on the returned signal and `Failure`s sent as failed events.
///
/// - parameters:
/// - operation: A closure that accepts a value and returns a `Result`.
///
/// - returns: A signal that receives `Success`ful `Result` as `next` event
/// and `Failure` as failed event.
public func attempt(_ operation: @escaping (Value) -> Result<(), Error>) -> Signal<Value, Error> {
return attemptMap { value in
return operation(value).map {
return value
}
}
}
/// Apply `operation` to values from `self` with `Success`ful results mapped
/// on the returned signal and `Failure`s sent as failed events.
///
/// - parameters:
/// - operation: A closure that accepts a value and returns a result of
/// a mapped value as `Success`.
///
/// - returns: A signal that sends mapped values from `self` if returned
/// `Result` is `Success`ful, failed events otherwise.
public func attemptMap<U>(_ operation: @escaping (Value) -> Result<U, Error>) -> Signal<U, Error> {
return Signal { observer in
self.observe { event in
switch event {
case let .next(value):
operation(value).analysis(
ifSuccess: observer.sendNext,
ifFailure: observer.sendFailed
)
case let .failed(error):
observer.sendFailed(error)
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If the input signal terminates while a value is being throttled,
/// that value will be discarded and the returned signal will
/// terminate immediately.
///
/// - note: If the device time changed backwords before previous date while
/// a value is being throttled, and if there is a new value sent,
/// the new value will be passed anyway.
///
/// - parameters:
/// - interval: Number of seconds to wait between sent values.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal that sends values at least `interval` seconds
/// appart on a given scheduler.
public func throttle(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
let disposable = CompositeDisposable()
disposable += schedulerDisposable
disposable += self.observe { event in
guard let value = event.value else {
schedulerDisposable.innerDisposable = scheduler.schedule {
observer.action(event)
}
return
}
var scheduleDate: Date!
state.modify {
$0.pendingValue = value
let proposedScheduleDate: Date
if let previousDate = $0.previousDate, previousDate.compare(scheduler.currentDate) != .orderedDescending {
proposedScheduleDate = previousDate.addingTimeInterval(interval)
} else {
proposedScheduleDate = scheduler.currentDate
}
switch proposedScheduleDate.compare(scheduler.currentDate) {
case .orderedAscending:
scheduleDate = scheduler.currentDate
case .orderedSame: fallthrough
case .orderedDescending:
scheduleDate = proposedScheduleDate
}
}
schedulerDisposable.innerDisposable = scheduler.schedule(after: scheduleDate) {
let pendingValue: Value? = state.modify { state in
defer {
if state.pendingValue != nil {
state.pendingValue = nil
state.previousDate = scheduleDate
}
}
return state.pendingValue
}
if let pendingValue = pendingValue {
observer.sendNext(pendingValue)
}
}
}
return disposable
}
}
/// Debounce values sent by the receiver, such that at least `interval`
/// seconds pass after the receiver has last sent a value, then forward the
/// latest value on the given scheduler.
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If the input signal terminates while a value is being debounced,
/// that value will be discarded and the returned signal will
/// terminate immediately.
///
/// - parameters:
/// - interval: A number of seconds to wait before sending a value.
/// - scheduler: A scheduler to send values on.
///
/// - returns: A signal that sends values that are sent from `self` at least
/// `interval` seconds apart.
public func debounce(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> Signal<Value, Error> {
precondition(interval >= 0)
return self
.materialize()
.flatMap(.latest) { event -> SignalProducer<Event<Value, Error>, NoError> in
if event.isTerminating {
return SignalProducer(value: event).observe(on: scheduler)
} else {
return SignalProducer(value: event).delay(interval, on: scheduler)
}
}
.dematerialize()
}
}
extension SignalProtocol {
/// Forward only those values from `self` that have unique identities across
/// the set of all values that have been seen.
///
/// - note: This causes the identities to be retained to check for
/// uniqueness.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns identity
/// value.
///
/// - returns: A signal that sends unique values during its lifetime.
public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Signal<Value, Error> {
return Signal { observer in
var seenValues: Set<Identity> = []
return self
.observe { event in
switch event {
case let .next(value):
let identity = transform(value)
if !seenValues.contains(identity) {
seenValues.insert(identity)
fallthrough
}
case .failed, .completed, .interrupted:
observer.action(event)
}
}
}
}
}
extension SignalProtocol where Value: Hashable {
/// Forward only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// - note: This causes the values to be retained to check for uniqueness.
/// Providing a function that returns a unique value for each sent
/// value can help you reduce the memory footprint.
///
/// - returns: A signal that sends unique values during its lifetime.
public func uniqueValues() -> Signal<Value, Error> {
return uniqueValues { $0 }
}
}
private struct ThrottleState<Value> {
var previousDate: Date? = nil
var pendingValue: Value? = nil
}
extension SignalProtocol {
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>) -> Signal<(Value, B), Error> {
return a.combineLatest(with: b)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(Value, B, C), Error> {
return combineLatest(a, b)
.combineLatest(with: c)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(Value, B, C, D), Error> {
return combineLatest(a, b, c)
.combineLatest(with: d)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(Value, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
.combineLatest(with: e)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(Value, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
.combineLatest(with: f)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(Value, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
.combineLatest(with: g)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G, H>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(Value, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
.combineLatest(with: h)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G, H, I>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatest(with: i)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public static func combineLatest<B, C, D, E, F, G, H, I, J>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatest(with: j)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`. No events will be sent if the sequence is empty.
public static func combineLatest<S: Sequence>(_ signals: S) -> Signal<[Value], Error>
where S.Iterator.Element == Signal<Value, Error>
{
var generator = signals.makeIterator()
if let first = generator.next() {
let initial = first.map { [$0] }
return IteratorSequence(generator).reduce(initial) { signal, next in
signal.combineLatest(with: next).map { $0.0 + [$0.1] }
}
}
return .never
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>) -> Signal<(Value, B), Error> {
return a.zip(with: b)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(Value, B, C), Error> {
return zip(a, b)
.zip(with: c)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C, D>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(Value, B, C, D), Error> {
return zip(a, b, c)
.zip(with: d)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(Value, B, C, D, E), Error> {
return zip(a, b, c, d)
.zip(with: e)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(Value, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
.zip(with: f)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(Value, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
.zip(with: g)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G, H>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(Value, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
.zip(with: h)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G, H, I>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
.zip(with: i)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public static func zip<B, C, D, E, F, G, H, I, J>(_ a: Signal<Value, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(Value, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
.zip(with: j)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`. No events will be sent if the sequence is empty.
public static func zip<S: Sequence>(_ signals: S) -> Signal<[Value], Error>
where S.Iterator.Element == Signal<Value, Error>
{
var generator = signals.makeIterator()
if let first = generator.next() {
let initial = first.map { [$0] }
return IteratorSequence(generator).reduce(initial) { signal, next in
signal.zip(with: next).map { $0.0 + [$0.1] }
}
}
return .never
}
}
extension SignalProtocol {
/// Forward events from `self` until `interval`. Then if signal isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The signal must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - error: Error to send with failed event if `self` is not completed
/// when `interval` passes.
/// - interval: Number of seconds to wait for `self` to complete.
/// - scheudler: A scheduler to deliver error on.
///
/// - returns: A signal that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with failed event
/// on `scheduler`.
public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateSchedulerProtocol) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let disposable = CompositeDisposable()
let date = scheduler.currentDate.addingTimeInterval(interval)
disposable += scheduler.schedule(after: date) {
observer.sendFailed(error)
}
disposable += self.observe(observer)
return disposable
}
}
}
extension SignalProtocol where Error == NoError {
/// Promote a signal that does not generate failures into one that can.
///
/// - note: This does not actually cause failures to be generated for the
/// given signal, but makes it easier to combine with other signals
/// that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A signal that has an instantiatable `ErrorType`.
public func promoteErrors<F: Swift.Error>(_: F.Type) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
switch event {
case let .next(value):
observer.sendNext(value)
case .failed:
fatalError("NoError is impossible to construct")
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forward events from `self` until `interval`. Then if signal isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The signal must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheudler: A scheduler to deliver error on.
///
/// - returns: A signal that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout<NewError: Swift.Error>(
after interval: TimeInterval,
raising error: NewError,
on scheduler: DateSchedulerProtocol
) -> Signal<Value, NewError> {
return self
.promoteErrors(NewError.self)
.timeout(after: interval, raising: error, on: scheduler)
}
}
| mit | bff607e2b302ecfb4a8a5e153e1d85ee | 31.573521 | 349 | 0.644979 | 3.668826 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings | Food Hygiene Ratings/LocalAuthority.swift | 1 | 1076 | //
// LocalAuthority.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 01/03/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import Foundation
/*
"LocalAuthorityId":197,
"LocalAuthorityIdCode":"760",
"Name":"Aberdeen City",
"EstablishmentCount":1757,
"SchemeType":2,
*/
struct LocalAuthority {
let email : String
let web : String
let name : String
let code : String
var searchCode : Int?
var establishmentCount : Int?
var schemeType : Int?
init(email : String, web : String, name : String, code : String){
self.email = email
self.web = web
self.name = name
self.code = code
}
//Data from basic look-up
init(name : String, searchCode : Int, establishmentCount : Int, schemeType : Int, code : String){
self.email = ""
self.web = ""
self.name = name
self.code = code
self.searchCode = searchCode
self.establishmentCount = establishmentCount
self.schemeType = schemeType
}
}
| apache-2.0 | 174bb5ada86538158e1c47b9050a6382 | 20.938776 | 101 | 0.613953 | 3.866906 | false | false | false | false |
handsomecode/InteractiveSideMenu | Sources/MenuContainerViewController.swift | 1 | 6946 | //
// MenuContainerViewController.swift
//
// Copyright 2017 Handsome LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
/**
Container for menu view controller.
*/
open class MenuContainerViewController: UIViewController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return currentContentViewController?.preferredStatusBarStyle ?? .lightContent
}
fileprivate weak var currentContentViewController: UIViewController?
fileprivate var navigationMenuTransitionDelegate: MenuTransitioningDelegate!
/**
Flag indicating if the side menu is being shown.
*/
fileprivate var isShown = false
public var currentItemOptions = SideMenuItemOptions() {
didSet {
navigationMenuTransitionDelegate?.currentItemOptions = currentItemOptions
}
}
/**
The view controller for side menu.
*/
public var menuViewController: MenuViewController! {
didSet {
if menuViewController == nil {
fatalError("Invalid `menuViewController` value. It should not be nil")
}
menuViewController.modalPresentationStyle = .fullScreen
menuViewController.menuContainerViewController = self
menuViewController.transitioningDelegate = navigationMenuTransitionDelegate
menuViewController.navigationMenuTransitionDelegate = navigationMenuTransitionDelegate
}
}
/**
The options defining side menu transitioning.
Could be set at any time of controller lifecycle.
*/
public var transitionOptions: TransitionOptions {
get {
return navigationMenuTransitionDelegate?.interactiveTransition.options ?? TransitionOptions()
}
set {
navigationMenuTransitionDelegate?.interactiveTransition.options = newValue
}
}
/**
The list of all content view controllers corresponding to side menu items.
*/
public var contentViewControllers = [UIViewController]()
// MARK: - Controller lifecycle
//
override open func viewDidLoad() {
super.viewDidLoad()
let interactiveTransition = MenuInteractiveTransition(
currentItemOptions: currentItemOptions,
presentAction: { [unowned self] in
self.presentNavigationMenu()
},
dismissAction: { [unowned self] in
self.dismissNavigationMenu()
}
)
navigationMenuTransitionDelegate = MenuTransitioningDelegate(interactiveTransition: interactiveTransition)
let screenEdgePanRecognizer = UIScreenEdgePanGestureRecognizer(
target: navigationMenuTransitionDelegate.interactiveTransition,
action: #selector(MenuInteractiveTransition.handlePanPresentation(recognizer:))
)
screenEdgePanRecognizer.edges = .left
view.addGestureRecognizer(screenEdgePanRecognizer)
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let viewBounds = CGRect(x:0, y:0, width:size.width, height:size.height)
let viewCenter = CGPoint(x:size.width/2, y:size.height/2)
coordinator.animate(alongsideTransition: { _ in
if self.menuViewController == nil {
fatalError("Invalid `menuViewController` value. It should not be nil")
}
self.menuViewController.view.bounds = viewBounds
self.menuViewController.view.center = viewCenter
self.view.bounds = viewBounds
self.view.center = viewCenter
if self.isShown {
self.hideSideMenu()
}
}, completion: nil)
}
}
// MARK: - Public
extension MenuContainerViewController {
/**
Shows left side menu.
*/
public func showSideMenu() {
presentNavigationMenu()
}
/**
Hides left side menu.
Controller from the right side will be visible.
*/
public func hideSideMenu() {
dismissNavigationMenu()
}
/**
Embeds menu item content view controller.
- parameter selectedContentVC: The view controller to be embedded.
*/
public func selectContentViewController(_ selectedContentVC: UIViewController) {
if let currentContentVC = currentContentViewController {
if currentContentVC != selectedContentVC {
currentContentVC.view.removeFromSuperview()
currentContentVC.removeFromParent()
setCurrentView(selectedContentVC)
}
} else {
setCurrentView(selectedContentVC)
}
}
}
// MARK: - Private
fileprivate extension MenuContainerViewController {
/**
Adds proper content view controller as a child.
- parameter selectedContentVC: The view controller to be added.
*/
func setCurrentView(_ selectedContentVC: UIViewController) {
addChild(selectedContentVC)
view.addSubviewWithFullSizeConstraints(view: selectedContentVC.view)
currentContentViewController = selectedContentVC
}
/**
Presents left side menu.
*/
func presentNavigationMenu() {
if menuViewController == nil {
fatalError("Invalid `menuViewController` value. It should not be nil")
}
present(menuViewController, animated: true, completion: nil)
isShown = true
}
/**
Dismisses left side menu.
*/
func dismissNavigationMenu() {
self.dismiss(animated: true, completion: nil)
isShown = false
}
}
extension UIView {
func addSubviewWithFullSizeConstraints(view : UIView) {
insertSubviewWithFullSizeConstraints(view: view, atIndex: subviews.count)
}
func insertSubviewWithFullSizeConstraints(view : UIView, atIndex: Int) {
view.translatesAutoresizingMaskIntoConstraints = false
insertSubview(view, at: atIndex)
let top = view.topAnchor.constraint(equalTo: self.topAnchor)
let leading = view.leadingAnchor.constraint(equalTo: self.leadingAnchor)
let trailing = self.trailingAnchor.constraint(equalTo: view.trailingAnchor)
let bottom = self.bottomAnchor.constraint(equalTo: view.bottomAnchor)
NSLayoutConstraint.activate([top, leading, trailing, bottom])
}
}
| apache-2.0 | ea4fc869a246980c6b251302e6f8b39b | 32.23445 | 117 | 0.676217 | 5.827181 | false | false | false | false |
Jnosh/swift | test/Serialization/Recovery/typedefs.swift | 2 | 12577 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -emit-sil -o - -emit-module-path %t/Lib.swiftmodule -module-name Lib -I %S/Inputs/custom-modules -disable-objc-attr-requires-foundation-module %s | %FileCheck -check-prefix CHECK-VTABLE %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD > %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY %s < %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY-NEGATIVE %s < %t.txt
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST -DVERIFY %s -verify
// RUN: %target-swift-frontend -emit-silgen -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-SIL %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
#if TEST
import Typedefs
import Lib
// CHECK-SIL-LABEL: sil hidden @_T08typedefs11testSymbolsyyF
func testSymbols() {
// Check that the symbols are not using 'Bool'.
// CHECK-SIL: function_ref @_T03Lib1xs5Int32Vfau
_ = Lib.x
// CHECK-SIL: function_ref @_T03Lib9usesAssocs5Int32VSgfau
_ = Lib.usesAssoc
} // CHECK-SIL: end sil function '_T08typedefs11testSymbolsyyF'
// CHECK-IR-LABEL: define{{.*}} void @_T08typedefs18testVTableBuildingy3Lib4UserC4user_tF
public func testVTableBuilding(user: User) {
// The important thing in this CHECK line is the "i64 24", which is the offset
// for the vtable slot for 'lastMethod()'. If the layout here
// changes, please check that offset 24 is still correct.
// CHECK-IR-NOT: ret
// CHECK-IR: getelementptr inbounds void (%T3Lib4UserC*)*, void (%T3Lib4UserC*)** %{{[0-9]+}}, {{i64 24|i32 27}}
_ = user.lastMethod()
} // CHECK-IR: ret void
#if VERIFY
let _: String = useAssoc(ImportedType.self) // expected-error {{cannot convert call result type '_.Assoc?' to expected type 'String'}}
let _: Bool? = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'Bool?'}}
let _: Int32? = useAssoc(ImportedType.self)
let _: String = useAssoc(AnotherType.self) // expected-error {{cannot convert call result type '_.Assoc?' to expected type 'String'}}
let _: Bool? = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'Bool?'}}
let _: Int32? = useAssoc(AnotherType.self)
let _ = wrapped // expected-error {{use of unresolved identifier 'wrapped'}}
let _ = unwrapped // okay
_ = usesWrapped(nil) // expected-error {{use of unresolved identifier 'usesWrapped'}}
_ = usesUnwrapped(nil) // expected-error {{nil is not compatible with expected argument type 'Int32'}}
public class UserDynamicSub: UserDynamic {
override init() {}
}
// FIXME: Bad error message; really it's that the convenience init hasn't been
// inherited.
_ = UserDynamicSub(conveniently: 0) // expected-error {{argument passed to call that takes no arguments}}
public class UserDynamicConvenienceSub: UserDynamicConvenience {
override init() {}
}
_ = UserDynamicConvenienceSub(conveniently: 0)
public class UserSub : User {} // expected-error {{cannot inherit from class 'User' because it has overridable members that could not be loaded}}
#endif // VERIFY
#else // TEST
import Typedefs
// CHECK-LABEL: class User {
// CHECK-RECOVERY-LABEL: class User {
open class User {
// CHECK: var unwrappedProp: UnwrappedInt?
// CHECK-RECOVERY: var unwrappedProp: Int32?
public var unwrappedProp: UnwrappedInt?
// CHECK: var wrappedProp: WrappedInt?
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
public var wrappedProp: WrappedInt?
// CHECK: func returnsUnwrappedMethod() -> UnwrappedInt
// CHECK-RECOVERY: func returnsUnwrappedMethod() -> Int32
public func returnsUnwrappedMethod() -> UnwrappedInt { fatalError() }
// CHECK: func returnsWrappedMethod() -> WrappedInt
// CHECK-RECOVERY: /* placeholder for returnsWrappedMethod() */
public func returnsWrappedMethod() -> WrappedInt { fatalError() }
// CHECK: subscript(_: WrappedInt) -> () { get }
// CHECK-RECOVERY: /* placeholder for _ */
public subscript(_: WrappedInt) -> () { return () }
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
// CHECK: required init(wrappedRequired: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt) {}
public func lastMethod() {}
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// This is mostly to check when changes are necessary for the CHECK-IR lines
// above.
// CHECK-VTABLE-LABEL: sil_vtable User {
// (10 words of normal class metadata on 64-bit platforms, 13 on 32-bit)
// 10 CHECK-VTABLE-NEXT: #User.unwrappedProp!getter.1:
// 11 CHECK-VTABLE-NEXT: #User.unwrappedProp!setter.1:
// 12 CHECK-VTABLE-NEXT: #User.unwrappedProp!materializeForSet.1:
// 13 CHECK-VTABLE-NEXT: #User.wrappedProp!getter.1:
// 14 CHECK-VTABLE-NEXT: #User.wrappedProp!setter.1:
// 15 CHECK-VTABLE-NEXT: #User.wrappedProp!materializeForSet.1:
// 16 CHECK-VTABLE-NEXT: #User.returnsUnwrappedMethod!1:
// 17 CHECK-VTABLE-NEXT: #User.returnsWrappedMethod!1:
// 18 CHECK-VTABLE-NEXT: #User.subscript!getter.1:
// 19 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 20 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 21 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 22 CHECK-VTABLE-NEXT: #User.init!allocator.1:
// 23 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 24 CHECK-VTABLE-NEXT: #User.lastMethod!1:
// CHECK-VTABLE: }
// CHECK-LABEL: class UserConvenience
// CHECK-RECOVERY-LABEL: class UserConvenience
open class UserConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamic
// CHECK-RECOVERY-LABEL: class UserDynamic
open class UserDynamic {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamicConvenience
// CHECK-RECOVERY-LABEL: class UserDynamicConvenience
open class UserDynamicConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserSub
// CHECK-RECOVERY-LABEL: class UserSub
open class UserSub : User {
// CHECK: init(wrapped: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public override init(wrapped: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequired: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt?) { super.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-DAG: let x: MysteryTypedef
// CHECK-RECOVERY-DAG: let x: Int32
public let x: MysteryTypedef = 0
public protocol HasAssoc {
associatedtype Assoc
}
extension ImportedType: HasAssoc {}
public struct AnotherType: HasAssoc {
public typealias Assoc = MysteryTypedef
}
public func useAssoc<T: HasAssoc>(_: T.Type) -> T.Assoc? { return nil }
// CHECK-DAG: let usesAssoc: ImportedType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc: Int32?
public let usesAssoc = useAssoc(ImportedType.self)
// CHECK-DAG: let usesAssoc2: AnotherType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc2: AnotherType.Assoc?
public let usesAssoc2 = useAssoc(AnotherType.self)
// CHECK-DAG: let wrapped: WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: let wrapped:
public let wrapped = WrappedInt(0)
// CHECK-DAG: let unwrapped: UnwrappedInt
// CHECK-RECOVERY-DAG: let unwrapped: Int32
public let unwrapped: UnwrappedInt = 0
// CHECK-DAG: let wrappedMetatype: WrappedInt.Type
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedMetatype:
public let wrappedMetatype = WrappedInt.self
// CHECK-DAG: let wrappedOptional: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedOptional:
public let wrappedOptional: WrappedInt? = nil
// CHECK-DAG: let wrappedIUO: WrappedInt!
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedIUO:
public let wrappedIUO: WrappedInt! = nil
// CHECK-DAG: let wrappedArray: [WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedArray:
public let wrappedArray: [WrappedInt] = []
// CHECK-DAG: let wrappedDictionary: [Int : WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedDictionary:
public let wrappedDictionary: [Int: WrappedInt] = [:]
// CHECK-DAG: let wrappedTuple: (WrappedInt, Int)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple:
public let wrappedTuple: (WrappedInt, Int)? = nil
// CHECK-DAG: let wrappedTuple2: (Int, WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple2:
public let wrappedTuple2: (Int, WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure: ((WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure:
public let wrappedClosure: ((WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosure2: (() -> WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure2:
public let wrappedClosure2: (() -> WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure3: ((Int, WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure3:
public let wrappedClosure3: ((Int, WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosureInout: ((inout WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosureInout:
public let wrappedClosureInout: ((inout WrappedInt) -> Void)? = nil
// CHECK-DAG: var wrappedFirst: WrappedInt?
// CHECK-DAG: var normalSecond: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFirst:
// CHECK-RECOVERY-DAG: var normalSecond: Int?
public var wrappedFirst: WrappedInt?, normalSecond: Int?
// CHECK-DAG: var normalFirst: Int?
// CHECK-DAG: var wrappedSecond: WrappedInt?
// CHECK-RECOVERY-DAG: var normalFirst: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedSecond:
public var normalFirst: Int?, wrappedSecond: WrappedInt?
// CHECK-DAG: var wrappedThird: WrappedInt?
// CHECK-DAG: var wrappedFourth: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedThird:
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFourth:
public var wrappedThird, wrappedFourth: WrappedInt?
// CHECK-DAG: func usesWrapped(_ wrapped: WrappedInt)
// CHECK-RECOVERY-NEGATIVE-NOT: func usesWrapped(
public func usesWrapped(_ wrapped: WrappedInt) {}
// CHECK-DAG: func usesUnwrapped(_ unwrapped: UnwrappedInt)
// CHECK-RECOVERY-DAG: func usesUnwrapped(_ unwrapped: Int32)
public func usesUnwrapped(_ unwrapped: UnwrappedInt) {}
// CHECK-DAG: func returnsWrapped() -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrapped(
public func returnsWrapped() -> WrappedInt { fatalError() }
// CHECK-DAG: func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrappedGeneric<
public func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt { fatalError() }
#endif // TEST
| apache-2.0 | 1e08d6fa89db02c473f6bdf044edb3bc | 39.834416 | 219 | 0.71917 | 3.832115 | false | false | false | false |
biohazardlover/ROer | Roer/Item+DatabaseRecord.swift | 1 | 21980 |
import UIKit
import CoreData
import CoreSpotlight
import MobileCoreServices
extension Item {
var displayType: String? {
guard let type = type else { return nil }
switch type {
case 0:
return "Item.Type.HealingItem".localized
case 2:
if let _ = script?.range(of: "pet") {
return "Item.Type.TamingItem".localized
} else {
return "Item.Type.UsableItem".localized
}
case 3:
return "Item.Type.Miscellaneous".localized
case 4:
return "Item.Type.Armor".localized
case 5:
return "Item.Type.Weapon".localized
case 6:
return "Item.Type.Card".localized
case 7:
return "Item.Type.MonsterEgg".localized
case 8:
return "Item.Type.PetArmor".localized
case 10:
return "Item.Type.Ammunition".localized
case 11:
return "Item.Type.DelayedConsumable".localized
case 12:
return "Item.Type.ShadowGear".localized
case 18:
return "Item.Type.CashShopItem".localized
default:
return nil
}
}
var displayClass: String? {
guard let type = type else { return nil }
switch type {
case 4:
guard let loc = loc else { return nil }
switch loc {
case 16:
return "Item.Class.Armor".localized
case 32:
return "Item.Class.Shield".localized
case 4:
return "Item.Class.Garment".localized
case 64:
return "Item.Class.Footgear".localized
case 8, 128, 136:
return "Item.Class.Accessory".localized
case 256:
return "Item.Class.UpperHeadgear".localized
case 512:
return "Item.Class.MiddleHeadgear".localized
case 1:
return "Item.Class.LowerHeadgear".localized
case 768:
return "Item.Class.UpperMiddleHeadgear".localized
case 513:
return "Item.Class.MiddleLowerHeadgear".localized
case 257:
return "Item.Class.UpperLowerHeadgear".localized
case 769:
return "Item.Class.UpperMiddleLowerHeadgear".localized
case 1024, 2048, 4096, 8192, 3072, 5120, 6144, 7168:
return "Item.Class.CostumeHeadgear".localized
default:
return nil
}
case 5:
guard let view = view else { return nil }
switch view {
case 1:
return "Item.Class.Dagger".localized
case 2:
return "Item.Class.OnehandedSword".localized
case 3:
return "Item.Class.TwohandedSword".localized
case 4:
return "Item.Class.OnehandedSpear".localized
case 5:
return "Item.Class.TwohandedSpear".localized
case 6:
return "Item.Class.OnehandedAxe".localized
case 7:
return "Item.Class.TwohandedAxe".localized
case 8:
return "Item.Class.Mace".localized
case 10:
return "Item.Class.OnehandedStaff".localized
case 11:
return "Item.Class.Bow".localized
case 12:
return "Item.Class.Knuckle".localized
case 13:
return "Item.Class.MusicalInstrument".localized
case 14:
return "Item.Class.Whip".localized
case 15:
return "Item.Class.Book".localized
case 16:
return "Item.Class.Katar".localized
case 17:
return "Item.Class.Revolver".localized
case 18:
return "Item.Class.Rifle".localized
case 19:
return "Item.Class.GatlingGun".localized
case 20:
return "Item.Class.Shotgun".localized
case 21:
return "Item.Class.GrenadeLauncher".localized
case 22:
return "Item.Class.FuumaShuriken".localized
case 23:
return "Item.Class.TwohandedStaff".localized
default:
return nil
}
case 6:
guard let loc = loc else { return nil }
switch loc {
case 2:
return "Item.Class.WeaponCard".localized
case 4:
return "Item.Class.GarmentCard".localized
case 16:
return "Item.Class.ArmorCard".localized
case 32:
return "Item.Class.ShieldCard".localized
case 64:
return "Item.Class.FootgearCard".localized
case 136:
return "Item.Class.AccessoryCard".localized
case 769:
return "Item.Class.HeadgearCard".localized
default:
return nil
}
case 10:
guard let view = view else { return nil }
switch view {
case 1:
return "Item.Class.Arrow".localized
case 2:
return "Item.Class.ThrowingDagger".localized
case 3:
return "Item.Class.Bullet".localized
case 4:
return "Item.Class.Shell".localized
case 5:
return "Item.Class.Grenade".localized
case 6:
return "Item.Class.Shuriken".localized
case 7:
return "Item.Class.Kunai".localized
case 8:
return "Item.Class.CannonBall".localized
case 9:
return "Item.Class.ThrowWeapon".localized
default:
return nil
}
case 12:
guard let loc = loc else { return nil }
switch loc {
case 65536:
return "Item.Class.ShadowArmor".localized
case 131072:
return "Item.Class.ShadowWeapon".localized
case 262144:
return "Item.Class.ShadowShield".localized
case 524288:
return "Item.Class.ShadowFootgear".localized
case 1048576:
return "Item.Class.ShadowEarring".localized
case 2097152:
return "Item.Class.ShadowPendant".localized
default:
return nil
}
default:
return nil
}
}
var displaySell: NSNumber? {
if let sell = sell {
return sell
} else if let buy = buy {
return (buy.intValue / 2) as NSNumber
} else {
return nil
}
}
var displayWeight: String? {
if let weight = weight {
return "\(weight.intValue / 10)"
} else {
return nil
}
}
var displayApplicableJobs: NSAttributedString? {
let jobs = applicableJobs
if jobs.count > 0 {
var displayApplicableJobs = "<meta charset=\"utf-8\"/><table border=\"0\" width=100% style=\"font-family: Helvetica; font-size: 17;\">"
for index in 0..<jobs.count {
if index % 2 == 0 {
displayApplicableJobs += "<tr>"
}
displayApplicableJobs += "<td width=50%>\(jobs[index])</td>"
if index % 2 == 1 || index == jobs.count - 1 {
displayApplicableJobs += "</tr>"
}
}
displayApplicableJobs += "</table>"
if let data = displayApplicableJobs.data(using: String.Encoding.utf8) {
return try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
}
}
return nil
}
var displayItemScript: NSAttributedString? {
guard let script = script, let onEquipScript = onEquipScript, let onUnequipScript = onUnequipScript else { return nil }
var scripts = [String]()
scripts.append(script)
scripts.append(onEquipScript)
scripts.append(onUnequipScript)
let font = UIFont(name: "Menlo", size: 17) ?? UIFont.systemFont(ofSize: 17)
return NSAttributedString(string: scripts.joined(separator: ","), attributes: [NSAttributedStringKey.font: font])
}
}
extension Item {
var applicableJobs: [String] {
guard let jobMask = job?.intValue, let classMask = category?.intValue else { return [] }
let isNormalClass = classMask & 1 << 0 != 0
let isTranscedentClass = classMask & 1 << 1 != 0
let isThirdClass = classMask & 1 << 3 != 0 || classMask & 1 << 4 != 0 || classMask & 1 << 5 != 0
var applicableJobs = [String]()
if jobMask & 0x7FFFFFFF == 0x7FFFFFFF {
applicableJobs.append("Job.All".localized)
return applicableJobs
}
if jobMask & 1 << 0 != 0 {
if isNormalClass {
applicableJobs.append("Job.Novice".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.SuperNovice".localized)
}
}
if jobMask & 1 << 1 != 0 {
if isNormalClass || isTranscedentClass {
applicableJobs.append("Job.Swordman".localized)
}
}
if jobMask & 1 << 2 != 0 {
if isNormalClass || isTranscedentClass {
applicableJobs.append("Job.Magician".localized)
}
}
if jobMask & 1 << 3 != 0 {
if isNormalClass || isTranscedentClass {
applicableJobs.append("Job.Archer".localized)
}
}
if jobMask & 1 << 4 != 0 {
if isNormalClass || isTranscedentClass {
applicableJobs.append("Job.Acolyte".localized)
}
}
if jobMask & 1 << 5 != 0 {
if isNormalClass || isTranscedentClass {
applicableJobs.append("Job.Merchant".localized)
}
}
if jobMask & 1 << 6 != 0 {
if isNormalClass || isTranscedentClass {
applicableJobs.append("Job.Thief".localized)
}
}
if jobMask & 1 << 7 != 0 {
if isNormalClass {
applicableJobs.append("Job.Knight".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.LordKnight".localized)
}
if isThirdClass {
applicableJobs.append("Job.RuneKnight".localized)
}
}
if jobMask & 1 << 8 != 0 {
if isNormalClass {
applicableJobs.append("Job.Priest".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.HighPriest".localized)
}
if isThirdClass {
applicableJobs.append("Job.ArchBishop".localized)
}
}
if jobMask & 1 << 9 != 0 {
if isNormalClass {
applicableJobs.append("Job.Wizard".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.HighWizard".localized)
}
if isThirdClass {
applicableJobs.append("Job.Warlock".localized)
}
}
if jobMask & 1 << 10 != 0 {
if isNormalClass {
applicableJobs.append("Job.Blacksmith".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.Whitesmith".localized)
}
if isThirdClass {
applicableJobs.append("Job.Mechanic".localized)
}
}
if jobMask & 1 << 11 != 0 {
if isNormalClass {
applicableJobs.append("Job.Hunter".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.Sniper".localized)
}
if isThirdClass {
applicableJobs.append("Job.Ranger".localized)
}
}
if jobMask & 1 << 12 != 0 {
if isNormalClass {
applicableJobs.append("Job.Assassin".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.AssassinCross".localized)
}
if isThirdClass {
applicableJobs.append("Job.GuillotineCross".localized)
}
}
if jobMask & 1 << 14 != 0 {
if isNormalClass {
applicableJobs.append("Job.Crusader".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.Paladin".localized)
}
if isThirdClass {
applicableJobs.append("Job.RoyalGuard".localized)
}
}
if jobMask & 1 << 15 != 0 {
if isNormalClass {
applicableJobs.append("Job.Monk".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.Champion".localized)
}
if isThirdClass {
applicableJobs.append("Job.Shura".localized)
}
}
if jobMask & 1 << 16 != 0 {
if isNormalClass {
applicableJobs.append("Job.Sage".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.Professor".localized)
}
if isThirdClass {
applicableJobs.append("Job.Sorcerer".localized)
}
}
if jobMask & 1 << 17 != 0 {
if isNormalClass {
applicableJobs.append("Job.Rogue".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.Stalker".localized)
}
if isThirdClass {
applicableJobs.append("Job.ShadowChaser".localized)
}
}
if jobMask & 1 << 18 != 0 {
if isNormalClass {
applicableJobs.append("Job.Alchemist".localized)
}
if isTranscedentClass {
applicableJobs.append("Job.Creator".localized)
}
if isThirdClass {
applicableJobs.append("Job.Genetic".localized)
}
}
if jobMask & 1 << 19 != 0 {
if isNormalClass {
let bard = "Job.Bard".localized
let dancer = "Job.Dancer".localized
applicableJobs.append("\(bard) / \(dancer)")
}
if isTranscedentClass {
let clown = "Job.Clown".localized
let gypsy = "Job.Gypsy".localized
applicableJobs.append("\(clown) / \(gypsy)")
}
if isThirdClass {
let minstrel = "Job.Minstrel".localized
let wanderer = "Job.Wanderer".localized
applicableJobs.append("\(minstrel) / \(wanderer)")
}
}
if jobMask & 1 << 21 != 0 {
applicableJobs.append("Job.Taekwon".localized)
}
if jobMask & 1 << 22 != 0 {
applicableJobs.append("Job.StarGladiator".localized)
}
if jobMask & 1 << 23 != 0 {
applicableJobs.append("Job.SoulLinker".localized)
}
if jobMask & 1 << 24 != 0 {
applicableJobs.append("Job.Gunslinger".localized)
}
if jobMask & 1 << 25 != 0 {
applicableJobs.append("Job.Ninja".localized)
}
if jobMask & 1 << 26 != 0 {
// Empty
}
if jobMask & 1 << 27 != 0 {
// Empty
}
if jobMask & 1 << 28 != 0 {
// Empty
}
if jobMask & 1 << 29 != 0 {
let kagerou = "Job.Kagerou".localized
let oboro = "Job.Oboro".localized
applicableJobs.append("\(kagerou) / \(oboro)")
}
if jobMask & 1 << 30 != 0 {
applicableJobs.append("Job.Rebellion".localized)
}
return applicableJobs
}
var droppedBy: [DatabaseRecordCellInfo] {
guard let id = id else { return [] }
let fetchRequest = NSFetchRequest<Monster>(entityName: "Monster")
fetchRequest.predicate = NSPredicate(format: "drop1id == %@ || drop2id == %@ || drop3id == %@ || drop4id == %@ || drop5id == %@ || drop6id == %@ || drop7id == %@ || drop8id == %@ || drop9id == %@ || dropCardid == %@ || mvp1id == %@ || mvp2id == %@ || mvp3id == %@", id, id, id, id, id, id, id, id, id, id, id, id, id)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)]
var droppedBy = [DatabaseRecordCellInfo]()
if let monsters = (try? managedObjectContext?.fetch(fetchRequest)) ?? nil {
for monster in monsters {
let drops = monster.drops
for drop in drops {
if drop.id == id {
droppedBy.append((monster, dropRateWithPer(drop.per)))
}
}
}
}
return droppedBy
}
}
extension Item {
var localizedName: String? {
guard let id = id else { return nil }
let result = Localization.preferred.itemInfo["\(id)"]["identifiedDisplayName"].string
return result?.isEmpty == false ? result : name
}
var localizedDescription: NSAttributedString? {
guard let id = id else { return nil }
guard let result = Localization.preferred.itemInfo["\(id)"]["identifiedDescriptionName"].string else { return nil }
return NSAttributedString(descriptiveString: result)
}
}
extension Item: DatabaseRecord {
var smallImageURL: URL? {
if type == 6 {
return URL(string: "http://img.ratemyserver.net/items/small/card.gif")
} else if let id = id {
return URL(string: "http://img.ratemyserver.net/items/small/\(id).gif")
} else {
return nil
}
}
var largeImageURL: URL? {
if let id = id {
return URL(string: "http://img.ratemyserver.net/items/large/\(id).gif")
} else {
return nil
}
}
var displayName: String? {
if let name = localizedName, let slots = slots {
return "\(name) [\(slots)]"
} else {
return localizedName
}
}
var recordDetails: DatabaseRecordDetails {
var attributeGroups = [DatabaseRecordAttributeGroup]()
attributeGroups.appendAttribute(("Item.Type".localized, displayType?.utf8))
attributeGroups.appendAttribute(("Item.Class".localized, displayClass?.utf8))
attributeGroups.appendAttribute(("Item.Buy".localized, buy)) { $0 + "z" }
attributeGroups.appendAttribute(("Item.Sell".localized, displaySell)) { $0 + "z" }
attributeGroups.appendAttribute(("Item.Weight".localized, displayWeight?.utf8))
attributeGroups.appendAttribute(("Item.Attack".localized, atk))
attributeGroups.appendAttribute(("Item.MagicAttack".localized, matk))
attributeGroups.appendAttribute(("Item.Defence".localized, def))
attributeGroups.appendAttribute(("Item.RequiredLevel".localized, eLV))
attributeGroups.appendAttribute(("Item.WeaponLevel".localized, wLV))
attributeGroups.appendAttribute(("Item.Slot".localized, slots))
attributeGroups.appendAttribute(("Item.Range".localized, range))
attributeGroups.appendAttribute(("Item.Refineable".localized, refineable)) { ($0 as NSString).boolValue ? "Item.Refineable.Yes".localized : "Item.Refineable.No".localized }
var recordDetails = DatabaseRecordDetails()
recordDetails.appendTitle(displayName != nil && id != nil ? "\(displayName!) #\(id!)" : "", section: .attributeGroups(attributeGroups))
recordDetails.appendTitle("Item.ApplicableJobs".localized, section: .description(displayApplicableJobs))
recordDetails.appendTitle("Item.Description".localized, section: .description(localizedDescription))
recordDetails.appendTitle("Item.ItemScript".localized, section: .description(displayItemScript))
recordDetails.appendTitle("Item.DroppedBy".localized, section: .databaseRecords(droppedBy))
return recordDetails
}
func correspondingDatabaseRecord(in managedObjectContext: NSManagedObjectContext) -> DatabaseRecord? {
guard let id = id else { return nil }
let request = NSFetchRequest<Item>(entityName: "Item")
request.predicate = NSPredicate(format: "%K == %@", "id", id)
let results = try? managedObjectContext.fetch(request)
return results?.first
}
}
extension Item: Searchable {
var searchableItem: CSSearchableItem {
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)
searchableItemAttributeSet.title = localizedName
searchableItemAttributeSet.contentDescription = nil
searchableItemAttributeSet.thumbnailData = nil
return CSSearchableItem(uniqueIdentifier: "Item/" + (id?.stringValue ?? ""), domainIdentifier: nil, attributeSet: searchableItemAttributeSet)
}
}
| mit | 0f1e25251878591477eeebee4c6c5d6a | 34.973813 | 325 | 0.526615 | 5.131917 | false | false | false | false |
Kievkao/YoutubeClassicPlayer | ClassicalPlayer/Flows/VideosFlow.swift | 1 | 2294 | //
// VideosFlow.swift
// ClassicalPlayer
//
// Created by Andrii Kravchenko on 08.02.18.
// Copyright © 2018 Kievkao. All rights reserved.
//
import UIKit
import RxFlow
import RxSwift
class VideosFlow: Flow {
var root: UIViewController {
return self.rootViewController
}
private let rootViewController: UINavigationController
private let networkServicesFactory: NetworkServiceFactoryProtocol
init(rootViewController: UINavigationController, networkServicesFactory: NetworkServiceFactoryProtocol) {
self.networkServicesFactory = networkServicesFactory
self.rootViewController = rootViewController
}
func navigate(to step: Step) -> NextFlowItems {
guard let step = step as? AppStep else { return NextFlowItems.stepNotHandled }
switch step {
case .videos(let composer):
return navigationToVideosScreen(composer: composer)
case .playback(let composer, let videos, let initialIndex):
return navigationToPlaybackScreen(composer: composer, videos: videos, initialIndex: initialIndex)
default:
return NextFlowItems.stepNotHandled
}
}
private func navigationToVideosScreen(composer: Composer) -> NextFlowItems {
let videosViewController = VideosViewController.instantiate()
let viewModel = VideosViewModel(videosService: networkServicesFactory.videoSearchService(), imagesLoader: networkServicesFactory.imagesLoaderService(), composer: composer)
videosViewController.viewModel = viewModel
rootViewController.pushViewController(videosViewController, animated: true)
return NextFlowItems.one(flowItem: NextFlowItem(nextPresentable: videosViewController, nextStepper: viewModel))
}
private func navigationToPlaybackScreen(composer: Composer, videos: [Video], initialIndex: Int) -> NextFlowItems {
let playbackViewController = PlaybackViewController.instantiate()
let viewModel = PlaybackViewModel(composer: composer, videos: videos, currentIndex: initialIndex)
playbackViewController.viewModel = viewModel
rootViewController.pushViewController(playbackViewController, animated: true)
return NextFlowItems.none
}
}
| mit | e985d70ac4177500e020c944c4cf5dad | 39.946429 | 179 | 0.732229 | 5.592683 | false | false | false | false |
julienbodet/wikipedia-ios | WMF Framework/CollectionViewCellActionsView.swift | 1 | 7715 | import Foundation
public class Action: UIAccessibilityCustomAction {
let icon: UIImage?
let confirmationIcon: UIImage?
public let type: ActionType
public let indexPath: IndexPath
public init(accessibilityTitle: String, icon: UIImage?, confirmationIcon: UIImage?, type: ActionType, indexPath: IndexPath, target: Any?, selector: Selector) {
self.icon = icon
self.confirmationIcon = confirmationIcon;
self.type = type
self.indexPath = indexPath
super.init(name: accessibilityTitle, target: target, selector: selector)
}
}
@objc public protocol ActionDelegate: NSObjectProtocol {
@objc func availableActions(at indexPath: IndexPath) -> [Action]
@objc func didPerformAction(_ action: Action) -> Bool
@objc func willPerformAction(_ action: Action) -> Bool
@objc optional func didPerformBatchEditToolbarAction(_ action: BatchEditToolbarAction) -> Bool
@objc optional var availableBatchEditToolbarActions: [BatchEditToolbarAction] { get }
}
public enum ActionType {
case delete, save, unsave, share
private struct Icon {
static let delete = UIImage(named: "swipe-action-delete", in: Bundle.wmf, compatibleWith: nil)
static let save = UIImage(named: "swipe-action-save", in: Bundle.wmf, compatibleWith: nil)
static let unsave = UIImage(named: "swipe-action-unsave", in: Bundle.wmf, compatibleWith: nil)
static let share = UIImage(named: "swipe-action-share", in: Bundle.wmf, compatibleWith: nil)
}
public func action(with target: Any?, indexPath: IndexPath) -> Action {
switch self {
case .delete:
return Action(accessibilityTitle: CommonStrings.deleteActionTitle, icon: Icon.delete, confirmationIcon: nil, type: .delete, indexPath: indexPath, target: target, selector: #selector(ActionDelegate.willPerformAction(_:)))
case .save:
return Action(accessibilityTitle: CommonStrings.saveTitle, icon: Icon.save, confirmationIcon: Icon.unsave, type: .save, indexPath: indexPath, target: target, selector: #selector(ActionDelegate.willPerformAction(_:)))
case .unsave:
return Action(accessibilityTitle: CommonStrings.accessibilitySavedTitle, icon: Icon.unsave, confirmationIcon: Icon.save, type: .unsave, indexPath: indexPath, target: target, selector: #selector(ActionDelegate.willPerformAction(_:)))
case .share:
return Action(accessibilityTitle: CommonStrings.shareActionTitle, icon: Icon.share, confirmationIcon: nil, type: .share, indexPath: indexPath, target: target, selector: #selector(ActionDelegate.willPerformAction(_:)))
}
}
}
public class ActionsView: SizeThatFitsView, Themeable {
fileprivate let minButtonWidth: CGFloat = 60
var maximumWidth: CGFloat = 0
var buttonWidth: CGFloat = 0
var buttons: [UIButton] = []
var needsSubviews = true
public var theme = Theme.standard
internal var actions: [Action] = [] {
didSet {
activatedIndex = NSNotFound
needsSubviews = true
}
}
fileprivate var activatedIndex = NSNotFound
func expand(_ action: Action) {
guard let index = actions.index(of: action) else {
return
}
bringSubview(toFront: buttons[index])
activatedIndex = index
setNeedsLayout()
}
public override var frame: CGRect {
didSet {
setNeedsLayout()
}
}
public override var bounds: CGRect {
didSet {
setNeedsLayout()
}
}
public override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let superSize = super.sizeThatFits(size, apply: apply)
if (apply) {
if (size.width > 0 && needsSubviews) {
createSubviews(for: actions)
needsSubviews = false
}
let isRTL = effectiveUserInterfaceLayoutDirection == .rightToLeft
if activatedIndex == NSNotFound {
let numberOfButtons = CGFloat(subviews.count)
let buttonDelta = min(size.width, maximumWidth) / numberOfButtons
var x: CGFloat = isRTL ? size.width - buttonWidth : 0
for button in buttons {
button.frame = CGRect(x: x, y: 0, width: buttonWidth, height: size.height)
if isRTL {
x -= buttonDelta
} else {
x += buttonDelta
}
}
} else {
var x: CGFloat = isRTL ? size.width : 0 - (buttonWidth * CGFloat(buttons.count - 1))
for button in buttons {
button.clipsToBounds = true
if button.tag == activatedIndex {
button.frame = CGRect(origin: .zero, size: CGSize(width: size.width, height: size.height))
} else {
button.frame = CGRect(x: x, y: 0, width: buttonWidth, height: size.height)
x += buttonWidth
}
}
}
}
let width = superSize.width == UIViewNoIntrinsicMetric ? maximumWidth : superSize.width
let height = superSize.height == UIViewNoIntrinsicMetric ? 50 : superSize.height
return CGSize(width: width, height: height)
}
func createSubviews(for actions: [Action]) {
for view in subviews {
view.removeFromSuperview()
}
buttons = []
var maxButtonWidth: CGFloat = 0
for (index, action) in actions.enumerated() {
let button = UIButton(type: .custom)
button.setImage(action.icon, for: .normal)
button.titleLabel?.numberOfLines = 1
button.contentEdgeInsets = UIEdgeInsetsMake(0, 14, 0, 14)
button.tag = index
switch (action.type) {
case .delete:
button.backgroundColor = theme.colors.destructive
case .share:
button.backgroundColor = theme.colors.secondaryAction
case .save:
button.backgroundColor = theme.colors.link
case .unsave:
button.backgroundColor = theme.colors.link
}
button.imageView?.tintColor = .white
button.addTarget(self, action: #selector(willPerformAction(_:)), for: .touchUpInside)
maxButtonWidth = max(maxButtonWidth, button.intrinsicContentSize.width)
insertSubview(button, at: 0)
buttons.append(button)
}
backgroundColor = buttons.last?.backgroundColor
buttonWidth = max(minButtonWidth, maxButtonWidth)
maximumWidth = buttonWidth * CGFloat(subviews.count)
setNeedsLayout()
}
public weak var delegate: ActionDelegate?
private var activeSender: UIButton?
@objc func willPerformAction(_ sender: UIButton) {
activeSender = sender
let action = actions[sender.tag]
let _ = delegate?.willPerformAction(action)
}
func updateConfirmationImage(for action: Action, completion: @escaping () -> Bool) -> Bool {
if let image = action.confirmationIcon {
activeSender?.setImage(image, for: .normal)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) {
let _ = completion()
}
} else {
return completion()
}
return true
}
public func apply(theme: Theme) {
self.theme = theme
backgroundColor = theme.colors.baseBackground
}
}
| mit | 94ef3ac9c771e564a0498e84687b8237 | 39.820106 | 244 | 0.608425 | 5.116048 | false | false | false | false |
silence0201/Swift-Study | Learn/08.闭包/类型推断简化.playground/section-1.swift | 1 | 455 |
func calculate(opr: String) -> (Int, Int) -> Int {
var result: (Int, Int) -> Int
switch (opr) {
case "+":
result = {
(a, b) in return a + b
}
default:
result = {
a, b in return a - b
}
}
return result
}
let f1: (Int, Int) -> Int = calculate(opr: "+")
print("10 + 5 = \(f1(10, 5))")
let f2: (Int, Int) -> Int = calculate(opr: "-")
print("10 - 5 = \(f2(10, 5))")
| mit | 23be159347d77eb14b79565d3d2f5373 | 17.958333 | 50 | 0.428571 | 2.973856 | false | false | false | false |
Mazy-ma/MiaoShow | MiaoShow/MiaoShow/Classes/Live/ViewController/LiveRecordController.swift | 1 | 1599 | //
// LiveRecordController.swift
// MiaoShow
//
// Created by Mazy on 2017/4/18.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class LiveRecordController: UIViewController {
@IBOutlet weak var bottomContentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
bottomContentView.transform = CGAffineTransform(translationX: 0, y: bottomContentView.bounds.height)
}
override func viewWillAppear(_ animated: Bool) {
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveLinear], animations: {
self.bottomContentView.transform = .identity
})
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: 0.2, animations: {
self.bottomContentView.transform = CGAffineTransform(translationX: 0, y: self.bottomContentView.bounds.height)
}) { (_) in
self.dismiss(animated: false, completion: nil)
}
}
@IBAction func beginRecord() {
print("录制直播")
let recordVC = FilterImageViewController()
recordVC.closeAction = {
self.dismiss(animated: false, completion: nil)
}
present(recordVC, animated: true) {
self.view.isHidden = true
}
}
@IBAction func shortVideoAction() {
print("短视频")
}
@IBAction func uploadAction() {
print("上传")
}
}
| apache-2.0 | 6a66c6a0051abee1631f8eb32a18547e | 24.868852 | 122 | 0.607098 | 4.54755 | false | false | false | false |
meteochu/HanekeSwift | Haneke/DiskFetcher.swift | 1 | 2431 | //
// DiskFetcher.swift
// Haneke
//
// Created by Joan Romano on 9/16/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import Foundation
extension HanekeGlobals {
// It'd be better to define this in the DiskFetcher class but Swift doesn't allow to declare an enum in a generic type
public struct DiskFetcher {
public enum ErrorCode : Int {
case InvalidData = -500
}
}
}
public class DiskFetcher<T : DataConvertible> : Fetcher<T> {
let path: String
var cancelled = false
public init(path: String) {
self.path = path
let key = path
super.init(key: key)
}
// MARK: Fetcher
public override func fetch(failure fail: @escaping ((NSError?) -> ()), success succeed: @escaping (T.Result) -> ()) {
self.cancelled = false
DispatchQueue.global(qos: .default).async { [weak self] in
if let strongSelf = self {
strongSelf.privateFetch(failure: fail, success: succeed)
}
}
}
public override func cancelFetch() {
self.cancelled = true
}
// MARK: Private
private func privateFetch(failure fail: @escaping ((NSError?) -> ()), success succeed: @escaping (T.Result) -> ()) {
if self.cancelled {
return
}
let data : Data
do {
data = try NSData(contentsOfFile: self.path, options: []) as Data
} catch {
DispatchQueue.main.async {
if self.cancelled {
return
}
fail(error as NSError)
}
return
}
if self.cancelled {
return
}
guard let value : T.Result = T.convertFromData(data: data) else {
let localizedFormat = NSLocalizedString("Failed to convert value from data at path %@", comment: "Error description")
let description = String(format:localizedFormat, self.path)
let error = errorWithCode(code: HanekeGlobals.DiskFetcher.ErrorCode.InvalidData.rawValue, description: description)
DispatchQueue.main.async {
fail(error)
}
return
}
DispatchQueue.main.async {
guard !self.cancelled else { return }
succeed(value)
}
}
}
| apache-2.0 | cb219fa92739ac620b1b2552c4cc9f1e | 26.625 | 129 | 0.545043 | 4.862 | false | false | false | false |
meteochu/HanekeSwift | Haneke/CGSize+Swift.swift | 1 | 1039 | //
// CGSize+Swift.swift
// Haneke
//
// Created by Oriol Blanc Gimeno on 09/09/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
extension CGSize {
func hnk_aspectFillSize(size: CGSize) -> CGSize {
let scaleWidth = size.width / self.width
let scaleHeight = size.height / self.height
let scale = max(scaleWidth, scaleHeight)
let resultSize = CGSize(width: self.width * scale, height: self.height * scale)
return CGSize(width: ceil(resultSize.width), height: ceil(resultSize.height))
}
func hnk_aspectFitSize(size: CGSize) -> CGSize {
let targetAspect = size.width / size.height
let sourceAspect = self.width / self.height
var resultSize = size
if (targetAspect > sourceAspect) {
resultSize.width = size.height * sourceAspect
}
else {
resultSize.height = size.width / sourceAspect
}
return CGSize(width: ceil(resultSize.width), height: ceil(resultSize.height))
}
}
| apache-2.0 | 23bfb1dee9fa46729c1b5be6c04dcdeb | 28.685714 | 87 | 0.635226 | 4.058594 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/XCTEurofurenceModel/StubConventionCountdownService.swift | 1 | 998 | import EurofurenceModel
public class StubConventionCountdownService: ConventionCountdownService {
fileprivate var observers = [ConventionCountdownServiceObserver]()
public fileprivate(set) var countdownState: ConventionCountdownState {
didSet {
observers.forEach({ $0.conventionCountdownStateDidChange(to: countdownState) })
}
}
public init(countdownState: ConventionCountdownState = .countingDown(daysUntilConvention: .random)) {
self.countdownState = countdownState
}
public func add(_ observer: ConventionCountdownServiceObserver) {
observer.conventionCountdownStateDidChange(to: countdownState)
observers.append(observer)
}
}
extension StubConventionCountdownService {
public func changeDaysUntilConvention(to days: Int) {
countdownState = .countingDown(daysUntilConvention: days)
}
public func simulateCountdownFinished() {
countdownState = .countdownElapsed
}
}
| mit | e6d7460450a63851c1e68267ae48e92c | 28.352941 | 105 | 0.729459 | 5.670455 | false | false | false | false |
kamawshuang/iOS---Animation | 关键帧动画与结构体属性(四)/ShapesMasks/ShapesMasks/AvatarView.swift | 1 | 1730 |
import UIKit
import QuartzCore
@IBDesignable
class AvatarView: UIView {
//constants
let lineWidth: CGFloat = 6.0
let animationDuration = 1.0
//ui
let photoLayer = CALayer()
let circleLayer = CAShapeLayer()
let maskLayer = CAShapeLayer()
let label: UILabel = {
let label = UILabel()
label.font = UIFont(name: "ArialRoundedMTBold", size: 18.0)
label.textAlignment = .Center
label.textColor = UIColor.blackColor()
return label
}()
//variables
@IBInspectable
var image: UIImage! {
didSet {
photoLayer.contents = image.CGImage
}
}
@IBInspectable
var name: NSString? {
didSet {
label.text = name as? String
}
}
var shouldTransitionToFinishedState = false
override func didMoveToWindow() {
layer.addSublayer(photoLayer)
photoLayer.mask = maskLayer
layer.addSublayer(circleLayer)
}
override func layoutSubviews() {
//Size the avatar image to fit
photoLayer.frame = CGRect(
x: (bounds.size.width - image.size.width + lineWidth)/2,
y: (bounds.size.height - image.size.height - lineWidth)/2,
width: image.size.width,
height: image.size.height)
//Draw the circle
circleLayer.path = UIBezierPath(ovalInRect: bounds).CGPath
circleLayer.strokeColor = UIColor.whiteColor().CGColor
circleLayer.lineWidth = lineWidth
circleLayer.fillColor = UIColor.clearColor().CGColor
//Size the layer
maskLayer.path = circleLayer.path
maskLayer.position = CGPoint(x: 0.0, y: 10.0)
//Size the label
label.frame = CGRect(x: 0.0, y: bounds.size.height + 10.0, width: bounds.size.width, height: 24.0)
}
}
| apache-2.0 | 3b1e93c2f897e5695ea03b47e03bf8e6 | 21.467532 | 102 | 0.646243 | 4.219512 | false | false | false | false |
CartoDB/mobile-ios-samples | AdvancedMap.Swift/Feature Demo/GeocodingController.swift | 1 | 7091 | //
// GeocodingController.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 06/07/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
import CartoMobileSDK
class GeocodingController : BaseGeocodingController, UITableViewDataSource, UITextFieldDelegate {
var searchRequestId: Int = 0
var displayRequestId: Int = 0
var addresses = [NTGeocodingResult]()
static let identifier = "AutocompleteRowId"
var service: NTGeocodingService!
override func viewDidLoad() {
super.viewDidLoad()
contentView = GeocodingView()
view = contentView
let folder = Utils.createDirectory(name: BaseGeocodingView.PACKAGE_FOLDER)
contentView.manager = NTCartoPackageManager(source: BaseGeocodingView.SOURCE, dataFolder: folder)
setOnlineMode()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
(contentView as! GeocodingView).inputField.delegate = self
(contentView as! GeocodingView).resultTable.delegate = self
(contentView as! GeocodingView).resultTable.dataSource = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
(contentView as! GeocodingView).inputField.delegate = nil
(contentView as! GeocodingView).resultTable.delegate = nil
(contentView as! GeocodingView).resultTable.dataSource = nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
(contentView as! GeocodingView).closeTextField()
geocode(text: (contentView as! GeocodingView).inputField.text!, autocomplete: false)
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
(contentView as! GeocodingView).resultTable.isHidden = false
let substring = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
geocode(text: substring, autocomplete: true)
return true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return addresses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let id = GeocodingController.identifier
let cell = tableView.dequeueReusableCell(withIdentifier: id) as! GeocodingResultCell
let result = addresses[indexPath.row]
cell.update(result: result)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// This controller contains two tableviews: package table and autocomplete table,
// both delegates direct here. Make the distinction:
if (tableView.isEqual((contentView as! GeocodingView).resultTable)) {
(contentView as! GeocodingView).closeTextField()
let result = addresses[indexPath.row]
showResult(result: result)
} else {
// Base class handles package table actions
super.tableView(tableView, didSelectRowAt: indexPath)
}
}
func geocode(text: String, autocomplete: Bool) {
let syncQueue = DispatchQueue(label: "com.carto.GeocodingControllerQueue")
var currentRequestId: Int = 0
syncQueue.sync {
self.searchRequestId += 1
currentRequestId = self.searchRequestId
}
DispatchQueue.global().async {
self.service.setAutocomplete(autocomplete)
let start = NSDate.timeIntervalSinceReferenceDate
let request = NTGeocodingRequest(projection: self.contentView.projection, query: text)
if (self.service is NTPackageManagerGeocodingService) {
(self.service as! NTPackageManagerGeocodingService).setAutocomplete(autocomplete)
} else {
(self.service as! NTMapBoxOnlineGeocodingService).setAutocomplete(autocomplete)
}
//request?.setLocation(self.contentView.projection.fromWgs84(NTMapPos(x: -1.0861967, y: 61.2675)))
//request?.setLocationRadius(10000000.0)
var results: NTGeocodingResultVector?
do {
try NTExceptionWrapper.catchException {
results = self.service.calculateAddresses(request)
}
}
catch {
NSLog("Failed to geocode")
return
}
syncQueue.sync {
if (self.displayRequestId > currentRequestId) {
return // a newer request has already been processed
}
self.displayRequestId = currentRequestId
}
let duration = NSDate.timeIntervalSinceReferenceDate - start
let count: Int = Int((results?.size())!)
DispatchQueue.main.async {
// In autocomplete mode just fill the autocomplete address list and reload tableview
// In full geocode mode, show the result
if (autocomplete) {
self.addresses.removeAll()
for var i in 00..<count {
let result = (results?.get(Int32(i)))!
self.addresses.append(result)
i += 1
}
(self.contentView as! GeocodingView).resultTable.reloadData()
return
}
if (count > 0) {
self.showResult(result: results?.get(0))
}
print("Geocoding took: " + String(describing: duration))
}
}
}
func showResult(result: NTGeocodingResult!) {
let title = ""
let description = result.getPrettyAddress()
let goToPosition = true
(self.contentView as! GeocodingView).showResult(result: result, title: title, description: description, goToPosition: goToPosition)
}
override func setOnlineMode() {
super.setOnlineMode()
service = NTMapBoxOnlineGeocodingService(accessToken: BaseGeocodingController.MAPBOX_KEY)
(contentView as! GeocodingView).showSearchBar()
}
override func setOfflineMode() {
super.setOfflineMode()
service = NTPackageManagerGeocodingService(packageManager: contentView.manager)
if ((contentView as! GeocodingView).hasLocalPackages()) {
(contentView as! GeocodingView).showLocalPackages()
(contentView as! GeocodingView).showSearchBar()
} else {
(contentView as! GeocodingView).showBannerInsteadOfSearchBar()
}
}
}
| bsd-2-clause | b9949f684d4e24c8a247825bfbe66e3b | 34.273632 | 139 | 0.603808 | 5.667466 | false | false | false | false |
PrashantMangukiya/SwiftUIDemo | Demo24-UIToolbar/Demo24-UIToolbar/ViewController.swift | 1 | 2703 | //
// ViewController.swift
// Demo24-UIToolbar
//
// Created by Prashant on 10/10/15.
// Copyright © 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// maintain state that toolbar is hiden or not.
var toolbarHidden: Bool = false
// outlet - toolbar
@IBOutlet var toolbar: UIToolbar!
// Action - toggle button
@IBAction func toggleButtonAction(_ sender: UIButton) {
// We are moving tool bar out of screen using animation.
// i.e. we are changing the frame postion for the toolbar and change it's alpha.
UIView.animate(withDuration: 1.0, animations: {
() -> Void in
// show/hide toolbar
if self.toolbarHidden {
self.toolbarHidden = false
let frameRect = CGRect(x: self.toolbar.frame.origin.x, y: self.toolbar.frame.origin.y - self.toolbar.frame.height , width: self.toolbar.frame.width , height: self.toolbar.frame.height)
self.toolbar.frame = frameRect
self.toolbar.alpha = 1.0
}else {
self.toolbarHidden = true
let frameRect = CGRect(x: self.toolbar.frame.origin.x , y: self.toolbar.frame.origin.y + self.toolbar.frame.height, width: self.toolbar.frame.width , height: self.toolbar.frame.height)
self.toolbar.frame = frameRect
self.toolbar.alpha = 0
}
})
}
// outlet - debug label
@IBOutlet var debugLabel: UILabel!
// action - rewind button
@IBAction func rewindButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Rewind - Action"
}
// action - play button
@IBAction func playButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Play - Action"
}
// action - pause button
@IBAction func pauseButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Pause - Action"
}
// action - forward button
@IBAction func forwardButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Forward - Action"
}
// MARK: - View functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | e9223a67cca05d1bde0124ebd2c0203b | 29.022222 | 206 | 0.57883 | 4.921676 | false | false | false | false |
manavgabhawala/swift | test/SILGen/optional-cast.swift | 1 | 9855 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
class A {}
class B : A {}
// CHECK-LABEL: sil hidden @_T04main3fooyAA1ACSgF : $@convention(thin) (@owned Optional<A>) -> () {
// CHECK: bb0([[ARG:%.*]] : $Optional<A>):
// CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// Check whether the temporary holds a value.
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[T1:%.*]] = select_enum [[ARG_COPY]]
// CHECK-NEXT: cond_br [[T1]], [[IS_PRESENT:bb.*]], [[NOT_PRESENT:bb[0-9]+]]
//
// CHECK: [[NOT_PRESENT]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[NOT_PRESENT_FINISH:bb[0-9]+]]
//
// If so, pull the value out and check whether it's a B.
// CHECK: [[IS_PRESENT]]:
// CHECK-NEXT: [[VAL:%.*]] = unchecked_enum_data [[ARG_COPY]] : $Optional<A>, #Optional.some!enumelt.1
// CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some
// CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]]
//
// If so, materialize that and inject it into x.
// CHECK: [[IS_B]]([[T0:%.*]] : $B):
// CHECK-NEXT: store [[T0]] to [init] [[X_VALUE]] : $*B
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.some
// CHECK-NEXT: br [[CONT:bb[0-9]+]]
//
// If not, destroy_value the A and inject nothing into x.
// CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : $A):
// CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.none
// CHECK-NEXT: br [[CONT]]
//
// Finish the present path.
// CHECK: [[CONT]]:
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: br [[RETURN_BB:bb[0-9]+]]
//
// Finish.
// CHECK: [[RETURN_BB]]:
// CHECK-NEXT: destroy_value [[X]]
// CHECK-NEXT: destroy_value [[ARG]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
//
// Finish the not-present path.
// CHECK: [[NOT_PRESENT_FINISH]]:
// CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none
// CHECK-NEXT: br [[RETURN_BB]]
func foo(_ y : A?) {
var x = (y as? B)
}
// CHECK-LABEL: sil hidden @_T04main3baryAA1ACSgSgSgSgF : $@convention(thin) (@owned Optional<Optional<Optional<Optional<A>>>>) -> () {
// CHECK: bb0([[ARG:%.*]] : $Optional<Optional<Optional<Optional<A>>>>):
// CHECK: [[X:%.*]] = alloc_box ${ var Optional<Optional<Optional<B>>> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// -- Check for some(...)
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[T1:%.*]] = select_enum [[ARG_COPY]]
// CHECK-NEXT: cond_br [[T1]], [[P:bb.*]], [[NIL_DEPTH_1:bb[0-9]+]]
//
// CHECK: [[NIL_DEPTH_1]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[FINISH_NIL_0:bb[0-9]+]]
//
// If so, drill down another level and check for some(some(...)).
// CHECK: [[P]]:
// CHECK-NEXT: [[VALUE_OOOA:%.*]] = unchecked_enum_data [[ARG_COPY]]
// CHECK: [[T1:%.*]] = select_enum [[VALUE_OOOA]]
// CHECK-NEXT: cond_br [[T1]], [[PP:bb.*]], [[NIL_DEPTH_2:bb[0-9]+]]
//
// CHECK: [[NIL_DEPTH_2]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[FINISH_NIL_0]]
//
// If so, drill down another level and check for some(some(some(...))).
// CHECK: [[PP]]:
// CHECK-NEXT: [[VALUE_OOA:%.*]] = unchecked_enum_data [[VALUE_OOOA]]
// CHECK: [[T1:%.*]] = select_enum [[VALUE_OOA]]
// CHECK-NEXT: cond_br [[T1]], [[PPP:bb.*]], [[NIL_DEPTH_3:bb[0-9]+]]
//
// CHECK: [[NIL_DEPTH_3]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[FINISH_NIL_1:bb[0-9]+]]
//
// If so, drill down another level and check for some(some(some(some(...)))).
// CHECK: [[PPP]]:
// CHECK-NEXT: [[VALUE_OA:%.*]] = unchecked_enum_data [[VALUE_OOA]]
// CHECK: [[T1:%.*]] = select_enum [[VALUE_OA]]
// CHECK-NEXT: cond_br [[T1]], [[PPPP:bb.*]], [[NIL_DEPTH_4:bb[0-9]+]]
//
// CHECK: [[NIL_DEPTH_4]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[FINISH_NIL_2:bb[0-9]+]]
//
// If so, pull out the A and check whether it's a B.
// CHECK: [[PPPP]]:
// CHECK-NEXT: [[VAL:%.*]] = unchecked_enum_data [[VALUE_OA]]
// CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]]
//
// If so, inject it back into an optional.
// TODO: We're going to switch back out of this; we really should peephole it.
// CHECK: [[IS_B]]([[T0:%.*]] : $B):
// CHECK-NEXT: enum $Optional<B>, #Optional.some!enumelt.1, [[T0]]
// CHECK-NEXT: br [[SWITCH_OB2:bb[0-9]+]](
//
// If not, inject nothing into an optional.
// CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : $A):
// CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]]
// CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt
// CHECK-NEXT: br [[SWITCH_OB2]](
//
// Switch out on the value in [[OB2]].
// CHECK: [[SWITCH_OB2]]([[VAL:%[0-9]+]] : $Optional<B>):
// CHECK: [[T0:%.*]] = select_enum [[VAL]]
// CHECK: cond_br [[T0]], [[HAVE_B:bb[0-9]+]], [[FINISH_NIL_4:bb[0-9]+]]
//
// CHECK: [[FINISH_NIL_4]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[FINISH_NIL_0]]
//
// CHECK: [[HAVE_B]]:
// CHECK: [[UNWRAPPED_VAL:%.*]] = unchecked_enum_data [[VAL]]
// CHECK: [[REWRAPPED_VAL:%.*]] = enum $Optional<B>, #Optional.some!enumelt.1, [[UNWRAPPED_VAL]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[DONE_DEPTH0:bb[0-9]+]]
//
// CHECK: [[DONE_DEPTH0]](
// CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.some!enumelt.1,
// CHECK-NEXT: br [[DONE_DEPTH1:bb[0-9]+]]
//
// Set X := some(OOB).
// CHECK: [[DONE_DEPTH1]]
// CHECK-NEXT: enum $Optional<Optional<Optional<B>>>, #Optional.some!enumelt.1,
// CHECK: br [[DONE_DEPTH2:bb[0-9]+]]
// CHECK: [[DONE_DEPTH2]]
// CHECK-NEXT: destroy_value [[X]]
// CHECK-NEXT: destroy_value %0
// CHECK: return
//
// On various failure paths, set OOB := nil.
// CHECK: [[FINISH_NIL_2]]:
// CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE_DEPTH0]]
//
// CHECK: [[FINISH_NIL_1]]:
// CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE_DEPTH1]]
//
// On various failure paths, set X := nil.
// CHECK: [[FINISH_NIL_0]]:
// CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none
// CHECK-NEXT: br [[DONE_DEPTH2]]
// Done.
func bar(_ y : A????) {
var x = (y as? B??)
}
// CHECK-LABEL: sil hidden @_T04main3bazys9AnyObject_pSgF : $@convention(thin) (@owned Optional<AnyObject>) -> () {
// CHECK: bb0([[ARG:%.*]] : $Optional<AnyObject>):
// CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[T1:%.*]] = select_enum [[ARG_COPY]]
// CHECK: bb1:
// CHECK: [[VAL:%.*]] = unchecked_enum_data [[ARG_COPY]]
// CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some
// CHECK-NEXT: checked_cast_br [[VAL]] : $AnyObject to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]]
// CHECK: [[IS_B]]([[CASTED_VALUE:%.*]] : $B):
// CHECK: store [[CASTED_VALUE]] to [init] [[X_VALUE]]
// CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : $AnyObject):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: } // end sil function '_T04main3bazys9AnyObject_pSgF'
func baz(_ y : AnyObject?) {
var x = (y as? B)
}
// <rdar://problem/17013042> T! <-> T? conversions should not produce a diamond
// CHECK-LABEL: sil hidden @_T04main07opt_to_B8_trivialSQySiGSiSgF
// CHECK: bb0(%0 : $Optional<Int>):
// CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "x"
// CHECK-NEXT: return %0 : $Optional<Int>
// CHECK-NEXT:}
func opt_to_opt_trivial(_ x: Int?) -> Int! {
return x
}
// CHECK-LABEL: sil hidden @_T04main07opt_to_B10_referenceAA1CCSgSQyADGF :
// CHECK: bb0([[ARG:%.*]] : $Optional<C>):
// CHECK: debug_value [[ARG]] : $Optional<C>, let, name "x"
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[RESULT:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[RESULT]] : $Optional<C>
// CHECK: } // end sil function '_T04main07opt_to_B10_referenceAA1CCSgSQyADGF'
func opt_to_opt_reference(_ x : C!) -> C? { return x }
// CHECK-LABEL: sil hidden @_T04main07opt_to_B12_addressOnly{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<T>, %1 : $*Optional<T>):
// CHECK-NEXT: debug_value_addr %1 : $*Optional<T>, let, name "x"
// CHECK-NEXT: copy_addr %1 to [initialization] %0
// CHECK-NEXT: destroy_addr %1
func opt_to_opt_addressOnly<T>(_ x : T!) -> T? { return x }
class C {}
public struct TestAddressOnlyStruct<T> {
func f(_ a : T?) {}
// CHECK-LABEL: sil hidden @_T04main21TestAddressOnlyStructV8testCall{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<T>, %1 : $TestAddressOnlyStruct<T>):
// CHECK: [[TMPBUF:%.*]] = alloc_stack $Optional<T>
// CHECK-NEXT: copy_addr %0 to [initialization] [[TMPBUF]]
// CHECK-NEXT: apply {{.*}}<T>([[TMPBUF]], %1)
func testCall(_ a : T!) {
f(a)
}
}
// CHECK-LABEL: sil hidden @_T04main35testContextualInitOfNonAddrOnlyTypeySiSgF
// CHECK: bb0(%0 : $Optional<Int>):
// CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a"
// CHECK-NEXT: [[X:%.*]] = alloc_box ${ var Optional<Int> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// CHECK-NEXT: store %0 to [trivial] [[PB]] : $*Optional<Int>
// CHECK-NEXT: destroy_value [[X]] : ${ var Optional<Int> }
func testContextualInitOfNonAddrOnlyType(_ a : Int?) {
var x: Int! = a
}
| apache-2.0 | c6fc12f336ac7fb4f5c9625eae44616b | 40.23431 | 135 | 0.570472 | 2.848266 | false | false | false | false |
samodom/CoreDataSwagger | CoreDataSwaggerTests/Tests/FetchTests.swift | 1 | 8452 | //
// FetchTests.swift
// CoreDataSwagger
//
// Created by Sam Odom on 10/21/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import CoreData
import XCTest
class FetchTests: XCTestCase {
var stack: CoreDataStack!
var goodRequest: NSFetchRequest!
var badRequest: NSFetchRequest!
var objectResults: [NSManagedObject]?
var objectIDResults: [NSManagedObjectID]?
var dictionaryResults: [AnyObject]?
var count: UInt?
var error: NSError?
var apple: Fruit!
var banana: Fruit!
var lettuce: Vegetable!
override func setUp() {
super.setUp()
let model = LoadModel(named: "Produce")
let modelSource = CoreDataModelSource(models: [model])
let configuration = CoreDataStackConfiguration(modelSource: modelSource)
stack = CoreDataStack(configuration: configuration)
createProduce()
goodRequest = NSFetchRequest(entityName: "Produce")
badRequest = NSFetchRequest(entityName: "Car")
}
override func tearDown() {
super.tearDown()
}
func createProduce() {
stack.save() {
let context = self.stack.context
self.apple = Fruit(name: "Apple", color: "red", context: context)
self.banana = Fruit(name: "Banana", color: "yellow", context: context)
self.lettuce = Vegetable(name: "Lettuce", color: "green", context: context)
}
}
func testSuccessfulManagedObjectFetchRequest() {
(objectResults, error) = stack.fetch(goodRequest)
XCTAssertTrue(error == nil, "There should be no error returned")
XCTAssertTrue(objectResults != nil, "There should be fetch results returned")
XCTAssertEqual(objectResults!.count, 3, "There should be three objects returned")
XCTAssertTrue(contains(objectResults!, apple), "The apple should be included in the results")
XCTAssertTrue(contains(objectResults!, banana), "The banana should be included in the results")
XCTAssertTrue(contains(objectResults!, lettuce), "The lettuce should be included in the results")
}
func testFailingManagedObjectFetchRequest() {
(objectResults, error) = stack.fetch(badRequest)
XCTAssertTrue(error != nil, "There should be an error returned")
XCTAssertTrue(objectResults == nil, "There should be no fetch results returned")
}
func testSuccessfulManagedObjectIdentifierFetchRequest() {
goodRequest.resultType = .ManagedObjectIDResultType
(objectIDResults, error) = stack.fetchIDs(goodRequest)
XCTAssertTrue(error == nil, "There should be no error returned")
XCTAssertTrue(objectIDResults != nil, "There should be fetch results returned")
XCTAssertEqual(objectIDResults!.count, 3, "There should be three object identifiers returned")
XCTAssertTrue(contains(objectIDResults!, apple.objectID), "The apple object identifier should be included in the results")
XCTAssertTrue(contains(objectIDResults!, banana.objectID), "The banana object identifier should be included in the results")
XCTAssertTrue(contains(objectIDResults!, lettuce.objectID), "The lettuce object identifier should be included in the results")
}
func testFailingManagedObjectIdentifierFetchRequest() {
badRequest.resultType = .ManagedObjectIDResultType
(objectIDResults, error) = stack.fetchIDs(badRequest)
XCTAssertTrue(error != nil, "There should be an error returned")
XCTAssertTrue(objectIDResults == nil, "There should be no fetch results returned")
}
func testSuccessfulDictionaryFetchRequest() {
goodRequest.resultType = .DictionaryResultType
goodRequest.propertiesToFetch = GetNameAndColorProperties(inContext: stack.context)
goodRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
(dictionaryResults, error) = stack.fetchDictionaries(goodRequest)
XCTAssertTrue(error == nil, "There should be no error returned")
XCTAssertTrue(dictionaryResults != nil, "There should be fetch results returned")
XCTAssertEqual(dictionaryResults!.count, 3, "There should be three objects returned")
var values = dictionaryResults![0] as [NSString:AnyObject]
XCTAssertEqual(values["name"] as String, "Apple", "The apple should be included in the results")
XCTAssertEqual(values["color"] as String, "red", "The apple should be included in the results")
values = dictionaryResults![1] as [NSString:AnyObject]
XCTAssertEqual(values["name"] as String, "Banana", "The banana should be included in the results")
XCTAssertEqual(values["color"] as String, "yellow", "The banana should be included in the results")
values = dictionaryResults![2] as [NSString:AnyObject]
XCTAssertEqual(values["name"] as String, "Lettuce", "The lettuce should be included in the results")
XCTAssertEqual(values["color"] as String, "green", "The lettuce should be included in the results")
}
func testFailingDictionaryFetchRequest() {
badRequest.resultType = .DictionaryResultType
badRequest.propertiesToFetch = GetNameAndColorProperties(inContext: stack.context)
badRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
(dictionaryResults, error) = stack.fetchDictionaries(badRequest)
XCTAssertTrue(error != nil, "There should be an error returned")
XCTAssertTrue(dictionaryResults == nil, "There should be no fetch results returned")
}
func testSuccessfulCountFetchRequest() {
goodRequest.resultType = .CountResultType
(count, error) = stack.count(goodRequest)
XCTAssertTrue(error == nil, "There should be no error returned")
XCTAssertTrue(count != nil, "There should be fetch result count returned")
XCTAssertEqual(count!, UInt(3), "There should be three objects that would be returned in a fetch request")
}
func testFailingCountFetchRequest() {
badRequest.resultType = .CountResultType
(count, error) = stack.count(badRequest)
XCTAssertTrue(error != nil, "There should be an error returned")
XCTAssertTrue(count == nil, "There should be no fetch result count returned")
}
func testSuccessfulEntityNameFetch() {
(objectResults, error) = stack.fetch("Fruit")
XCTAssertTrue(error == nil, "There should be no error returned")
XCTAssertTrue(objectResults != nil, "There should be fetch results returned")
XCTAssertEqual(objectResults!.count, 2, "There should be two objects returned")
XCTAssertTrue(contains(objectResults!, apple), "The apple should be included in the results")
XCTAssertTrue(contains(objectResults!, banana), "The banana should be included in the results")
}
func testFailingEntityNameFetch() {
(objectResults, error) = stack.fetch("Car")
XCTAssertTrue(error != nil, "There should be an error returned")
XCTAssertTrue(objectResults == nil, "There should be no fetch results returned")
}
func testSuccessfulEntityDescriptionFetch() {
let entity = NSEntityDescription.entityForName("Fruit", inManagedObjectContext: stack.context)!
(objectResults, error) = stack.fetch(entity)
XCTAssertTrue(error == nil, "There should be no error returned")
XCTAssertTrue(objectResults != nil, "There should be fetch results returned")
XCTAssertEqual(objectResults!.count, 2, "There should be two objects returned")
XCTAssertTrue(contains(objectResults!, apple), "The apple should be included in the results")
XCTAssertTrue(contains(objectResults!, banana), "The banana should be included in the results")
}
}
private func GetNameAndColorProperties(inContext context: NSManagedObjectContext) -> [NSPropertyDescription] {
let nameProperty = GetProducePropertyDescription(named: "name", inContext: context)!
let colorProperty = GetProducePropertyDescription(named: "color", inContext: context)!
return [nameProperty, colorProperty]
}
private func GetProducePropertyDescription(named propertyName: String, inContext context: NSManagedObjectContext) -> NSPropertyDescription? {
let entity = NSEntityDescription.entityForName("Produce", inManagedObjectContext: context)
return entity!.propertiesByName[propertyName] as? NSPropertyDescription
}
| mit | cd9fe345fee5a6472526f2c3827fbe0f | 49.915663 | 141 | 0.709536 | 5.113128 | false | true | false | false |
Syject/MyLessPass-iOS | LessPass/Libraries/KeychainHelper.swift | 1 | 16661 | //
// KeychainHelper.swift
// PupilHD
//
// Created by Dan Slupskiy on 29.11.16.
// Copyright © 2016 Syject. All rights reserved.
//
import Security
import Foundation
/**
A collection of helper functions for saving text and data in the keychain.
*/
open class KeychainSwift {
var lastQueryParameters: [String: Any]? // Used by the unit tests
/// Contains result code from the last operation. Value is noErr (0) for a successful result.
open var lastResultCode: OSStatus = noErr
var keyPrefix = "" // Can be useful in test.
/**
Specify an access group that will be used to access keychain items. Access groups can be used to share keychain items between applications. When access group value is nil all application access groups are being accessed. Access group name is used by all functions: set, get, delete and clear.
*/
open var accessGroup: String?
/**
Specifies whether the items can be synchronized with other devices through iCloud. Setting this property to true will
add the item to other devices with the `set` method and obtain synchronizable items with the `get` command. Deleting synchronizable items will remove them from all devices. In order for keychain synchronization to work the user must enable "Keychain" in iCloud settings.
Does not work on macOS.
*/
open var synchronizable: Bool = false
/// Instantiate a KeychainSwift object
public init() { }
/**
- parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
*/
public init(keyPrefix: String) {
self.keyPrefix = keyPrefix
}
/**
Stores the text value in the keychain item under the given key.
- parameter key: Key under which the text value is stored in the keychain.
- parameter value: Text string to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
@discardableResult
open func set(_ value: String, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
if let value = value.data(using: String.Encoding.utf8) {
return set(value, forKey: key, withAccess: access)
}
return false
}
/**
Stores the data in the keychain item under the given key.
- parameter key: Key under which the data is stored in the keychain.
- parameter value: Data to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
@discardableResult
open func set(_ value: Data, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
delete(key) // Delete any existing key before saving it
let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
let prefixedKey = keyWithPrefix(key)
var query: [String : Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.valueData : value,
KeychainSwiftConstants.accessible : accessible
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: true)
lastQueryParameters = query
lastResultCode = SecItemAdd(query as CFDictionary, nil)
return lastResultCode == noErr
}
/**
Stores the boolean value in the keychain item under the given key.
- parameter key: Key under which the value is stored in the keychain.
- parameter value: Boolean to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the value in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the value was successfully written to the keychain.
*/
@discardableResult
open func set(_ value: Bool, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
let bytes: [UInt8] = value ? [1] : [0]
let data = Data(bytes: bytes)
return set(data, forKey: key, withAccess: access)
}
/**
Retrieves the text value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
open func get(_ key: String) -> String? {
if let data = getData(key) {
if let currentString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String {
return currentString
}
lastResultCode = -67853 // errSecInvalidEncoding
}
return nil
}
/**
Retrieves the data from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
open func getData(_ key: String) -> Data? {
let prefixedKey = keyWithPrefix(key)
var query: [String: Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.returnData : kCFBooleanTrue,
KeychainSwiftConstants.matchLimit : kSecMatchLimitOne
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
var result: AnyObject?
lastResultCode = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if lastResultCode == noErr { return result as? Data }
return nil
}
/**
Retrieves the boolean value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The boolean value from the keychain. Returns nil if unable to read the item.
*/
open func getBool(_ key: String) -> Bool? {
guard let data = getData(key) else { return nil }
guard let firstBit = data.first else { return nil }
return firstBit == 1
}
/**
Deletes the single keychain item specified by the key.
- parameter key: The key that is used to delete the keychain item.
- returns: True if the item was successfully deleted.
*/
@discardableResult
open func delete(_ key: String) -> Bool {
let prefixedKey = keyWithPrefix(key)
var query: [String: Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionary)
return lastResultCode == noErr
}
/**
Deletes all Keychain items used by the app. Note that this method deletes all items regardless of the prefix settings used for initializing the class.
- returns: True if the keychain items were successfully deleted.
*/
@discardableResult
open func clear() -> Bool {
var query: [String: Any] = [ kSecClass as String : kSecClassGenericPassword ]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionary)
return lastResultCode == noErr
}
/// Returns the key with currently set prefix.
func keyWithPrefix(_ key: String) -> String {
return "\(keyPrefix)\(key)"
}
func addAccessGroupWhenPresent(_ items: [String: Any]) -> [String: Any] {
guard let accessGroup = accessGroup else { return items }
var result: [String: Any] = items
result[KeychainSwiftConstants.accessGroup] = accessGroup
return result
}
/**
Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny` item to the dictionary when the `synchronizable` property is true.
- parameter items: The dictionary where the kSecAttrSynchronizable items will be added when requested.
- parameter addingItems: Use `true` when the dictionary will be used with `SecItemAdd` method (adding a keychain item). For getting and deleting items, use `false`.
- returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary.
*/
func addSynchronizableIfRequired(_ items: [String: Any], addingItems: Bool) -> [String: Any] {
if !synchronizable { return items }
var result: [String: Any] = items
result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny
return result
}
}
// ----------------------------
//
// KeychainSwiftAccessOptions.swift
//
// ----------------------------
import Security
/**
These options are used to determine when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
*/
public enum KeychainSwiftAccessOptions {
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.
This is the default value for keychain items added without explicitly setting an accessibility constant.
*/
case accessibleWhenUnlocked
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleWhenUnlockedThisDeviceOnly
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
*/
case accessibleAfterFirstUnlock
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleAfterFirstUnlockThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
*/
case accessibleAlways
/**
The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.
*/
case accessibleWhenPasscodeSetThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleAlwaysThisDeviceOnly
static var defaultOption: KeychainSwiftAccessOptions {
return .accessibleWhenUnlocked
}
var value: String {
switch self {
case .accessibleWhenUnlocked:
return toString(kSecAttrAccessibleWhenUnlocked)
case .accessibleWhenUnlockedThisDeviceOnly:
return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .accessibleAfterFirstUnlock:
return toString(kSecAttrAccessibleAfterFirstUnlock)
case .accessibleAfterFirstUnlockThisDeviceOnly:
return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
case .accessibleAlways:
return toString(kSecAttrAccessibleAlways)
case .accessibleWhenPasscodeSetThisDeviceOnly:
return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
case .accessibleAlwaysThisDeviceOnly:
return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
}
}
func toString(_ value: CFString) -> String {
return KeychainSwiftConstants.toString(value)
}
}
// ----------------------------
//
// TegKeychainConstants.swift
//
// ----------------------------
import Foundation
import Security
/// Constants used by the library
public struct KeychainSwiftConstants {
/// Specifies a Keychain access group. Used for sharing Keychain items between apps.
public static var accessGroup: String { return toString(kSecAttrAccessGroup) }
/**
A value that indicates when your app needs access to the data in a keychain item. The default value is AccessibleWhenUnlocked. For a list of possible values, see KeychainSwiftAccessOptions.
*/
public static var accessible: String { return toString(kSecAttrAccessible) }
/// Used for specifying a String key when setting/getting a Keychain value.
public static var attrAccount: String { return toString(kSecAttrAccount) }
/// Used for specifying synchronization of keychain items between devices.
public static var attrSynchronizable: String { return toString(kSecAttrSynchronizable) }
/// An item class key used to construct a Keychain search dictionary.
public static var klass: String { return toString(kSecClass) }
/// Specifies the number of values returned from the keychain. The library only supports single values.
public static var matchLimit: String { return toString(kSecMatchLimit) }
/// A return data type used to get the data from the Keychain.
public static var returnData: String { return toString(kSecReturnData) }
/// Used for specifying a value when setting a Keychain value.
public static var valueData: String { return toString(kSecValueData) }
static func toString(_ value: CFString) -> String {
return value as String
}
}
| gpl-3.0 | ec47320d0f1965d00e2c97416566b5d3 | 38.761337 | 380 | 0.669928 | 5.655126 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | AppCoreData_GDP/AppCoreData_GDP/DPServiciosJuridicosViewController.swift | 1 | 1710 | //
// DPServiciosJuridicosViewController.swift
// AppCoreData_GDP
//
// Created by formador on 14/9/16.
// Copyright © 2016 iCologic. All rights reserved.
//
import UIKit
class DPServiciosJuridicosViewController: UIViewController {
//MARK: - IBOUTLET
@IBOutlet weak var myCustomScrollView: UIScrollView!
@IBOutlet weak var myCustomPageControll: UIPageControl!
//MARK: - LIFE VC
override func viewDidLoad() {
super.viewDidLoad()
//let alturaVariableSegunDispositivo = self.view.frame.height
//1 - Creacion del bucle de fotos
for indiceFotos in 0..<15{
let imagenesSerJur = UIImageView(image: UIImage(named: NSString(format: "AJ_%d.jpg", indiceFotos)as String))
imagenesSerJur.frame = CGRectMake(CGFloat(indiceFotos - 1) * 540, 0, 540, 352)
myCustomScrollView.addSubview(imagenesSerJur)
}
myCustomScrollView.delegate = self
myCustomScrollView.contentSize = CGSizeMake(14 * 540, 352)
myCustomScrollView.pagingEnabled = true
myCustomPageControll.numberOfPages = 14
myCustomPageControll.currentPage = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: - EXTENCION DE SCROLL VIEW
extension DPServiciosJuridicosViewController : UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let paginado = myCustomScrollView.contentOffset.x / myCustomScrollView.frame.width
myCustomPageControll.currentPage = Int(paginado)
}
}
| apache-2.0 | 6385853ad6cd25c8174ec788ce48a64e | 28.465517 | 120 | 0.672908 | 4.720994 | false | false | false | false |
teambox/RealmResultsController | Example/RealmResultsController-iOSTests/TestModels.swift | 2 | 1809 | //
// testmodels.swift
// RealmResultsController
//
// Created by Isaac Roldan on 6/8/15.
// Copyright © 2015 Redbooth.
//
import Foundation
import RealmSwift
func NewTask(_ id: Int) -> Task {
let task = Task()
task.id = id
return task
}
class Task: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var resolved = false
dynamic var projectID = 0
dynamic var user: User?
override static func primaryKey() -> String? {
return "id"
}
static func map(_ model: TaskModel) -> Task {
let task = Task()
task.id = model.id
task.name = model.name
task.resolved = model.resolved
task.projectID = model.projectID
return task
}
static func mapTask(_ taskModel: Task) -> TaskModel {
let task = TaskModel()
task.id = taskModel.id
task.name = taskModel.name
task.resolved = taskModel.resolved
task.projectID = taskModel.projectID
return task
}
}
class TaskModel: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var resolved = false
dynamic var projectID = 0
dynamic var user: User?
override static func primaryKey() -> String? {
return "id"
}
}
class User: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var avatarURL = ""
override static func primaryKey() -> String? {
return "id"
}
}
class Project: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var projectDrescription = ""
override static func primaryKey() -> String? {
return "id"
}
}
class Dummy: RealmSwift.Object {
dynamic var id: Int = 0
dynamic var optionalNilValue: Project?
}
| mit | 2d55245237addd7c89c9237cca90e7f9 | 20.783133 | 57 | 0.603429 | 4.194896 | false | false | false | false |
analuizaferrer/TrocaComigo | Example/SwapIt/ClosetCollectionViewController.swift | 1 | 4659 | //
// ClosetCollectionViewController.swift
// Koloda
//
// Created by Helena Leitão on 18/06/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class ClosetCollectionViewController: UICollectionViewController {
private let leftAndRightPadding: CGFloat = 0.0
private let numberOfItensPerRow: CGFloat = 3.0
private let heightAdjustment: CGFloat = 30.0
let teste1 = UIImage(named: "pizza")
let teste2 = UIImage(named: "pizza")
let teste3 = UIImage(named: "pizza")
var productArrayCloset: [UIImage]! = []
var productImages: [NSData]!
override func viewDidLoad() {
super.viewDidLoad()
let cellWidth = (CGRectGetWidth((collectionView?.frame)!) - leftAndRightPadding) / numberOfItensPerRow
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSizeMake(cellWidth, cellWidth)
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
productArrayCloset.removeAll()
if User.singleton.products.count > 0 {
for i in closetArray {
let image = UIImage(data: i)
productArrayCloset.append(image!)
}
self.collectionView?.reloadData()
// for product in User.singleton.products {
//
// let image = UIImage(data: product.images![0])
// productArray.append(image!)
//
// }
// self.collectionView?.reloadData()
}
}
// func callback(data: NSData?, error: NSError?) {
// if error == nil {
// let image: UIImage = UIImage(data: data!)!
// product.append(image)
// print(product.count)
// } else {
// print(error)
// }
// }
@IBAction func prepareForUnwind(segue: UIStoryboardSegue) {
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return productArrayCloset.count
}
private struct Storyboard {
static let CellIdentifier = "closetCell"
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("closetCell", forIndexPath: indexPath) as! ClosetCollectionViewCell
let thisProduct = productArrayCloset[indexPath.row]
cell.productImageView.contentMode = UIViewContentMode.ScaleAspectFill
cell.productImageView.image = thisProduct
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
| mit | ab9b8770cf91f73cb5d79c586a2fe238 | 32.264286 | 185 | 0.65321 | 5.590636 | false | false | false | false |
rgkobashi/PhotoSearcher | PhotoViewer/FlickrPhoto.swift | 1 | 2579 | //
// FlickrPhoto.swift
// PhotoViewer
//
// Created by Rogelio Martinez Kobashi on 2/28/17.
// Copyright © 2017 Rogelio Martinez Kobashi. All rights reserved.
//
import Foundation
import UIKit
class FlickrPhoto: Photo
{
var text = ""
var thumbnailUrl = ""
var originalUrl = ""
var secret = ""
var id = ""
var server = ""
var farm = 0
}
class FlickrUtility
{
class func parseResponse(_ response: AnyObject) -> [FlickrPhoto]
{
var resPhotos = [FlickrPhoto]()
if let response = response as? [String : AnyObject]
{
if let photos = response["photos"] as? [String : AnyObject]
{
if let photo = photos["photo"] as? [AnyObject]
{
for aPhoto in photo
{
let flickrPhoto = FlickrPhoto()
if let secret = aPhoto["secret"] as? String
{
flickrPhoto.secret = secret
}
if let id = aPhoto["id"] as? String
{
flickrPhoto.id = id
}
if let server = aPhoto["server"] as? String
{
flickrPhoto.server = server
}
if let farm = aPhoto["farm"] as? Int
{
flickrPhoto.farm = farm
}
if let title = aPhoto["title"] as? String
{
flickrPhoto.text = title
}
flickrPhoto.thumbnailUrl = thumbnailUrlFromFlickrPhoto(flickrPhoto)
flickrPhoto.originalUrl = originalUrlFromFlickrPhoto(flickrPhoto)
resPhotos.append(flickrPhoto)
}
}
}
}
return resPhotos
}
fileprivate class func thumbnailUrlFromFlickrPhoto(_ flickrPhoto: FlickrPhoto) -> String
{
let url = "https://farm\(flickrPhoto.farm).static.flickr.com/\(flickrPhoto.server)/\(flickrPhoto.id)_\(flickrPhoto.secret)_s.jpg"
return url
}
fileprivate class func originalUrlFromFlickrPhoto(_ flickrPhoto: FlickrPhoto) -> String
{
let url = "https://farm\(flickrPhoto.farm).static.flickr.com/\(flickrPhoto.server)/\(flickrPhoto.id)_\(flickrPhoto.secret)_b.jpg"
return url
}
}
| mit | f9dbc928a0c394cb66c200ccef55e1b6 | 32.051282 | 137 | 0.478666 | 5.508547 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/advantage-shuffle.swift | 2 | 602 | /**
* https://leetcode.com/problems/advantage-shuffle/
*
*
*/
// Date: Wed Mar 24 08:54:50 PDT 2021
class Solution {
func advantageCount(_ A: [Int], _ B: [Int]) -> [Int] {
let a = A.sorted()
let b = B.enumerated().sorted { $0.1 < $1.1 }
var result = A
var start = 0
var end = A.count - 1
for num in a {
if num > b[start].1 {
result[b[start].0] = num
start += 1
} else {
result[b[end].0] = num
end -= 1
}
}
return result
}
} | mit | 235ee2cbffa26910434d9e4213baa973 | 23.12 | 58 | 0.418605 | 3.56213 | false | false | false | false |
RuiAAPeres/Argo | Argo/Types/StandardTypes.swift | 1 | 2565 | import Foundation
extension String: Decodable {
public static func decode(j: JSON) -> Decoded<String> {
switch j {
case let .String(s): return pure(s)
default: return typeMismatch("String", forObject: j)
}
}
}
extension Int: Decodable {
public static func decode(j: JSON) -> Decoded<Int> {
switch j {
case let .Number(n): return pure(n as Int)
default: return typeMismatch("Int", forObject: j)
}
}
}
extension Int64: Decodable {
public static func decode(j: JSON) -> Decoded<Int64> {
switch j {
case let .Number(n): return pure(n.longLongValue)
default: return typeMismatch("Int64", forObject: j)
}
}
}
extension Double: Decodable {
public static func decode(j: JSON) -> Decoded<Double> {
switch j {
case let .Number(n): return pure(n as Double)
default: return typeMismatch("Double", forObject: j)
}
}
}
extension Bool: Decodable {
public static func decode(j: JSON) -> Decoded<Bool> {
switch j {
case let .Number(n): return pure(n as Bool)
default: return typeMismatch("Bool", forObject: j)
}
}
}
extension Float: Decodable {
public static func decode(j: JSON) -> Decoded<Float> {
switch j {
case let .Number(n): return pure(n as Float)
default: return typeMismatch("Float", forObject: j)
}
}
}
public extension Optional where T: Decodable, T == T.DecodedType {
static func decode(j: JSON) -> Decoded<T?> {
return .optional(T.decode(j))
}
}
public extension Array where Element: Decodable, Element == Element.DecodedType {
static func decode(j: JSON) -> Decoded<[Element]> {
switch j {
case let .Array(a): return sequence(a.map(Element.decode))
default: return typeMismatch("Array", forObject: j)
}
}
}
public extension Dictionary where Value: Decodable, Value == Value.DecodedType {
static func decode(j: JSON) -> Decoded<[String: Value]> {
switch j {
case let .Object(o): return sequence(Value.decode <^> o)
default: return typeMismatch("Object", forObject: j)
}
}
}
func decodedJSON(json: JSON, forKey key: String) -> Decoded<JSON> {
switch json {
case let .Object(o): return guardNull(key, j: o[key] ?? .Null)
default: return typeMismatch("Object", forObject: json)
}
}
private func typeMismatch<T>(expectedType: String, forObject object: JSON) -> Decoded<T> {
return .TypeMismatch("\(object) is not a \(expectedType)")
}
private func guardNull(key: String, j: JSON) -> Decoded<JSON> {
switch j {
case .Null: return .MissingKey(key)
default: return pure(j)
}
}
| mit | 6d3eeb009c59e38750d681424eafda05 | 25.443299 | 90 | 0.660429 | 3.638298 | false | false | false | false |
euajudo/ios | euajudo/View/CampaignGoalView.swift | 1 | 1357 | //
// CampaignGoalView.swift
// euajudo
//
// Created by Filipe Alvarenga on 12/04/15.
// Copyright (c) 2015 euajudo. All rights reserved.
//
import UIKit
class CampaignGoalView: UIView {
var campaign: Campaign! {
didSet {
self.generatePercentage()
}
}
@IBOutlet weak var progressContainer: UIView!
@IBOutlet weak var progress: UIView!
@IBOutlet weak var labelActualValue: UILabel!
@IBOutlet weak var labelFinalValue: UILabel!
func generatePercentage() {
var percentage = (((campaign.donatedValue * 100.0) / campaign.targetValue) / 100)
if percentage > 1 {
percentage = 1
}
let progressWidth = self.progressContainer.bounds.width * CGFloat(percentage)
self.progress.layer.frame = CGRect(
x: 0.0,
y: 0.0,
width: progressWidth,
height: self.progress.bounds.height
)
// Update labels
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.currencySymbol = ""
formatter.maximumFractionDigits = 0
labelActualValue.text = "R$ \(formatter.stringFromNumber(campaign.donatedValue)!)"
labelFinalValue.text = "R$ \(formatter.stringFromNumber(campaign.targetValue)!)"
}
}
| mit | 905176194eb64204d8e528e009554b14 | 26.14 | 90 | 0.615328 | 4.6 | false | false | false | false |
xiabob/ZhiHuDaily | ZhiHuDaily/ZhiHuDaily/Views/Theme/ThemeEditorView.swift | 1 | 3628 | //
// ThemeEditorView.swift
// ZhiHuDaily
//
// Created by xiabob on 17/4/12.
// Copyright © 2017年 xiabob. All rights reserved.
//
import UIKit
class ThemeEditorView: UIControl {
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.textColor = UIColor.black.withAlphaComponent(0.6)
label.text = "主编"
label.sizeToFit()
return label
}()
fileprivate lazy var editorCollectionView: UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 20, height: 20)
layout.minimumInteritemSpacing = 4
layout.scrollDirection = .horizontal
let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.register(UICollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(UICollectionViewCell.self))
view.backgroundColor = UIColor.white
view.showsHorizontalScrollIndicator = false
view.dataSource = self
view.isUserInteractionEnabled = false
return view
}()
fileprivate lazy var flagView: UIImageView = {
let view = UIImageView(image: #imageLiteral(resourceName: "Editor_Arrow"))
view.sizeToFit()
return view
}()
fileprivate lazy var bottomLine: UIView = {
let view = UIView()
view.backgroundColor = kXBBorderColor
return view
}()
fileprivate var editorModels = [EditorModel]()
//MARK: - init
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
configViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - config view
fileprivate func configViews() {
addSubview(titleLabel)
addSubview(editorCollectionView)
addSubview(flagView)
addSubview(bottomLine)
setLayout()
}
fileprivate func setLayout() {
titleLabel.xb_left = 12
titleLabel.xb_centerY = xb_centerY
flagView.xb_right = xb_width - 12
flagView.xb_centerY = titleLabel.xb_centerY
editorCollectionView.xb_left = titleLabel.xb_right + 12
editorCollectionView.xb_relativeRight = flagView.xb_left - 8
editorCollectionView.xb_height = xb_height
editorCollectionView.xb_centerY = titleLabel.xb_centerY
bottomLine.xb_left = 0
bottomLine.xb_bottom = xb_height
bottomLine.xb_width = xb_width
bottomLine.xb_height = kXBBorderWidth
}
//
func refreshViews(with editorModels: [EditorModel]) {
self.editorModels = editorModels
editorCollectionView.reloadData()
}
}
//MARK : - UICollectionViewDataSource
extension ThemeEditorView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return editorModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(UICollectionViewCell.self), for: indexPath)
let model = editorModels[indexPath.row]
cell.layer.yy_setImage(with: URL(string: model.avatar), placeholder: #imageLiteral(resourceName: "Field_Avatar"))
cell.xb_setCornerRadius(10)
return cell
}
}
| mit | e5163cccb8069daf436bf0d28f99eea9 | 31.044248 | 136 | 0.658934 | 5.078541 | false | false | false | false |
anto0522/AdMate | AdMate/LineChart.swift | 1 | 39407 | ///
// LineChart.swift
// SensorTag
//
// Created by Kevin Brewster on 1/7/15.
// Copyright (c) 2015 KevinBrewster. All rights reserved.
//
import QuartzCore
import AdDataKit2
public func rounder (numbertoround: CGFloat) -> String {
let rounded: NSString
if (numbertoround > 10){
rounded = NSString(format: "%.02f", numbertoround)
} else if (numbertoround < 1){
rounded = NSString(format: "%.02f", numbertoround)
} else {
rounded = NSString(format: "%.02f", numbertoround)
}
return rounded as String
}
import AppKit
class LineChartView: NSView {
// A simple NSView which "hosts" a LineChart as it's layer
// It does a couple nice things on top of the core LineChart functionality:
// 1) Auto-resizes the LineChart layer when view is resized
// 2) Tracks mouse movement and displays a tooltip at the closest point
let popover = NSPopover()
var popoverPoint: LineChart.Point?
var lineChart: LineChart { return layer as! LineChart }
var trackingArea: NSTrackingArea!
required init?(coder: NSCoder) {
super.init(coder: coder)
self.layer = LineChart() as LineChart
self.layer!.autoresizingMask = [CAAutoresizingMask.LayerWidthSizable, CAAutoresizingMask.LayerHeightSizable]
self.layer!.needsDisplayOnBoundsChange = true
self.wantsLayer = true
popover.contentViewController = SimpleLineChartTooltop(nibName: nil, bundle: nil)
updateTrackingAreas()
}
func layoutSubviews() {
lineChart.frame = self.bounds
}
override func viewDidChangeBackingProperties() {
// self.print("viewDidChangeBackingProperties, new scale = \(window!.backingScaleFactor)")
lineChart.contentsScale = window!.backingScaleFactor
}
// Mark: Mouse Tracking
override func updateTrackingAreas() {
if trackingArea != nil {
removeTrackingArea(trackingArea)
}
// only track the mouse inside the actual graph, not when over the axis labels or legend e.g.
let trackingRect = CGRect(x: lineChart.graphInsets.left, y: lineChart.graphInsets.bottom, width: bounds.width - lineChart.graphInsets.left - lineChart.graphInsets.right, height: bounds.height - lineChart.graphInsets.bottom - lineChart.graphInsets.top)
trackingArea = NSTrackingArea(rect: trackingRect, options: [NSTrackingAreaOptions.ActiveAlways, NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.MouseMoved], owner: self, userInfo: nil)
addTrackingArea(trackingArea)
}
override func mouseEntered(theEvent: NSEvent) {
//println("mouseEntered")
}
override func mouseExited(theEvent: NSEvent) {
if popoverPoint != nil {
popoverPoint!.highlighted = false // un-highlight the previously highlighted point
popoverPoint = nil
}
if popover.shown {
popover.close()
}
}
override func mouseMoved(theEvent: NSEvent) {
//var mouseLocation = convertPoint(theEvent.locationInWindow, fromView: nil)
let mouseLocation = lineChart.convertPoint(theEvent.locationInWindow, toLayer: lineChart.datasets.first)
if let point = lineChart.closestPointTo(mouseLocation) {
if popoverPoint == nil || popoverPoint! != point {
if popoverPoint != nil {
popoverPoint!.highlighted = false // un-highlight the previously highlighted point
}
popoverPoint = point
popover.contentViewController!.representedObject = point
point.highlighted = true
popover.contentSize = NSSize(width: 75.0, height: 45.0)
let rect = CGRect(origin: lineChart.convertPoint(point.position, fromLayer: lineChart.datasets.first), size: CGSize(width: 1.0, height: 1.0))
popover.showRelativeToRect(rect, ofView: self, preferredEdge: NSRectEdge.MaxY)
popover.contentViewController!.view.window!.ignoresMouseEvents = true // to prevent mouseExited from triggering when mouse over popover
}
}
}
}
class SimpleLineChartTooltop : NSViewController {
// a very simple tooltip view controller to be presented by popover controller
let lineLabel = NSTextField(frame: CGRect(x: 0.0, y: 20.0, width: 75.0, height: 20.0))
let valueLabel = NSTextField(frame: CGRect(x: 0.0, y: 0.0, width: 75.0, height: 20.0))
/*var point: LineChart.Point? {
didSet {
valueLabel.stringValue = point == nil ? "" : point!.value.shortFormatted
lineLabel.stringValue = point == nil || point!.line == nil ? "" : point!.line!.label
}
}*/
override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.view = NSView(frame: CGRect(x: 0.0, y: 0.0, width: 75.00, height: 45.0))
for label in [lineLabel, valueLabel] {
label.editable = false
label.selectable = false
label.bordered = false
label.alignment = NSTextAlignment.Center
label.backgroundColor = NSColor.clearColor()
view.addSubview(label)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var representedObject: AnyObject? {
didSet {
if let point = representedObject as? LineChart.Point {
if point.IndiceLabel == "%" {
valueLabel.stringValue = "\(ConvertPercentage(Float(point.value)))" + " \(point.IndiceLabel)"
lineLabel.stringValue = point.PopLabel
} else {
valueLabel.stringValue = "\(rounder(point.value))" + " \(point.IndiceLabel)"
lineLabel.stringValue = point.PopLabel
}
}
}
}
}
class LineChart: CALayer {
let defaultColors = [0x1f77b4, 0xff7f0e, 0x2ca02c, 0xd62728, 0x9467bd, 0x8c564b, 0xe377c2, 0x7f7f7f, 0xbcbd22, 0x17becf].map { CGColorCreateFromHex($0) }
var datasets: [Dataset] = [Dataset]() {
didSet {
for dataset in oldValue {
dataset.removeFromSuperlayer()
dataset.legendElement.removeFromSuperlayer()
}
for dataset in datasets {
if dataset.xAxis == nil {
dataset.xAxis = xAxis
}
if dataset.yAxis == nil {
dataset.yAxis = self.yAxes.first!
}
if !yAxes.contains(dataset.yAxis) {
yAxes += [dataset.yAxis]
}
if dataset.strokeColor == nil {
let colorIndex = (datasets.count - 1) % 5
dataset.color = defaultColors[colorIndex]
}
dataset.delegate = self
addSublayer(dataset)
legend.addSublayer(dataset.legendElement)
}
updateXAxis()
updateLegend()
}
}
private(set) var xAxis: Axis = Axis(alignment: .Right, transform: CATransform3DMakeRotation(CGFloat(M_PI) / -2.0, 0.0, 0.0, 1.0))
var yAxes: [Axis] = [Axis(alignment: .Left)] {
didSet {
for axis in oldValue {
axis.removeFromSuperlayer()
}
for axis in yAxes {
axis.delegate = self
addSublayer(axis)
}
}
}
var graphInsets: (left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) = (0.0, 0.0, 0.0, 0.0) {
didSet {
//println("Graph insets did set")
}
}
var title: CATextLayer = CATextLayer(autoScale: true)
var legend = CALayer()
var legendEnabled: Bool = false {
didSet {
if legendEnabled {
graphInsets.top = 60.0 // todo: calculate this value
addSublayer(legend)
} else {
graphInsets.top = 10.0
legend.removeFromSuperlayer()
}
}
}
var animationDurations = CATransaction.animationDuration() // can't call it "animationDuration" or swift compile error - no idea why
var animationTimingFunction = CATransaction.animationTimingFunction()
/*override init!(layer: AnyObject!) {
super.init(layer: layer)
}*/
override init() {
super.init()
postInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
postInit()
}
override init(layer: AnyObject) {
super.init(layer: layer)
}
func postInit() {
geometryFlipped = true
delegate = self
legend.delegate = self
xAxis.delegate = self
// addSublayer(xAxis)
//here
yAxes.first!.delegate = self
// addSublayer(yAxes.first!) // here
legendEnabled = true
}
func updateXAxis() {
// X-Axis
let minXTickValue: CGFloat = 0.0 // x-axis always starts at zero
let maxXTickValue = CGFloat( datasets.reduce(0, combine: {$0 > $1.data.count ? $0 : $1.data.count }) - 1 )
xAxis.range = (minXTickValue, maxXTickValue, interval: 1.0)
xAxis.size = CGSize(width: 40.0, height: 0.0)
graphInsets.bottom = xAxis.size.width
}
func updateLegend() {
//legend.sublayers = nil
var lastLegendElementOrigin = CGPointZero
for dataset in datasets {
//legend.addSublayer(legendEl)
dataset.legendElement.frame = CGRect(origin: lastLegendElementOrigin, size:dataset.legendElement.frame.size)
lastLegendElementOrigin = CGPoint(x: lastLegendElementOrigin.x + dataset.legendElement.frame.width + 20.0, y: 0.0)
}
legend.bounds = CGRect(origin: CGPointZero, size: CGSize(width: lastLegendElementOrigin.x, height: 20.0))
}
override func layoutSublayers() {
if datasets.count == 0 {
return
}
// 1) Estimate Y-axis widths so we know graph width
let estimatedYAxisWidths = 50.0 * CGFloat(yAxes.count)
// 2) Knowing graph width, figure out X-axis height
let maxTickLabelWidth: CGFloat = xAxis.ticks.reduce(0.0, combine: { max($0, $1.labelLayer.bounds.width) })
let tickIntervalWidth = (bounds.width - estimatedYAxisWidths) / CGFloat(xAxis.ticks.count)
if maxTickLabelWidth > tickIntervalWidth {
// we need to rotate x-axis tick labels so they are not overlapping
xAxis.labelRotation = -acos(tickIntervalWidth * 0.9 / maxTickLabelWidth)
} else {
xAxis.labelRotation = 0.0
}
let maxTickLabelHeight: CGFloat = xAxis.ticks.reduce(0.0, combine: { max($0, $1.labelLayer.frame.width) })
xAxis.size = CGSize(width: 12.0 + maxTickLabelHeight + 16.0, height: 0.0)
graphInsets.bottom = xAxis.size.width
graphInsets.right = (xAxis.ticks.last!.labelLayer.frame.height / 2.0) + 8.0 // half the label will stick out a bit on the right, so leave a little room
// 3) Knowing x-axis height and title, we know graph height and can figure out a "nice" amount of y-axis ticks
graphInsets.left = 0.0
for yAxis in yAxes {
let datasetsForAxis = datasets.filter { $0.yAxis == yAxis }
// figure out how many Y-Axis tick marks look best and at what interval
let minYValue = datasetsForAxis.reduce(CGFloat.max, combine: { min($0, ($1.data).minElement()!) })
let maxYValue = datasetsForAxis.reduce(CGFloat.min, combine: { max($0, ($1.data).maxElement()!) })
let yTickInterval = yAxis.optimalInterval(minYValue, max: maxYValue)
var minYTickValue = minYValue - (yTickInterval / 4.0) // we want the bottom of graph to be at least quarter-step below minY
minYTickValue = floor(minYTickValue / yTickInterval) * yTickInterval
if minYValue > 0.0 && minYTickValue < 0.0 {
minYTickValue = 0.0 // silly to show negative numbers when all numbers are positive
}
var maxYTickValue = maxYValue + (yTickInterval / 4.0) // we want the bottom of graph to be at least quarter-step below minY
maxYTickValue = ceil(maxYTickValue / yTickInterval) * yTickInterval
yAxis.range = (minYTickValue, maxYTickValue, yTickInterval)
let maxTickWidth: CGFloat = yAxis.ticks.reduce(0.0, combine: { max($0, $1.width) })
let axisWidth = maxTickWidth + 16.0
yAxis.size = CGSize(width: axisWidth, height: bounds.height - graphInsets.top - graphInsets.bottom)
if yAxis.alignment == .Left {
graphInsets.left += yAxis.size.width
} else {
graphInsets.right += yAxis.size.width
yAxis.position = CGPoint(x: bounds.width - graphInsets.left - graphInsets.right, y: 0.0)
}
}
// yAxes.first!.showGrid(bounds.width - graphInsets.left - graphInsets.right)
//Here
// 4) Knowing the exact y-axes widths, we can layout the x-axis
xAxis.size = CGSize(width: xAxis.bounds.height, height: bounds.width - graphInsets.left - graphInsets.right)
// xAxis.layoutSublayers()
//here
//xAxis.gridWidth = bounds.height - graphInsets.top - graphInsets.bottom
//xAxis.showGrid(bounds.height - graphInsets.top - graphInsets.bottom)
// 5) Configure layer so coordinate system starts in lower left with (0,0) pixel point at origin of graph
sublayerTransform = CATransform3DMakeAffineTransform(CGAffineTransformMakeTranslation(graphInsets.left, graphInsets.bottom))
// 6) Update legend position
legend.position = CGPoint(x: self.bounds.width - graphInsets.left - legend.bounds.width, y: self.bounds.height - graphInsets.bottom - 40.0)
// 7) Refresh the individual datasets
for dataset in datasets {
dataset.layoutSublayers()
}
}
// Provide smooth animation for both path and position
override func actionForLayer(layer: CALayer, forKey event: String) -> CAAction? {
if event == "path" || event == "position" {
let animation = CABasicAnimation(keyPath: event)
animation.duration = animationDurations
animation.timingFunction = animationTimingFunction
return animation
}
return nil
}
#if os(OSX)
override func layer(layer: CALayer, shouldInheritContentsScale newScale: CGFloat, fromWindow window: NSWindow) -> Bool {
return true
}
#endif
}
// Mark: Other Classes
extension LineChart {
enum Alignment { case Left, Right}
class Axis : CALayer {
var label: String?
var ticks: [Tick] = [Tick]()
var size: CGSize!
var gridWidth: CGFloat?
var alignment: Alignment
var axisLine = CAShapeLayer()
var labels: [String]?
var labelRotation: CGFloat = 0.0 {
didSet {
var correctedRotation = labelRotation
if let axisRotation = valueForKeyPath("transform.rotation.z") as? CGFloat {
// if the axis has been rotated, we need to rotate the text so it's right-side up
correctedRotation -= axisRotation
}
for tick in ticks {
let transform = CATransform3DIdentity
tick.labelLayer.transform = CATransform3DRotate(transform, correctedRotation, 0.0, 0.0, 1.0)
tick.updateLabelPosition()
}
}
}
var range: (min: CGFloat, max: CGFloat, interval: CGFloat?)! {
didSet {
if range.interval == nil {
range.interval = 1.0
}
for tick in ticks {
tick.removeFromSuperlayer()
}
let extra = range.interval! / 2.0 // // the "extra" craziness is to make sure the final condition evaluates as true if float values are very, very close but not equal (i.e. sometimes 1.0 != 1.0)
var newTicks = [Tick]()
var index = 0
for var value = range.min; value <= range.max + extra; value += range.interval!, index++ {
let tick = index < ticks.count ? ticks[index] : Tick(value: value, alignment: alignment, major: true)
tick.delegate = delegate
tick.value = value
if labels != nil && index < labels!.count {
tick.label = labels![index]
}
addSublayer(tick)
newTicks += [tick]
}
ticks = newTicks
}
}
override weak var delegate: AnyObject? {
didSet { axisLine.delegate = delegate! }
}
init(alignment: Alignment = .Left, transform: CATransform3D = CATransform3DIdentity) {
self.alignment = alignment
super.init()
self.transform = transform
axisLine.strokeColor = CGColorCreateCopyWithAlpha(CGColorCreateFromHex(0x000000), 0.4)
addSublayer(axisLine)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: AnyObject) {
self.alignment = .Left
super.init(layer: layer)
}
override func layoutSublayers() {
if size == nil {
return
}
axisLine.path = CGPath.Dataset(CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: size.height))
let scaleFactor = size.height / (range.max - range.min)
for tick in ticks {
let y = (tick.value - range.min) * scaleFactor
tick.position = CGPoint(x: 0.0, y: y)
}
}
func optimalInterval(min: CGFloat, max: CGFloat) -> CGFloat {
let maxInterval: CGFloat = 15.0 // todo: calc based on label font height
let minInterval = (max - min) / 0.9 / maxInterval // if we used the max amount of steps, each step would have represent at least this many units
// divide by 0.9 because we want all the data points to only take up ~90% of the available vertical space. the leftover is to provide some extra space below the min point and above the max point
let magnitude = pow(10.0, round( log10(minInterval) ))
// in order for the ticks to be "pretty" or intuitive, make them in multiples of either (100, 10, 1, .1, etc) or (50, 5, .5, .05) or (20, 2, .2, .02, etc)
var stepBase: CGFloat = 0.0
if minInterval <= 1.0 * magnitude {
stepBase = 1.0
} else if minInterval <= 2.0 * magnitude {
stepBase = 2.0
} else {
stepBase = 5.0
}
return stepBase * magnitude
}
func showGrid(width: CGFloat) {
for tick in ticks {
if tick.major {
let xStart = alignment == .Left ? -6.0 : 6.0
let xEnd = alignment == .Left ? width : -width
tick.lineLayer.path = CGPath.Dataset(CGPoint(x: xStart, y: 0), end: CGPoint(x: xEnd, y: 0))
}
}
}
}
class Tick : CALayer {
var major = true
var alignment: Alignment!
var labelLayer = CATextLayer(autoScale: true)
var lineLayer = CAShapeLayer()
var width: CGFloat { return 12.0 + labelLayer.frame.size.width }
var value: CGFloat! {
didSet { label = value.shortFormatted }
}
let labelSpacing: CGFloat = 12.0
var label: String {
get { return labelLayer.string as! String }
set {
labelLayer.string = newValue
labelLayer.sizeToFit()
updateLabelPosition()
}
}
override weak var delegate: AnyObject? {
didSet {
labelLayer.delegate = delegate // so it can get contentsScale
}
}
func updateLabelPosition() {
if alignment == .Left {
labelLayer.position = CGPoint(x: -labelSpacing - (labelLayer.frame.width / 2.0), y: 0.0)
labelLayer.alignmentMode = kCAAlignmentRight
} else {
labelLayer.position = CGPoint(x: labelSpacing + (labelLayer.frame.width / 2.0), y: 0.0)
labelLayer.alignmentMode = kCAAlignmentLeft
}
}
init(value: CGFloat, alignment: Alignment, major: Bool) {
self.value = value
self.alignment = alignment
self.major = major
super.init()
// Tick / Grid
var xStart: CGFloat
var xEnd: CGFloat
if major {
xStart = alignment == .Left ? -6.0 : 6.0
xEnd = alignment == .Left ? 6.0 : -6.0
} else {
xStart = -3.0
xEnd = 3.0
}
lineLayer.path = CGPath.Dataset(CGPoint(x: xStart, y: 0), end: CGPoint(x: xEnd, y: 0))
lineLayer.strokeColor = CGColorCreateCopyWithAlpha(CGColorCreateFromHex(0x000000), 0.2)
addSublayer(lineLayer)
// Label
labelLayer.fontSize = 12.0
labelLayer.foregroundColor = CGColorCreateFromHex(0x444444)
addSublayer(labelLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: AnyObject) {
super.init(layer: layer)
}
}
enum Curve {
case Bezier(CGFloat)
}
class Dataset : CAShapeLayer {
var xAxis: Axis!
var yAxis: Axis!
var label = ""
var PopLabels = [String]?()
var indice = String()
var data: [CGFloat] = [CGFloat]() {
didSet {
updatePoints()
if let delegate = delegate as? LineChart {
delegate.updateXAxis()
delegate.setNeedsLayout()
}
}
}
private let fillLayer = CAShapeLayer()
var curve: Curve?
let defaultPoint = CAShapeLayer()
var points = [Point]()
override weak var delegate: AnyObject? {
didSet {
legendLabel.delegate = delegate
fillLayer.delegate = delegate
for point in points { point.delegate = delegate }
}
}
lazy var legendMarker: CAShapeLayer = {
let legendMarker = CAShapeLayer()
legendMarker.path = CGPath.Rect(CGRect(x: 0.0, y: 0.0, width: 20.0, height: 15.0))
legendMarker.fillColor = self.strokeColor
return legendMarker
}()
lazy var legendLabel: CATextLayer = {
let legendLabel = CATextLayer(autoScale: true)
//legendLabel.contentsScale = UIScreen.mainScreen().scale
legendLabel.fontSize = 12.0
legendLabel.string = self.label
legendLabel.foregroundColor = CGColorCreateFromHex(0x000000)
legendLabel.position = CGPoint(x: 14.0, y:0.0)
legendLabel.alignmentMode = kCAAlignmentLeft
legendLabel.sizeToFit()
legendLabel.frame = CGRect(origin: CGPoint(x: 28.0, y: 0.0), size: legendLabel.frame.size)
return legendLabel
}()
lazy var legendElement: CALayer = {
let legendEl = CALayer()
legendEl.addSublayer(self.legendMarker)
legendEl.frame = CGRect(origin: CGPointZero, size: CGSize(width: self.legendLabel.frame.origin.x + self.legendLabel.frame.width, height: 15.0))
legendEl.addSublayer(self.legendLabel)
return legendEl
}()
override var path: CGPath? {
didSet {
let fillPath = CGPathCreateMutable()
// We need to use this special ordering of points so the animated transition/morphing looks correct
let lastPoint = CGPathGetCurrentPoint(path)
let start = oldValue != nil ? CGPathGetCurrentPoint(oldValue) : lastPoint
CGPathMoveToPoint(fillPath, nil, start.x, 0)
CGPathAddLineToPoint(fillPath, nil, 0, 0)
CGPathAddLineToPoint(fillPath, nil, points.first!.position.x, points.first!.position.y)
CGPathAddPath(fillPath, nil, path)
CGPathAddLineToPoint(fillPath, nil, lastPoint.x, lastPoint.y) // duplicate point important
CGPathAddLineToPoint(fillPath, nil, lastPoint.x, 0)
CGPathAddLineToPoint(fillPath, nil, start.x, 0)
CGPathCloseSubpath(fillPath)
fillLayer.path = fillPath
}
}
override var fillColor: CGColorRef? {
get { return nil }
set {
super.fillColor = nil
fillLayer.fillColor = newValue
}
}
convenience init(label: String, data: [CGFloat], yAxis: Axis, poplabelfrominit: [String], indice: String) {
self.init(label: label, data: data, poplabelfrominit: poplabelfrominit, indice: indice)
self.yAxis = yAxis
}
init(label: String, data: [CGFloat], poplabelfrominit: [String], indice: String) {
self.label = label
self.data = data
self.PopLabels = poplabelfrominit
self.indice = indice
defaultPoint.path = CGPath.Circle(10.0)
defaultPoint.strokeColor = CGColorCreateFromHex(0xFFFFFF)
super.init()
updatePoints()
lineWidth = 2.0
defaultPoint.addObserver(self, forKeyPath: "strokeColor", options: NSKeyValueObservingOptions(), context: nil)
defaultPoint.addObserver(self, forKeyPath: "fillColor", options: NSKeyValueObservingOptions(), context: nil)
defaultPoint.addObserver(self, forKeyPath: "path", options: NSKeyValueObservingOptions(), context: nil)
addSublayer(fillLayer)
//updatePoints();
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
for point in points {
point.setValue(defaultPoint.valueForKeyPath(keyPath!), forKeyPath: keyPath!)
}
}
deinit{
defaultPoint.removeObserver(self, forKeyPath: "strokeColor")
defaultPoint.removeObserver(self, forKeyPath: "fillColor")
defaultPoint.removeObserver(self, forKeyPath: "path")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(layer: AnyObject) {
super.init(layer: layer)
}
func updatePoints() {
for point in points {
point.removeFromSuperlayer()
}
var newPoints = [Point]()
for var i = 0; i < data.count; i++ {
let point = i < points.count ? points[i] : Point(layer: defaultPoint)
point.dataset = self
point.delegate = delegate
point.value = data[i]
point.PopLabel = PopLabels![i]
point.IndiceLabel = indice
point.highlighted = false
addSublayer(point)
newPoints += [point]
}
points = newPoints
}
var color: CGColorRef! {
get { return strokeColor }
set {
strokeColor = newValue
fillColor = CGColorCreateCopyWithAlpha(newValue, 0.3)
defaultPoint.fillColor = newValue
legendMarker.fillColor = newValue
}
}
override func layoutSublayers() {
var x: CGFloat = 0
let yScaleFactor = yAxis.size.height / (yAxis.range.max - yAxis.range.min)
let xIntervalWidth = xAxis.size.height / (xAxis.range.max - xAxis.range.min)
for point in points {
let y = (point.value - yAxis.range.min) * yScaleFactor
point.position = CGPoint(x: x, y: y)
x += xIntervalWidth
}
let positions = points.map { $0.position }
if curve != nil {
switch curve! {
case .Bezier(let tension):
path = CGPath.SplineCurve(positions, tension: tension)
}
} else {
path = CGPath.Polyline(positions)
}
}
}
class Point : CAShapeLayer {
var value: CGFloat!
var PopLabel : String!
weak var dataset: Dataset?
var IndiceLabel : String!
override init(layer: AnyObject) {
super.init(layer: layer)
path = layer.path
strokeColor = layer.strokeColor
fillColor = layer.fillColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var highlighted: Bool = false {
didSet {
if highlighted {
transform = CATransform3DMakeAffineTransform( CGAffineTransformMakeScale(2.0, 2.0) )
} else {
transform = CATransform3DMakeAffineTransform( CGAffineTransformMakeScale(1.0, 1.0) )
}
}
}
}
}
// Mark: User Interaction
extension LineChart {
func closestPointTo(refPoint: CGPoint) -> Point? {
var min: (point: Point, xDist: CGFloat, yDist: CGFloat)?
for dataset in datasets {
for point in dataset.points {
// Values -220 and + 30 are completely arbitrary and depend on the chart's view size. Not sure what to do about that besides hard coding them
let xDist = abs(refPoint.x - point.position.x - 220)
let yDist = abs(refPoint.y - point.position.y + 30)
if min == nil || xDist < min!.xDist || (xDist == min!.xDist && yDist < min!.yDist) {
min = (point, xDist, yDist)
}
}
}
return (min == nil) ? nil : min!.point
}
}
// Mark: Helpers
func CGColorCreateFromHex(rgb: UInt) -> CGColor {
return CGColorCreate(CGColorSpaceCreateDeviceRGB(), [CGFloat((rgb & 0xFF0000) >> 16) / 255.0, CGFloat((rgb & 0x00FF00) >> 8) / 255.0, CGFloat(rgb & 0x0000FF) / 255.0, 1.0])!
}
extension CGFloat {
var shortFormatted: String {
if self == 0.0 {
return "0"
}
let exponent = floor(log10(self))
let formatter = NSNumberFormatter()
// let prefixes = [3:"k", 6:"M"]
if exponent > 3 && exponent < 6 && self % 100 == 0 {
formatter.maximumSignificantDigits = 3
return formatter.stringFromNumber(self / 1000)! + "k"
} else if exponent >= 6 && exponent < 9 && self % 100000 == 0 {
formatter.maximumSignificantDigits = 3
return formatter.stringFromNumber(self / 1000000)! + "M"
}
if exponent > 4 || exponent < -4 {
formatter.numberStyle = NSNumberFormatterStyle.ScientificStyle
formatter.maximumSignificantDigits = 5
} else {
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
formatter.maximumSignificantDigits = 5
}
return formatter.stringFromNumber(self)!
}
}
extension CGPath {
class func Dataset(start: CGPoint, end: CGPoint) -> CGPath {
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, start.x, start.y)
CGPathAddLineToPoint(path, nil, end.x, end.y)
return CGPathCreateCopy(path)!
}
class func Polyline(points:[CGPoint]) -> CGPath {
let path = CGPathCreateMutable()
for point in points {
if point == points.first {
CGPathMoveToPoint(path, nil, point.x, point.y)
} else {
CGPathAddLineToPoint(path, nil, point.x, point.y)
}
}
return path
}
class func Circle(radius: CGFloat) -> CGPath {
return CGPathCreateWithEllipseInRect(CGRect(x: (radius / -2.0), y: (radius / -2.0), width: radius, height: radius), nil)
}
class func Rect(rect: CGRect) -> CGPath {
return CGPathCreateWithRect(rect, nil)
}
class func SplineCurve(points: [CGPoint], tension: CGFloat = 0.3, minY: CGFloat = CGFloat.min, maxY: CGFloat = CGFloat.max) -> CGPath {
func controlPoints(t: CGPoint, i: CGPoint, e: CGPoint, s: CGFloat) -> (inner: CGPoint, outer: CGPoint) {
// adapted from chart.js helper library
// calculates the control points for bezier curve for a dataset
let n = sqrt(pow(i.x - t.x, 2) + pow(i.y - t.y, 2));
let o = sqrt(pow(e.x - i.x, 2) + pow(e.y - i.y, 2))
let a = s * n / (n + o)
let h = s * o / (n + o)
let inner = CGPoint(x: i.x - a * (e.x - t.x), y: i.y - a * (e.y - t.y))
let outer = CGPoint(x: i.x + h * (e.x - t.x), y: i.y + h * (e.y - t.y))
return (inner, outer)
}
let path = CGPathCreateMutable()
var prevControlPoints: (inner: CGPoint, outer: CGPoint)?
for var i = 0; i < points.count; i++ {
let point = points[i]
// bezier curve control point calculations
let pTension: CGFloat = i > 0 && i < points.count - 1 ? tension : 0.0
let prevPoint = i > 0 ? points[i-1] : CGPointZero
let nextPoint = i < points.count - 1 ? points[i+1] : CGPointZero
var controlPoints = controlPoints(prevPoint, i: point, e: nextPoint, s: pTension)
// if it doesn't make sense for data to ever go below or above a certain value, then we can cap it off
controlPoints = ( CGPoint(x: controlPoints.inner.x, y: max(min(controlPoints.inner.y, maxY), minY)),
CGPoint(x: controlPoints.outer.x, y: max(min(controlPoints.outer.y, maxY), minY)) )
if i == 0 {
CGPathMoveToPoint(path, nil, point.x, point.y)
} else {
CGPathAddCurveToPoint(path, nil, prevControlPoints!.outer.x, prevControlPoints!.outer.y, controlPoints.inner.x, controlPoints.inner.y, point.x, point.y)
}
prevControlPoints = controlPoints
}
return path
}
}
extension CGAffineTransform {
init(verticalFlipWithHeight height: CGFloat) {
let t = CGAffineTransformMakeScale(1.0, -1.0)
//CGAffineTransformTranslate(t, 0.0, -height)
self.init(a: t.a, b:t.b, c:t.c, d:t.d, tx:t.tx, ty:t.ty)
}
}
extension CATextLayer {
convenience init(autoScale: Bool) {
self.init()
if autoScale {
#if os(iOS)
contentsScale = UIScreen.mainScreen().scale
#else
contentsScale = NSScreen.mainScreen()!.backingScaleFactor
#endif
}
}
// Helper function - It's nice to have access to an NSAttributedString because you can use the attributedString.size property to determine the correct frame for the layer
var attributedString : NSAttributedString {
if let attString = string as? NSAttributedString {
return attString
} else if let string = string as? NSString {
var layerFont: CTFontRef?
if let fontName = font as? NSString {
//layerFont = UIFont(name: fontName, size: fontSize)
layerFont = CTFontCreateWithName(fontName, fontSize, nil);
} else {
let ftypeid = CFGetTypeID(font)
if ftypeid == CTFontGetTypeID() {
let fontName = CTFontCopyPostScriptName(font as! CTFont)
//layerFont = UIFont(name: fontName, size: fontSize)
layerFont = CTFontCreateWithName(fontName, fontSize, nil);
} else if ftypeid == CGFontGetTypeID() {
let fontName = CGFontCopyPostScriptName((font as! CGFont))
//layerFont = UIFont(name: fontName, size: fontSize)
layerFont = CTFontCreateWithName(fontName, fontSize, nil);
}
}
if layerFont == nil {
//layerFont = UIFont.systemFontOfSize(fontSize)
layerFont = CTFontCreateUIFontForLanguage(CTFontUIFontType.System, fontSize, nil)
}
//return NSAttributedString(string: string as NSString, attributes: [NSFontAttributeName: layerFont!])
return NSAttributedString(string: string as NSString as String, attributes: [kCTFontAttributeName as String: layerFont!])
} else {
return NSAttributedString(string: "")
}
}
func sizeToFit() {
#if os(iOS)
bounds = CGRect(origin: CGPointZero, size: self.attributedString.size())
#else
bounds = CGRect(origin: CGPointZero, size: self.attributedString.size())
#endif
}
} | mit | b27254fc01a4a0bede9d8324e4c1b0f6 | 39.879668 | 263 | 0.551603 | 4.935746 | false | false | false | false |
shyamalschandra/swix | swix_ios_app/swix_ios_app/swix/ndarray/simple-math.swift | 7 | 6155 | //
// oneD_math.swift
// swix
//
// Created by Scott Sievert on 6/11/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func apply_function(function: Double->Double, x: ndarray) -> ndarray{
// apply a function to every element.
// I've tried the below, but it doesn't apply the function to every element (at least in Xcode6b4)
//var function:Double->Double = sin
//var x = arange(N)*pi / N
//var y = zeros(x.count)
//dispatch_apply(UInt(N), dispatch_get_global_queue(0,0), {(i)->() in
// y[Int(i)] = function(x[Int(i)])
// })
var y = zeros(x.count)
for i in 0..<x.count{
y[i] = function(x[i])
}
return y
}
func apply_function(function: String, x: ndarray)->ndarray{
// apply select optimized functions
let y = zeros_like(x)
let n = x.n.length
var count = Int32(x.n)
if function=="abs"{
vDSP_vabsD(!x, 1, !y, 1, n);}
else if function=="sign"{
var o = CDouble(0)
var l = CDouble(1)
vDSP_vlimD(!x, 1.stride, &o, &l, !y, 1.stride, n)
}
else if function=="cumsum"{
var scalar:CDouble = 1
vDSP_vrsumD(!x, 1.stride, &scalar, !y, 1.stride, n)
}
else if function=="floor"{
vvfloor(!y, !x, &count)
}
else if function=="log10"{
assert(min(x) > 0, "log must be called with positive values")
vvlog10(!y, !x, &count)
}
else if function=="log2"{
assert(min(x) > 0, "log must be called with positive values")
vvlog2(!y, !x, &count)
}
else if function=="exp2"{
vvexp2(!y, !x, &count)
}
else if function=="log"{
assert(min(x) > 0, "log must be called with positive values")
vvlog(!y, !x, &count)
}
else if function=="exp"{
vvexp(!y, !x, &count)
}
else if function=="cos"{
vvcos(!y, !x, &count)
}
else if function=="sin"{
vvsin(!y, !x, &count)
}
else if function=="tan"{
vvtan(!y, !x, &count)
}
else if function=="expm1"{
vvexpm1(!y, !x, &count)
}
else if function=="round"{
vvnint(!y, !x, &count)
}
else if function=="ceil"{
vvceil(!y, !x, &count)
}
else if function == "tanh" {
vvtanh(!y, !x, &count)
}
else {assert(false, "Function not recongized")}
return y
}
// MIN/MAX
func min(x: ndarray) -> Double{
// finds the min
return x.min()}
func max(x: ndarray) -> Double{
// finds the max
return x.max()}
func max(x: ndarray, y:ndarray)->ndarray{
// finds the max of two arrays element wise
assert(x.n == y.n)
let z = zeros_like(x)
vDSP_vmaxD(!x, 1.stride, !y, 1.stride, !z, 1.stride, x.n.length)
return z
}
func min(x: ndarray, y:ndarray)->ndarray{
// finds the min of two arrays element wise
assert(x.n == y.n)
let z = zeros_like(x)
vDSP_vminD(!x, 1.stride, !y, 1.stride, !z, 1.stride, x.n.length)
return z
}
// BASIC STATS
func mean(x: ndarray) -> Double{
// finds the mean
return x.mean()
}
func std(x: ndarray) -> Double{
// standard deviation
return sqrt(variance(x))}
func variance(x: ndarray) -> Double{
// the varianace
return sum(pow(x - mean(x), power: 2) / x.count.double)}
// BASIC INFO
func sign(x: ndarray)->ndarray{
// finds the sign
return apply_function("sign", x: x)}
func sum(x: ndarray) -> Double{
// finds the sum of an array
var ret:CDouble = 0
vDSP_sveD(!x, 1.stride, &ret, x.n.length)
return Double(ret)
}
func remainder(x1:ndarray, x2:ndarray)->ndarray{
// finds the remainder
return (x1 - floor(x1 / x2) * x2)
}
func cumsum(x: ndarray) -> ndarray{
// the sum of each element before.
return apply_function("cumsum", x: x)}
func abs(x: ndarray) -> ndarray{
// absolute value
return apply_function("abs", x: x)}
func prod(x:ndarray)->Double{
var y = x.copy()
var factor = 1.0
if min(y) < 0{
y[argwhere(y < 0.0)] *= -1.0
if sum(x < 0) % 2 == 1 {factor = -1}
}
return factor * exp(sum(log(y)))
}
func cumprod(x:ndarray)->ndarray{
var y = x.copy()
if min(y) < 0.0{
let i = y < 0
y[argwhere(i)] *= -1.0
let j = 1 - (cumsum(i) % 2.0) < S2_THRESHOLD
var z = exp(cumsum(log(y)))
z[argwhere(j)] *= -1.0
return z
}
return exp(cumsum(log(y)))
}
// POWER FUNCTIONS
func pow(x:ndarray, power:Double)->ndarray{
// take the power. also callable with ^
let y = zeros_like(x)
CVWrapper.pow(!x, n:x.n.cint, power:power, into:!y)
return y
}
func pow(x:ndarray, y:ndarray)->ndarray{
// take the power. also callable with ^
let z = zeros_like(x)
var num = CInt(x.n)
vvpow(!z, !y, !x, &num)
return z
}
func pow(x:Double, y:ndarray)->ndarray{
// take the power. also callable with ^
let xx = ones(y.n) * x
return pow(xx, y: y)
}
func sqrt(x: ndarray) -> ndarray{
return x^0.5
}
func exp(x:ndarray)->ndarray{
return apply_function("exp", x: x)
}
func exp2(x:ndarray)->ndarray{
return apply_function("exp2", x: x)
}
func expm1(x:ndarray)->ndarray{
return apply_function("expm1", x: x)
}
// ROUND
func round(x:ndarray)->ndarray{
return apply_function("round", x: x)
}
func round(x:ndarray, decimals:Double)->ndarray{
let factor = pow(10, decimals)
return round(x*factor) / factor
}
func floor(x: ndarray) -> ndarray{
return apply_function("floor", x: x)
}
func ceil(x: ndarray) -> ndarray{
return apply_function("ceil", x: x)
}
// LOG
func log10(x:ndarray)->ndarray{
// log_10
return apply_function("log10", x: x)
}
func log2(x:ndarray)->ndarray{
// log_2
return apply_function("log2", x: x)
}
func log(x:ndarray)->ndarray{
// log_e
return apply_function("log", x: x)
}
// TRIG
func sin(x: ndarray) -> ndarray{
return apply_function("sin", x: x)
}
func cos(x: ndarray) -> ndarray{
return apply_function("cos", x: x)
}
func tan(x: ndarray) -> ndarray{
return apply_function("tan", x: x)
}
func tanh(x: ndarray) -> ndarray {
return apply_function("tanh", x: x)
}
| mit | 35c67b2fc4aeba13c9b05ad8cc3574f4 | 23.521912 | 102 | 0.57433 | 3.006839 | false | false | false | false |
uny/Reachability.swift | ReachabilitySample/ViewController.swift | 1 | 3012 | //
// ViewController.swift
// Reachability Sample
//
// Created by Ashley Mills on 22/09/2014.
// Copyright (c) 2014 Joylord Systems. All rights reserved.
//
import UIKit
import Reachability
let useClosures = false
class ViewController: UIViewController {
@IBOutlet weak var networkStatus: UILabel!
var reachability: Reachability?
override func viewDidLoad() {
super.viewDidLoad()
do {
let reachability = try Reachability.reachabilityForInternetConnection()
self.reachability = reachability
} catch ReachabilityError.FailedToCreateWithAddress(let address) {
networkStatus.textColor = UIColor.redColor()
networkStatus.text = "Unable to create\nReachability with address:\n\(address)"
return
} catch {}
if (useClosures) {
reachability?.whenReachable = { reachability in
self.updateLabelColourWhenReachable(reachability)
}
reachability?.whenUnreachable = { reachability in
self.updateLabelColourWhenNotReachable(reachability)
}
} else {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
}
do {
try reachability?.startNotifier()
} catch {
networkStatus.textColor = UIColor.redColor()
networkStatus.text = "Unable to start\nnotifier"
return
}
// Initial reachability check
if let reachability = reachability {
if reachability.isReachable() {
updateLabelColourWhenReachable(reachability)
} else {
updateLabelColourWhenNotReachable(reachability)
}
}
}
deinit {
reachability?.stopNotifier()
if (!useClosures) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
}
}
func updateLabelColourWhenReachable(reachability: Reachability) {
if reachability.isReachableViaWiFi() {
self.networkStatus.textColor = UIColor.greenColor()
} else {
self.networkStatus.textColor = UIColor.blueColor()
}
self.networkStatus.text = reachability.currentReachabilityString
}
func updateLabelColourWhenNotReachable(reachability: Reachability) {
self.networkStatus.textColor = UIColor.redColor()
self.networkStatus.text = reachability.currentReachabilityString
}
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
updateLabelColourWhenReachable(reachability)
} else {
updateLabelColourWhenNotReachable(reachability)
}
}
}
| bsd-2-clause | 657eea498bc57c640cf63c6b55930fb1 | 29.734694 | 161 | 0.628818 | 6.146939 | false | false | false | false |
TalkingBibles/TBMultiAppearanceButton | TBMultiAppearanceButtonPlayground.playground/Contents.swift | 1 | 1158 | //: Playground - noun: a place where people can play
import UIKit
import TBMultiAppearanceButton
enum PlayerButtonAppearance: Int, TBControlAppearanceType {
case Stop = 1
case Play = 2
case Pause = 3
}
let button = TBMultiAppearanceButton<PlayerButtonAppearance>(frame: CGRectMake(0, 0, 100, 100))
button.setTitle("Play", forAppearance: .Play, andState: .Normal)
button.setTitle("Play", forAppearance: .Play, andState: .Highlighted)
button.setBackgroundImage(UIImage.imageWithColor(UIColor.blueColor()), forAppearance: .Play, andState: .Normal)
button.setBackgroundImage(UIImage.imageWithColor(UIColor.lightGrayColor()), forAppearance: .Play, andState: .Highlighted)
button.setTitle("Pause", forAppearance: .Pause, andState: .Normal)
button.setTitleColor(UIColor.blueColor(), forAppearance: .Pause, andState: .Normal)
button.setBackgroundImage(UIImage.imageWithColor(UIColor.yellowColor()), forAppearance: .Pause, andState: .Normal)
button.setTitle("Stop", forAppearance: .Stop, andState: .Normal)
button.activateAppearance(.Play)
button
button.highlighted = true
button
button.highlighted = false
button.activateAppearance(.Pause)
button
| mit | 373ef1fc1a4897f221b31ecb63ed597b | 30.297297 | 121 | 0.787565 | 4.180505 | false | false | false | false |
LYM-mg/MGOFO | MGOFO/MGOFO/Class/Side(侧边栏)/Controller/AboutUsViewController.swift | 1 | 6489 | //
// AboutUsViewController.swift
// MGOFO
//
// Created by i-Techsys.com on 2017/5/11.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class AboutUsViewController: UIViewController {
// MARK: - 懒加载属性
fileprivate lazy var tableView: UITableView = { [unowned self] in
let tb = UITableView()
tb.backgroundColor = UIColor.clear
tb.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tb.dataSource = self
tb.delegate = self
tb.rowHeight = 40
tb.isScrollEnabled = false
tb.tableFooterView = UIView()
return tb
}()
fileprivate lazy var dataArr = [["title": "微信服务号","detail": "ofobike"],
["title": "ofo官网","detail": "www.ofo.so"],
["title": "商务合作","detail": "[email protected]"]]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "关于我们"
view.backgroundColor = UIColor(r: 246, g: 246, b: 246)
setUpMainView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - TableView数据源
extension AboutUsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "cellID")
}
cell?.textLabel?.textColor = UIColor(r: 152, g: 147, b: 130)
cell?.detailTextLabel?.textColor = UIColor(r: 152, g: 147, b: 130)
cell!.textLabel?.text = dataArr[indexPath.row]["title"]
cell!.detailTextLabel?.text = dataArr[indexPath.row]["detail"]
return cell!
}
}
// MARK: - TableView代理
extension AboutUsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
switch indexPath.row {
case 0:
// iOS 将内容复制到剪切板
let pasteboard = UIPasteboard.general
pasteboard.string = cell?.detailTextLabel?.text
self.showHint(hint: "已复制到剪贴板")
break
case 1:
self.show(WKWebViewController(navigationTitle: "关于ofo", urlStr: "http://m.ofo.so/index.html"), sender: nil)
case 2:
break
default:
break
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
cell.separatorInset = UIEdgeInsets.zero
}
if cell.responds(to:#selector(setter: UIView.layoutMargins)) {
cell.layoutMargins = UIEdgeInsets.zero
}
}
}
// MARK: - Navigation
extension AboutUsViewController {
// MARK: setUpMainView
fileprivate func setUpMainView() {
self.automaticallyAdjustsScrollViewInsets = false
if tableView.responds(to:#selector(setter: UITableViewCell.separatorInset)) {
tableView.separatorInset = UIEdgeInsets.zero
}
if tableView.responds(to:#selector(setter: UIView.layoutMargins)) {
tableView.layoutMargins = UIEdgeInsets.zero
}
/// 顶部
let topView = UIView()
topView.backgroundColor = UIColor.white
let imageV = UIImageView(image: #imageLiteral(resourceName: "icon_60x60_"))
let descripLabel = UILabel()
descripLabel.numberOfLines = 0
descripLabel.textColor = UIColor(r: 152, g: 147, b: 130)
descripLabel.text = "ofo 共享单车是全球第一个无桩共享单车出行平台,首创\"单车共享\"模式,用户只需在微信服务号或App输入车牌号,即可获得密码解锁用车,随取随用,随时随地。"
descripLabel.sizeToFit()
topView.addSubview(imageV)
topView.addSubview(descripLabel)
/// 底部
let bottomView = UIView()
let versionLabel = UILabel()
versionLabel.textColor = UIColor(r: 221, g: 194, b: 190)
versionLabel.font = UIFont.systemFont(ofSize: 14)
versionLabel.text = "当前版本:V\(Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String)"
let copyrightLabel = UILabel()
copyrightLabel.textColor = UIColor(r: 221, g: 194, b: 190)
copyrightLabel.font = UIFont.systemFont(ofSize: 13)
copyrightLabel.text = "2017 ofo.so all rights reaerved"
bottomView.addSubview(versionLabel)
bottomView.addSubview(copyrightLabel)
view.addSubview(topView)
view.addSubview(tableView)
view.addSubview(bottomView)
/// 布局
topView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(navHeight)
make.left.right.equalToSuperview()
make.bottom.equalTo(descripLabel).offset(10)
}
imageV.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalToSuperview().offset(20)
make.height.width.equalTo(60)
}
descripLabel.snp.makeConstraints { (make) in
make.top.equalTo(imageV.snp.bottom).offset(20)
make.left.equalToSuperview().offset(15)
make.right.equalToSuperview().offset(-15)
}
tableView.snp.makeConstraints { (make) in
make.top.equalTo(topView.snp.bottom).offset(10)
make.left.right.bottom.equalToSuperview()
}
bottomView.snp.makeConstraints { (make) in
make.bottom.left.right.equalToSuperview()
make.height.equalTo(50)
}
versionLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalToSuperview().offset(10)
}
copyrightLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(versionLabel.snp.bottom)
}
}
}
| mit | d0f793ac15d894f2cb9e1f2757594e98 | 35.502924 | 123 | 0.611343 | 4.651267 | false | false | false | false |
laonayt/NewFreshBeen-Swift | WEFreshBeen/Classes/Base/Common/SwiftDictModel.swift | 1 | 8203 | //
// SwiftDictModel.swift
// Created by 维尼的小熊 on 16/1/12.
// Copyright © 2016年 tianzhongtao. All rights reserved.
// GitHub地址:https://github.com/ZhongTaoTian/LoveFreshBeen
// Blog讲解地址:http://www.jianshu.com/p/879f58fe3542
// 小熊的新浪微博:http://weibo.com/5622363113/profile?topnav=1&wvr=6
import Foundation
@objc public protocol DictModelProtocol {
static func customClassMapping() -> [String: String]?
}
/// 字典转模型管理器
public class DictModelManager {
private static let instance = DictModelManager()
/// 全局统一访问入口
public class var sharedManager: DictModelManager {
return instance
}
/// 字典转模型
/// - parameter dict: 数据字典
/// - parameter cls: 模型类
///
/// - returns: 模型对象
public func objectWithDictionary(dict: NSDictionary, cls: AnyClass) -> AnyObject? {
// 动态获取命名空间
let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
// 模型信息
let infoDict = fullModelInfo(cls)
let obj: AnyObject = (cls as! NSObject.Type).init()
autoreleasepool {
// 3. 遍历模型字典
for (k, v) in infoDict {
if k == "desc" {
let newValue = dict["description"] as? String
obj.setValue(newValue, forKey: "desc")
}
if let value: AnyObject = dict[k] {
if v.isEmpty {
if !(value === NSNull()) {
if k == "number" && ScreenWidth < 375 {
if let vav: String = value as? String {
obj.setValue(Int(vav)!, forKey: k)
}
} else {
obj.setValue(value, forKey: k)
}
}
} else {
let type = "\(value.classForCoder)"
if type == "NSDictionary" {
if let subObj: AnyObject = objectWithDictionary(value as! NSDictionary, cls: NSClassFromString(ns + "." + v)!) {
obj.setValue(subObj, forKey: k)
}
} else if type == "NSArray" {
if let subObj: AnyObject = objectsWithArray(value as! NSArray, cls: NSClassFromString(ns + "." + v)!) {
obj.setValue(subObj, forKey: k)
}
}
}
}
}
}
return obj
}
/// 创建自定义对象数组
///
/// - parameter NSArray: 字典数组
/// - parameter cls: 模型类
///
/// - returns: 模型数组
public func objectsWithArray(array: NSArray, cls: AnyClass) -> NSArray? {
var list = [AnyObject]()
autoreleasepool { () -> () in
for value in array {
let type = "\(value.classForCoder)"
if type == "NSDictionary" {
if let subObj: AnyObject = objectWithDictionary(value as! NSDictionary, cls: cls) {
list.append(subObj)
}
} else if type == "NSArray" {
if let subObj: AnyObject = objectsWithArray(value as! NSArray, cls: cls) {
list.append(subObj)
}
}
}
}
if list.count > 0 {
return list
} else {
return nil
}
}
/// 模型转字典
///
/// - parameter obj: 模型对象
///
/// - returns: 字典信息
public func objectDictionary(obj: AnyObject) -> [String: AnyObject]? {
// 1. 取出对象模型字典
let infoDict = fullModelInfo(obj.classForCoder)
var result = [String: AnyObject]()
// 2. 遍历字典
for (k, v) in infoDict {
var value: AnyObject? = obj.valueForKey(k)
if value == nil {
value = NSNull()
}
if v.isEmpty || value === NSNull() {
result[k] = value
} else {
let type = "\(value!.classForCoder)"
var subValue: AnyObject?
if type == "NSArray" {
subValue = objectArray(value! as! [AnyObject])
} else {
subValue = objectDictionary(value!)
}
if subValue == nil {
subValue = NSNull()
}
result[k] = subValue
}
}
if result.count > 0 {
return result
} else {
return nil
}
}
/// 模型数组转字典数组
///
/// - parameter array: 模型数组
///
/// - returns: 字典数组
public func objectArray(array: [AnyObject]) -> [AnyObject]? {
var result = [AnyObject]()
for value in array {
let type = "\(value.classForCoder)"
var subValue: AnyObject?
if type == "NSArray" {
subValue = objectArray(value as! [AnyObject])
} else {
subValue = objectDictionary(value)
}
if subValue != nil {
result.append(subValue!)
}
}
if result.count > 0 {
return result
} else {
return nil
}
}
// MARK: - 私有函数
/// 加载完整类信息
///
/// - parameter cls: 模型类
///
/// - returns: 模型类完整信息
func fullModelInfo(cls: AnyClass) -> [String: String] {
// 检测缓冲池
if let cache = modelCache["\(cls)"] {
return cache
}
var currentCls: AnyClass = cls
var infoDict = [String: String]()
while let parent: AnyClass = currentCls.superclass() {
infoDict.merge(modelInfo(currentCls))
currentCls = parent
}
// 写入缓冲池
modelCache["\(cls)"] = infoDict
return infoDict
}
/// 加载类信息
///
/// - parameter cls: 模型类
///
/// - returns: 模型类信息
func modelInfo(cls: AnyClass) -> [String: String] {
// 检测缓冲池
if let cache = modelCache["\(cls)"] {
return cache
}
// 拷贝属性列表
var count: UInt32 = 0
let properties = class_copyPropertyList(cls, &count)
// 检查类是否实现了协议
var mappingDict: [String: String]?
if cls.respondsToSelector("customClassMapping") {
mappingDict = cls.customClassMapping()
}
var infoDict = [String: String]()
for i in 0..<count {
let property = properties[Int(i)]
// 属性名称
let cname = property_getName(property)
let name = String.fromCString(cname)!
let type = mappingDict?[name] ?? ""
infoDict[name] = type
}
free(properties)
// 写入缓冲池
modelCache["\(cls)"] = infoDict
return infoDict
}
/// 模型缓冲,[类名: 模型信息字典]
var modelCache = [String: [String: String]]()
}
extension Dictionary {
/// 将字典合并到当前字典
mutating func merge<K, V>(dict: [K: V]) {
for (k, v) in dict {
self.updateValue(v as! Value, forKey: k as! Key)
}
}
}
| apache-2.0 | 242375b6f6015db08bdf7acec61ece63 | 27.902985 | 140 | 0.43403 | 4.943204 | false | false | false | false |
CosmicMind/Motion | Sources/Transition/MotionTransition+Interactive.swift | 3 | 3730 | /*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
public extension MotionTransition {
/**
Updates the elapsed time for the interactive transition.
- Parameter progress t: the current progress, must be between -1...1.
*/
func update(_ percentageComplete: TimeInterval) {
guard .animating == state else {
startingProgress = percentageComplete
return
}
progressRunner.stop()
progress = Double(CGFloat(percentageComplete).clamp(0, 1))
}
/**
Finish the interactive transition.
Will stop the interactive transition and animate from the
current state to the **end** state.
- Parameter isAnimated: A Boolean.
*/
func finish(isAnimated: Bool = true) {
guard .animating == state || .notified == state || .starting == state else {
return
}
guard isAnimated else {
complete(isFinishing: true)
return
}
var d: TimeInterval = 0
for a in animators {
d = max(d, a.resume(at: progress * totalDuration, isReversed: false))
}
complete(after: d, isFinishing: true)
}
/**
Cancel the interactive transition.
Will stop the interactive transition and animate from the
current state to the **begining** state
- Parameter isAnimated: A boolean indicating if the completion is animated.
*/
func cancel(isAnimated: Bool = true) {
guard .animating == state || .notified == state || .starting == state else {
return
}
guard isAnimated else {
complete(isFinishing: false)
return
}
var d: TimeInterval = 0
for a in animators {
var t = progress
if t < 0 {
t = -t
}
d = max(d, a.resume(at: t * totalDuration, isReversed: true))
}
complete(after: d, isFinishing: false)
}
/**
Override transition animations during an interactive animation.
For example:
Motion.shared.apply([.position(x:50, y:50)], to: view)
will set the view's position to 50, 50
- Parameter modifiers: An Array of MotionModifier.
- Parameter to view: A UIView.
*/
func apply(modifiers: [MotionModifier], to view: UIView) {
guard .animating == state else {
return
}
let targetState = MotionTargetState(modifiers: modifiers)
if let otherView = context.pairedView(for: view) {
for animator in animators {
animator.apply(state: targetState, to: otherView)
}
}
for animator in self.animators {
animator.apply(state: targetState, to: view)
}
}
}
| mit | 323749439b49f715c32bfe2ef8343d82 | 28.84 | 80 | 0.666756 | 4.477791 | false | false | false | false |
maxsokolov/TableKit | Sources/TableRow.swift | 3 | 4803 | //
// Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov
//
// 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
open class TableRow<CellType: ConfigurableCell>: Row where CellType: UITableViewCell {
public let item: CellType.CellData
private lazy var actions = [String: [TableRowAction<CellType>]]()
private(set) open var editingActions: [UITableViewRowAction]?
open var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
open var reuseIdentifier: String {
return CellType.reuseIdentifier
}
open var estimatedHeight: CGFloat? {
return CellType.estimatedHeight
}
open var defaultHeight: CGFloat? {
return CellType.defaultHeight
}
open var cellType: AnyClass {
return CellType.self
}
public init(item: CellType.CellData, actions: [TableRowAction<CellType>]? = nil, editingActions: [UITableViewRowAction]? = nil) {
self.item = item
self.editingActions = editingActions
actions?.forEach { on($0) }
}
// MARK: - RowConfigurable -
open func configure(_ cell: UITableViewCell) {
(cell as? CellType)?.configure(with: item)
}
// MARK: - RowActionable -
open func invoke(action: TableRowActionType, cell: UITableViewCell?, path: IndexPath, userInfo: [AnyHashable: Any]? = nil) -> Any? {
return actions[action.key]?.compactMap({ $0.invokeActionOn(cell: cell, item: item, path: path, userInfo: userInfo) }).last
}
open func has(action: TableRowActionType) -> Bool {
return actions[action.key] != nil
}
open func isEditingAllowed(forIndexPath indexPath: IndexPath) -> Bool {
if actions[TableRowActionType.canEdit.key] != nil {
return invoke(action: .canEdit, cell: nil, path: indexPath) as? Bool ?? false
}
return editingActions?.isEmpty == false || actions[TableRowActionType.clickDelete.key] != nil
}
// MARK: - actions -
@discardableResult
open func on(_ action: TableRowAction<CellType>) -> Self {
if actions[action.type.key] == nil {
actions[action.type.key] = [TableRowAction<CellType>]()
}
actions[action.type.key]?.append(action)
return self
}
@discardableResult
open func on<T>(_ type: TableRowActionType, handler: @escaping (_ options: TableRowActionOptions<CellType>) -> T) -> Self {
return on(TableRowAction<CellType>(type, handler: handler))
}
@discardableResult
open func on(_ key: String, handler: @escaping (_ options: TableRowActionOptions<CellType>) -> ()) -> Self {
return on(TableRowAction<CellType>(.custom(key), handler: handler))
}
open func removeAllActions() {
actions.removeAll()
}
open func removeAction(forActionId actionId: String) {
for (key, value) in actions {
if let actionIndex = value.firstIndex(where: { $0.id == actionId }) {
actions[key]?.remove(at: actionIndex)
}
}
}
// MARK: - deprecated actions -
@available(*, deprecated, message: "Use 'on' method instead")
@discardableResult
open func action(_ action: TableRowAction<CellType>) -> Self {
return on(action)
}
@available(*, deprecated, message: "Use 'on' method instead")
@discardableResult
open func action<T>(_ type: TableRowActionType, handler: @escaping (_ options: TableRowActionOptions<CellType>) -> T) -> Self {
return on(TableRowAction<CellType>(type, handler: handler))
}
}
| mit | c893219ff6efa50f986afc55d23d3e50 | 34.058394 | 136 | 0.644805 | 4.704212 | false | false | false | false |
ric2b/Vivaldi-browser | chromium/third_party/tflite_support/src/tensorflow_lite_support/ios/text/tokenizers/Tests/TFLBertTokenizerTest.swift | 1 | 1820 | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import XCTest
@testable import TFLBertTokenizer
class TFLBertTokenizerTest: XCTestCase {
static let bundle = Bundle(for: TFLBertTokenizerTest.self)
static let mobileBertVocabPath = bundle.path(forResource: "vocab", ofType: "txt")!
func testInitBertTokenizerFromPath() {
let bertTokenizer = TFLBertTokenizer(vocabPath: TFLBertTokenizerTest.mobileBertVocabPath)
XCTAssertNotNil(bertTokenizer)
let tokens = bertTokenizer.tokens(fromInput: "i'm questionansweraskask")
XCTAssertEqual(tokens, ["i", "'", "m", "question", "##ans", "##wer", "##ask", "##ask"])
let ids = bertTokenizer.ids(fromTokens: tokens)
XCTAssertEqual(ids, [1045, 1005, 1049, 3160, 6962, 13777, 19895, 19895])
}
func testInitBertTokenizerFromVocab() {
let bertTokenizer = TFLBertTokenizer(vocab: ["hell", "##o", "wor", "##ld", "there"])
XCTAssertNotNil(bertTokenizer)
let tokens = bertTokenizer.tokens(fromInput: "hello there hello world")
XCTAssertEqual(tokens, ["hell", "##o", "there", "hell", "##o", "wor", "##ld"])
let ids = bertTokenizer.ids(fromTokens: tokens)
XCTAssertEqual(ids, [0, 1, 4, 0, 1, 2, 3])
}
}
| bsd-3-clause | 28900298efbd91172cc24a86114cf49e | 35.4 | 93 | 0.691758 | 4.2723 | false | true | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/00713-swift-declcontext-lookupqualified.swift | 11 | 1066 | // 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
// RUN: not %target-swift-frontend %s -parse
// Distribu where D.C == E> {s func c() { }
func f<g>() -> (g, g -> g) -> g {
d j d.i = {
}
{
g) {
h }
}
protocol f {
}
protocol A {
-func b<d>(a : d) -> c { {}ol !(a)
}
}
func c<d {
enum c {
}
}
func a<T>() {
enum b {
}
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
class a<f : b, g : b where f.d == g> {
}
protocol b {
}
struct c<h : b> : b {
typealias e = a<c<h>0) {
}
protocol a : a {
}
class a {
}
struct A<T> {
}
func f<g>() -> (g, g -> g) -> g {
d j d.i = {
}
{
g) {
}
}
ny, Any) -> Any) -> Any)) -> Any {
return z({
})
}
func prefix(with: String) -> <T>(() -> T return "\(with): \(g())" }
}
struct c<S: Sequence, T where Optional<T> == S.Iterator.Element>
| apache-2.0 | 2e5d4894786528d23167ae5b321d5084 | 15.920635 | 78 | 0.555347 | 2.502347 | false | false | false | false |
huangboju/Moots | Examples/URLSession/Carthage/Checkouts/SwiftyJSON/Example/Playground.playground/Contents.swift | 4 | 10126 | //: Playground - noun: a place where people can play
/*:
# SwiftyJSON
SwiftyJSON makes it easy to deal with JSON data in Swift.
You must have to build `SwiftyJSON iOS` package for import.
*/
/*:
### Basic setting for playground
*/
import SwiftyJSON
import Foundation
var jsonData: Data?
if let file = Bundle.main.path(forResource: "SwiftyJSONTests", ofType: "json") {
jsonData = try? Data(contentsOf: URL(fileURLWithPath: file))
} else {
print("Fail")
}
let jsonObject = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)
let jsonString = String(data: jsonData!, encoding: .utf8)
/*:
## Usage
### Initialization
*/
let json1 = try? JSON(data: jsonData!)
/*:
or
*/
let json2 = JSON(jsonObject)
/*:
or
*/
let dataFromString = jsonString?.data(using: .utf8)
let json3 = try? JSON(data: dataFromString!)
/*:
### Subscript
*/
// Example json
let json: JSON = JSON([
"array": [12.34, 56.78],
"users": [
[
"id": 987654,
"info": [
"name": "jack",
"email": "[email protected]"
],
"feeds": [98833, 23443, 213239, 23232]
],
[
"id": 654321,
"info": [
"name": "jeffgukang",
"email": "[email protected]"
],
"feeds": [12345, 56789, 12423, 12412]
]
]
])
// Getting a double from a JSON Array
json["array"][0].double
// Getting an array of string from a JSON Array
let arrayOfString = json["users"].arrayValue.map({$0["info"]["name"]})
print(arrayOfString)
// Getting a string from a JSON Dictionary
json["users"][0]["info"]["name"].stringValue
// Getting a string using a path to the element
let path = ["users", 1, "info", "name"] as [JSONSubscriptType]
var name = json["users", 1, "info", "name"].string
// With a custom way
let keys: [JSONSubscriptType] = ["users", 1, "info", "name"]
name = json[keys].string
// Just the same
name = json["users"][1]["info"]["name"].string
// Alternatively
name = json["users", 1, "info", "name"].string
/*:
### Loop
*/
// If json is .Dictionary
for (key, subJson):(String, JSON) in json {
//Do something you want
print(key)
print(subJson)
}
/*The first element is always a String, even if the JSON is an Array*/
//If json is .Array
//The `index` is 0..<json.count's string value
for (index, subJson):(String, JSON) in json["array"] {
//Do something you want
print("\(index): \(subJson)")
}
/*:
### Error
SwiftyJSON 4.x
SwiftyJSON 4.x introduces an enum type called `SwiftyJSONError`, which includes `unsupportedType`, `indexOutOfBounds`, `elementTooDeep`, `wrongType`, `notExist` and `invalidJSON`, at the same time, `ErrorDomain` are being replaced by `SwiftyJSONError.errorDomain`. Note: Those old error types are deprecated in SwiftyJSON 4.x and will be removed in the future release.
Use a subscript to get/set a value in an Array or Dictionary
If the JSON is:
- an array, the app may crash with "index out-of-bounds."
- a dictionary, it will be assigned nil without a reason.
- not an array or a dictionary, the app may crash with an "unrecognised selector" exception.
This will never happen in SwiftyJSON.
*/
let errorJson = JSON(["name", "age"])
if let name = errorJson[999].string {
//Do something you want
print(name)
} else {
print(errorJson[999].error!) // "Array[999] is out of bounds"
}
let errorJson2 = JSON(["name": "Jack", "age": 25])
if let name = errorJson2["address"].string {
//Do something you want
print(name)
} else {
print(errorJson2["address"].error!) // "Dictionary["address"] does not exist"
}
let errorJson3 = JSON(12345)
if let age = errorJson3[0].string {
//Do something you want
print(age)
} else {
print(errorJson3[0]) // "Array[0] failure, It is not an array"
print(errorJson3[0].error!) // "Array[0] failure, It is not an array"
}
if let name = json["name"].string {
//Do something you want
print(name)
} else {
print(json["name"]) // "Dictionary[\"name"] failure, It is not an dictionary"
print(json["name"].error!) // "Dictionary[\"name"] failure, It is not an dictionary"
}
/*:
### Optional getter
*/
// Example json
let jsonOG: JSON = JSON([
"id": 987654,
"user": [
"favourites_count": 8,
"name": "jack",
"email": "[email protected]",
"is_translator": true
]
])
//NSNumber
if let id = jsonOG["user"]["favourites_count"].number {
//Do something you want
print(id)
} else {
//Print the error
print(jsonOG["user"]["favourites_count"].error!)
}
//String
if let id = jsonOG["user"]["name"].string {
//Do something you want
print(id)
} else {
//Print the error
print(jsonOG["user"]["name"].error!)
}
//Bool
if let id = jsonOG["user"]["is_translator"].bool {
//Do something you want
print(id)
} else {
//Print the error
print(jsonOG["user"]["is_translator"].error!)
}
/*:
### Non-optional getter
Non-optional getter is named xxxValue
*/
// Example json
let jsonNOG: JSON = JSON([
"id": 987654,
"name": "jack",
"list": [
["number": 1],
["number": 2],
["number": 3]
],
"user": [
"favourites_count": 8,
"email": "[email protected]",
"is_translator": true
]
])
//If not a Number or nil, return 0
let idNOG: Int = jsonOG["id"].intValue
print(idNOG)
//If not a String or nil, return ""
let nameNOG: String = jsonNOG["name"].stringValue
print(nameNOG)
//If not an Array or nil, return []
let listNOG: Array = jsonNOG["list"].arrayValue
print(listNOG)
//If not a Dictionary or nil, return [:]
let userNOG: Dictionary = jsonNOG["user"].dictionaryValue
print(userNOG)
/*:
### Setter
*/
var jsonSetter: JSON = JSON([
"id": 987654,
"name": "jack",
"array": [0, 2, 4, 6, 8],
"double": 3513.352,
"dictionary": [
"name": "Jack",
"sex": "man"
],
"user": [
"favourites_count": 8,
"email": "[email protected]",
"is_translator": true
]
])
jsonSetter["name"] = JSON("new-name")
jsonSetter["array"][0] = JSON(1)
jsonSetter["id"].int = 123456
jsonSetter["double"].double = 123456.789
jsonSetter["name"].string = "Jeff"
jsonSetter.arrayObject = [1, 2, 3, 4]
jsonSetter.dictionaryObject = ["name": "Jeff", "age": 20]
/*:
### Raw object
*/
let rawObject: Any = jsonSetter.object
let rawValue: Any = jsonSetter.rawValue
//convert the JSON to raw NSData
do {
let rawData = try jsonSetter.rawData()
print(rawData)
} catch {
print("Error \(error)")
}
//convert the JSON to a raw String
if let rawString = jsonSetter.rawString() {
print(rawString)
} else {
print("Nil")
}
/*:
### Existence
*/
// shows you whether value specified in JSON or not
if jsonSetter["name"].exists() {
print(jsonSetter["name"])
}
/*:
### Literal convertibles
For more info about literal convertibles: [Swift literal Convertibles](http://nshipster.com/swift-literal-convertible/)
*/
// StringLiteralConvertible
let jsonLiteralString: JSON = "I'm a json"
// IntegerLiteralConvertible
let jsonLiteralInt: JSON = 12345
// BooleanLiteralConvertible
let jsonLiteralBool: JSON = true
// FloatLiteralConvertible
let jsonLiteralFloat: JSON = 2.8765
// DictionaryLiteralConvertible
let jsonLiteralDictionary: JSON = ["I": "am", "a": "json"]
// ArrayLiteralConvertible
let jsonLiteralArray: JSON = ["I", "am", "a", "json"]
// With subscript in array
var jsonSubscriptArray: JSON = [1, 2, 3]
jsonSubscriptArray[0] = 100
jsonSubscriptArray[1] = 200
jsonSubscriptArray[2] = 300
jsonSubscriptArray[999] = 300 // Don't worry, nothing will happen
// With subscript in dictionary
var jsonSubscriptDictionary: JSON = ["name": "Jack", "age": 25]
jsonSubscriptDictionary["name"] = "Mike"
jsonSubscriptDictionary["age"] = "25" // It's OK to set String
jsonSubscriptDictionary["address"] = "L.A" // Add the "address": "L.A." in json
// Array & Dictionary
var jsonArrayDictionary: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]]
jsonArrayDictionary["list"][3]["what"] = "that"
jsonArrayDictionary["list", 3, "what"] = "that"
let arrayDictionarypath: [JSONSubscriptType] = ["list", 3, "what"]
jsonArrayDictionary[arrayDictionarypath] = "that"
// With other JSON objects
let user: JSON = ["username": "Steve", "password": "supersecurepassword"]
let auth: JSON = [
"user": user.object, //use user.object instead of just user
"apikey": "supersecretapitoken"
]
/*:
### Merging
It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the other JSON.
If both JSONs contain a value for the same key, mostly this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment:
- In case of both values being a JSON.Type.array the values form the array found in the other JSON getting appended to the original JSON's array value.
- In case of both values being a JSON.Type.dictionary both JSON-values are getting merged the same way the encapsulating JSON is merged.
In case, where two fields in a JSON have a different types, the value will get always overwritten.
There are two different fashions for merging: merge modifies the original JSON, whereas merged works non-destructively on a copy.
*/
var original: JSON = [
"first_name": "John",
"age": 20,
"skills": ["Coding", "Reading"],
"address": [
"street": "Front St",
"zip": "12345"
]
]
let update: JSON = [
"last_name": "Doe",
"age": 21,
"skills": ["Writing"],
"address": [
"zip": "12342",
"city": "New York City"
]
]
try original.merge(with: update)
print(original)
// [
// "first_name": "John",
// "last_name": "Doe",
// "age": 21,
// "skills": ["Coding", "Reading", "Writing"],
// "address": [
// "street": "Front St",
// "zip": "12342",
// "city": "New York City"
// ]
// ]
/*:
### String representation
There are two options available:
- use the default Swift one
- use a custom one that will handle optionals well and represent nil as "null":
*/
let stringRepresentationDict = ["1": 2, "2": "two", "3": nil] as [String: Any?]
let stringRepresentionJson: JSON = JSON(stringRepresentationDict)
let representation = stringRepresentionJson.rawString([.castNilToNSNull: true])
print(representation!)
// representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null}
| mit | 01835e901e1c11abd91f5044ef44384e | 23.458937 | 368 | 0.669761 | 3.265398 | false | false | false | false |
Juanpe/Counter | Example/Counter/ViewController.swift | 1 | 3288 | //
// ViewController.swift
// Counter
//
// Created by Juanpe Catalán on 09/19/2017.
// Copyright (c) 2017 Juanpe Catalán. All rights reserved.
//
import UIKit
import Counter
struct Person {
var age: Int
}
extension Person: Countable{
var deltaValue: Int {
return self.age
}
}
class ViewController: UIViewController, CounterDelegate, AutomaticCounterDelegate {
var automaticCounter: AutomaticCounter!
var automaticCounter2: AutomaticCounter!
var automaticCounter3: AutomaticCounter!
override func viewDidLoad() {
super.viewDidLoad()
let counter = Counter()
counter.delegate = self
counter.add(milestone: 3)
print(counter.currentValue) // 0
counter.increment()
print(counter.currentValue) // 1
counter.increment(2)
print(counter.currentValue) // 3
counter.decrement()
print(counter.currentValue) // 2
counter.reset()
print(counter.currentValue) // 0
counter.sum(countables: 2, 3, -1)
print(counter.currentValue) // 4
/// Advanced
let dad = Person(age: 45)
let mum = Person(age: 40)
let son = Person(age: 25)
let ageCounter = Counter()
ageCounter.increment(dad)
ageCounter.increment(mum)
ageCounter.increment(son)
print(ageCounter.currentValue) // 110
ageCounter.reset()
ageCounter.sum(countables: dad, mum, son)
print(ageCounter.currentValue) // 110
let ages = Counter.sum(countables: dad, mum, son)
print(ages) // 110
print("\n\n\nAUTOMATIC COUNTER\n\n\n")
automaticCounter = AutomaticCounter(startIn: 0, interval: 0.5, autoIncrement: 1)
automaticCounter.delegate = self
automaticCounter.automaticDelegate = self
automaticCounter.startCounting(endingAt: 10)
}
func launchTimer2() {
automaticCounter2 = AutomaticCounter(startIn: 0, interval: 0.2)
automaticCounter2.delegate = self
automaticCounter2.automaticDelegate = self
automaticCounter2.startCounting()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.automaticCounter2.endCounting()
}
}
func launchTimer3() {
automaticCounter3 = AutomaticCounter(startIn: 0, interval: 1)
automaticCounter3.delegate = self
automaticCounter3.automaticDelegate = self
automaticCounter3.startCounting(endingAfter: 3)
}
func counter(_ counter: Counter, hasReachedValue value: Int) {
print("\(#function) => \(value)")
}
func counter(_ counter: Counter, didChangeValue value: Int) {
print("\(#function) => \(value)")
}
func counter(_ counter: Counter, willReachValue value: Int) {
print("\(#function) => \(value)")
}
func counter(_ counter: Counter, didFinishCounting value: Int) {
print("\(#function) => \(value)\n\n")
if automaticCounter === counter {
launchTimer2()
}
else if automaticCounter2 === counter {
launchTimer3()
}
}
}
| mit | 725a42a6e57f0ed04fc4ed7001fa2c9d | 26.847458 | 88 | 0.59647 | 4.667614 | false | false | false | false |
Antondomashnev/Sourcery | Pods/SourceKittenFramework/Source/SourceKittenFramework/ObjCDeclarationKind.swift | 3 | 3094 | //
// ObjCDeclarationKind.swift
// SourceKitten
//
// Created by JP Simard on 7/15/15.
// Copyright © 2015 SourceKitten. All rights reserved.
//
#if !os(Linux)
#if SWIFT_PACKAGE
import Clang_C
#endif
/**
Objective-C declaration kinds.
More or less equivalent to `SwiftDeclarationKind`, but with made up values because there's no such
thing as SourceKit for Objective-C.
*/
public enum ObjCDeclarationKind: String {
/// `category`.
case category = "sourcekitten.source.lang.objc.decl.category"
/// `class`.
case `class` = "sourcekitten.source.lang.objc.decl.class"
/// `constant`.
case constant = "sourcekitten.source.lang.objc.decl.constant"
/// `enum`.
case `enum` = "sourcekitten.source.lang.objc.decl.enum"
/// `enumcase`.
case enumcase = "sourcekitten.source.lang.objc.decl.enumcase"
/// `initializer`.
case initializer = "sourcekitten.source.lang.objc.decl.initializer"
/// `method.class`.
case methodClass = "sourcekitten.source.lang.objc.decl.method.class"
/// `method.instance`.
case methodInstance = "sourcekitten.source.lang.objc.decl.method.instance"
/// `property`.
case property = "sourcekitten.source.lang.objc.decl.property"
/// `protocol`.
case `protocol` = "sourcekitten.source.lang.objc.decl.protocol"
/// `typedef`.
case typedef = "sourcekitten.source.lang.objc.decl.typedef"
/// `function`.
case function = "sourcekitten.source.lang.objc.decl.function"
/// `mark`.
case mark = "sourcekitten.source.lang.objc.mark"
/// `struct`
case `struct` = "sourcekitten.source.lang.objc.decl.struct"
/// `field`
case field = "sourcekitten.source.lang.objc.decl.field"
/// `ivar`
case ivar = "sourcekitten.source.lang.objc.decl.ivar"
/// `ModuleImport`
case moduleImport = "sourcekitten.source.lang.objc.module.import"
/// `UnexposedDecl`
case unexposedDecl = "sourcekitten.source.lang.objc.decl.unexposed"
// swiftlint:disable:next cyclomatic_complexity
public init(_ cursorKind: CXCursorKind) {
switch cursorKind {
case CXCursor_ObjCCategoryDecl: self = .category
case CXCursor_ObjCInterfaceDecl: self = .class
case CXCursor_EnumDecl: self = .enum
case CXCursor_EnumConstantDecl: self = .enumcase
case CXCursor_ObjCClassMethodDecl: self = .methodClass
case CXCursor_ObjCInstanceMethodDecl: self = .methodInstance
case CXCursor_ObjCPropertyDecl: self = .property
case CXCursor_ObjCProtocolDecl: self = .protocol
case CXCursor_TypedefDecl: self = .typedef
case CXCursor_VarDecl: self = .constant
case CXCursor_FunctionDecl: self = .function
case CXCursor_StructDecl: self = .struct
case CXCursor_FieldDecl: self = .field
case CXCursor_ObjCIvarDecl: self = .ivar
case CXCursor_ModuleImportDecl: self = .moduleImport
case CXCursor_UnexposedDecl: self = .unexposedDecl
default: fatalError("Unsupported CXCursorKind: \(clang_getCursorKindSpelling(cursorKind))")
}
}
}
#endif
| mit | eb3b4fecc33472846b3b2aa73f5e6d48 | 37.185185 | 99 | 0.684772 | 3.996124 | false | false | false | false |
spark/photon-tinker-ios | Photon-Tinker/Mesh/StepGetUserWifiNetworkSelection.swift | 1 | 2144 | //
// Created by Raimundas Sakalauskas on 2019-03-07.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class StepGetUserWifiNetworkSelection : Gen3SetupStep {
override func start() {
guard let context = self.context else {
return
}
if (context.selectedWifiNetworkInfo != nil) {
self.stepCompleted()
} else {
context.delegate.gen3SetupDidEnterState(self, state: .TargetDeviceScanningForWifiNetworks)
self.scanWifiNetworks()
}
}
func scanWifiNetworks() {
guard let context = self.context else {
return
}
context.targetDevice.transceiver?.sendScanWifiNetworks { [weak self, weak context] result, networks in
guard let self = self, let context = context, !context.canceled else {
return
}
self.log("sendScanWifiNetworks: \(result.description()), networksCount: \(networks?.count as Optional)\n\(networks as Optional)")
if (result == .NONE) {
context.targetDevice.wifiNetworks = Gen3SetupStep.removeRepeatedWifiNetworks(networks!)
} else {
//this command will be repeated multiple times, no need to trigger errors.. just pretend all is fine
context.targetDevice.wifiNetworks = []
}
context.delegate.gen3SetupDidRequestToSelectWifiNetwork(self, availableNetworks: context.targetDevice.wifiNetworks!)
}
}
func setSelectedWifiNetwork(selectedNetwork: Gen3SetupNewWifiNetworkInfo) -> Gen3SetupFlowError? {
guard let context = self.context else {
return nil
}
context.selectedWifiNetworkInfo = selectedNetwork
self.log("self.selectedWifiNetworkInfo: \(context.selectedWifiNetworkInfo)")
self.stepCompleted()
return nil
}
override func rewindTo(context: Gen3SetupContext) {
super.rewindTo(context: context)
guard let context = self.context else {
return
}
context.selectedWifiNetworkInfo = nil
}
}
| apache-2.0 | c796fd5e7d75398896285d409e22b0f4 | 30.529412 | 141 | 0.633862 | 5.153846 | false | false | false | false |
ObjectAlchemist/OOUIKit | Sources/_UIKitDelegate/UIApplicationDelegate/DisallowingSpecifiedAppExtensionTypes/UIApplicationDelegateDisallowAppExtensionPrinting.swift | 1 | 1570 | //
// UIApplicationDelegateDisallowAppExtensionPrinting.swift
// OOSwift
//
// Created by Karsten Litsche on 28.10.17.
//
//
import UIKit
/**
Print the UIApplicationDelegate section:
- Disallowing Specified App Extension Types
Use this decorator to log the print outputs while development/debugging. Define a filterKey if you need a
clear identification of this instance.
For more informations see UIPrintOverload.swift and UIApplicationDelegate documentation
*/
public final class UIApplicationDelegateDisallowAppExtensionPrinting: UIResponder, UIApplicationDelegate {
// MARK: - init
convenience override init() {
fatalError("Not supported!")
}
public init(_ decorated: UIApplicationDelegate, filterKey: String = "") {
self.decorated = decorated
// add space if exist to separate following log
self.filterKey = filterKey.count == 0 ? "" : "\(filterKey) "
}
// MARK: - protocol: UIApplicationDelegate
public func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplication.ExtensionPointIdentifier) -> Bool {
printUI("\(filterKey)application shouldAllowExtensionPointIdentifier called (\n extensionPointIdentifier=\(extensionPointIdentifier.rawValue)\n)")
return decorated.application?(application, shouldAllowExtensionPointIdentifier: extensionPointIdentifier) ?? true
}
// MARK: - private
private let decorated: UIApplicationDelegate
private let filterKey: String
}
| mit | 126359f5ede4d177002beff37b4091cd | 33.888889 | 169 | 0.736306 | 5.836431 | false | false | false | false |
AlesTsurko/AudioKit | Examples/iOS/Swift/AudioKitDemo/AudioKitDemo/Processing/ProcessingViewController.swift | 1 | 2521 | //
// ProcessingViewController.swift
// AudioKitDemo
//
// Created by Nicholas Arner on 3/1/15.
// Copyright (c) 2015 AudioKit. All rights reserved.
//
class ProcessingViewController: UIViewController {
@IBOutlet var sourceSegmentedControl: UISegmentedControl!
@IBOutlet var maintainPitchSwitch: UISwitch!
@IBOutlet var pitchSlider: UISlider!
var pitchToMaintain:Float
let conv: ConvolutionInstrument
let audioFilePlayer = AudioFilePlayer()
override init() {
conv = ConvolutionInstrument(input: audioFilePlayer.auxilliaryOutput)
pitchToMaintain = 1.0
super.init()
}
required init(coder aDecoder: NSCoder) {
conv = ConvolutionInstrument(input: audioFilePlayer.auxilliaryOutput)
pitchToMaintain = 1.0
super.init(coder: aDecoder)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
AKOrchestra.addInstrument(audioFilePlayer)
AKOrchestra.addInstrument(conv)
}
@IBAction func start(sender:UIButton) {
conv.play()
audioFilePlayer.play()
}
@IBAction func stop(sender:UIButton) {
conv.stop()
audioFilePlayer.stop()
}
@IBAction func wetnessChanged(sender:UISlider) {
AKTools.setProperty(conv.dryWetBalance, withSlider: sender)
}
@IBAction func impulseResponseChanged(sender:UISlider) {
AKTools.setProperty(conv.dishWellBalance, withSlider: sender)
}
@IBAction func speedChanged(sender:UISlider) {
AKTools.setProperty(audioFilePlayer.speed, withSlider: sender)
if (maintainPitchSwitch.on && fabs(audioFilePlayer.speed.value) > 0.1) {
audioFilePlayer.scaling.value = pitchToMaintain / fabs(audioFilePlayer.speed.value)
AKTools.setSlider(pitchSlider, withProperty: audioFilePlayer.scaling)
}
}
@IBAction func pitchChanged(sender:UISlider) {
AKTools.setProperty(audioFilePlayer.scaling, withSlider: sender)
}
@IBAction func togglePitchMaintenance(sender:UISwitch) {
if sender.on {
pitchSlider.enabled = false
pitchToMaintain = fabs(audioFilePlayer.speed.value) * audioFilePlayer.scaling.value
} else {
pitchSlider.enabled = true
}
}
@IBAction func fileChanged(sender:UISegmentedControl) {
audioFilePlayer.sampleMix.value = Float(sender.selectedSegmentIndex)
}
}
| lgpl-3.0 | 35e87cb2401c8dde17015527d0b828a7 | 29.373494 | 95 | 0.666799 | 4.91423 | false | false | false | false |
HotWordland/wlblog_server | Sources/App/main.swift | 1 | 798 | import Vapor
import VaporPostgreSQL
//let drop = Droplet(preparations:[User.self]
// ,providers:[VaporPostgreSQL.Provider.self])
let drop = Droplet()
drop.middleware = [CorsMiddleware()] // cors 设置
/* 版本之前的 cors 设置代码
let drop = Droplet(
availableMiddleware: ["cors" : CorsMiddleware()],
serverMiddleware: ["file", "cors"],
preparations: [Todo.self],
providers: [VaporMySQL.Provider.self]
)
*/
try drop.addProvider(VaporPostgreSQL.Provider.self)
drop.preparations+=User.self
drop.preparations+=Catagory.self
drop.preparations+=Article.self
//测试一下数据连接
if let postgresql = drop.database?.driver as? PostgreSQLDriver {
let all = try postgresql.raw("SELECT * FROM catagorys")
print(all)
}
//配置路由
configRoute(drop: drop)
drop.run()
| mit | 10b5cf567c56ebf2c4bcc908ee7790d6 | 21.787879 | 64 | 0.732713 | 3.387387 | false | false | false | false |
urbn/URBNConvenience | Pod/Classes/LayoutConvenience.swift | 1 | 5172 | //
// ConstraintConvenience.swift
// Pods
//
// Created by Nick DiStefano on 12/11/15.
//
//
import Foundation
public typealias InsetConstraint = (constant: CGFloat, priority: UILayoutPriority)
fileprivate var defaultInsetConstraint: InsetConstraint {
return (constant: 0.0, priority: UILayoutPriorityRequired)
}
public struct InsetConstraints {
public var top: InsetConstraint
public var left: InsetConstraint
public var right: InsetConstraint
public var bottom: InsetConstraint
public init(top: InsetConstraint = defaultInsetConstraint, left: InsetConstraint = defaultInsetConstraint, bottom: InsetConstraint = defaultInsetConstraint, right: InsetConstraint = defaultInsetConstraint) {
self.top = top
self.left = left
self.bottom = bottom
self.right = right
}
public init(insets: UIEdgeInsets, horizontalPriority: UILayoutPriority = UILayoutPriorityRequired, verticalPriority: UILayoutPriority = UILayoutPriorityRequired) {
self.init(top: (constant: insets.top, priority: verticalPriority),
left: (constant: insets.left, priority: horizontalPriority),
bottom: (constant: insets.bottom, priority: verticalPriority),
right: (constant: insets.right, priority: horizontalPriority))
}
public init(insets: UIEdgeInsets, priority: UILayoutPriority = UILayoutPriorityRequired) {
self.init(insets: insets, horizontalPriority: priority, verticalPriority: priority)
}
}
public func activateVFL(format: String, options: NSLayoutFormatOptions = [], metrics: [String : Any]? = nil, views: [String : Any]) {
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(
withVisualFormat: format,
options: options,
metrics: metrics,
views: views
)
)
}
public extension UIView {
@available(*, unavailable, message: "use addSubviewsWithNoConstraints instead")
public func addSubviewWithNoConstraints(_ subview: UIView) { }
public func addSubviewsWithNoConstraints(_ subviews: UIView...) {
addSubviewsWithNoConstraints(subviews)
}
public func addSubviewsWithNoConstraints(_ subviews: [UIView]) {
for v in subviews {
v.translatesAutoresizingMaskIntoConstraints = false
addSubview(v)
}
}
public func addSubviewsWithNoConstraints<T: UIView>(_ subviews: LazyMapCollection<[String: T], T>) {
addSubviewsWithNoConstraints(Array(subviews))
}
public func wrapInView(_ view: UIView? = nil, withInsets insets: UIEdgeInsets = UIEdgeInsets.zero) -> UIView {
var container: UIView
if let view = view {
container = view
}
else {
container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
}
container.addSubviewsWithNoConstraints(self)
let metrics = ["top": insets.top, "left": insets.left, "bottom": insets.bottom, "right": insets.right]
activateVFL(format: "H:|-left-[view]-right-|", metrics: metrics, views: ["view": self])
activateVFL(format: "V:|-top-[view]-bottom-|", metrics: metrics, views: ["view": self])
return container
}
@available(iOS 9, *)
public func wrap(in view: UIView, with insetConstraints: InsetConstraints) {
wrap(child: self, inParent: view, with: insetConstraints)
}
@available(iOS 9, *)
public func wrapInNewView(with insetConstraints: InsetConstraints) -> UIView {
let view = UIView()
wrap(child: self, inParent: view, with: insetConstraints)
return view
}
@available(iOS 9, *)
private func wrap(child: UIView, inParent parent: UIView, with insetConstraints: InsetConstraints) {
parent.addSubviewsWithNoConstraints(child)
let topAnchor = child.topAnchor.constraint(equalTo: parent.topAnchor, constant: insetConstraints.top.constant)
topAnchor.priority = insetConstraints.top.priority
topAnchor.isActive = true
let leftAnchor = child.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: insetConstraints.left.constant)
leftAnchor.priority = insetConstraints.left.priority
leftAnchor.isActive = true
let bottomAnchor = child.bottomAnchor.constraint(equalTo: parent.bottomAnchor, constant: -insetConstraints.bottom.constant)
bottomAnchor.priority = insetConstraints.bottom.priority
bottomAnchor.isActive = true
let rightAnchor = child.rightAnchor.constraint(equalTo: parent.rightAnchor, constant: -insetConstraints.right.constant)
rightAnchor.priority = insetConstraints.right.priority
rightAnchor.isActive = true
}
}
@available(iOS 9.0, *)
public extension UIStackView {
public func addArrangedSubviews(_ subviews: UIView...) {
addArrangedSubviews(subviews)
}
public func addArrangedSubviews(_ subviews: [UIView]) {
for v in subviews {
addArrangedSubview(v)
}
}
}
| mit | 64c51b88f5a6585c867700ea70b1c1fb | 36.751825 | 211 | 0.673047 | 5.218971 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureInterest/Sources/FeatureInterestUI/InterestAccountList/InterestAccountListItem/InterestAccountDetails.swift | 1 | 1595 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import ComposableArchitecture
import FeatureInterestDomain
import Localization
import MoneyKit
import PlatformKit
import PlatformUIKit
import SwiftUI
struct InterestAccountDetails: Equatable, Identifiable {
private typealias LocalizationId = LocalizationConstants.Interest.Screen.Overview
var id: String {
currency.code
}
var actionDisplayString: String {
balance.isPositive ? LocalizationId.Action.view : LocalizationId.Action.earnInterest
}
var isEligible: Bool {
ineligibilityReason == .eligible
}
var badgeImageViewModel: BadgeImageViewModel {
let model: BadgeImageViewModel = .default(
image: currency.logoResource,
cornerRadius: .round,
accessibilityIdSuffix: ""
)
model.marginOffsetRelay.accept(0)
return model
}
var actions: [InterestAccountListItemAction] {
guard isEligible else { return [] }
return [balance.isPositive ? .viewInterestButtonTapped(self) : .earnInterestButtonTapped(self)]
}
let ineligibilityReason: InterestAccountIneligibilityReason
let currency: CurrencyType
let balance: MoneyValue
let interestEarned: MoneyValue
let rate: Double
static func == (
lhs: InterestAccountDetails,
rhs: InterestAccountDetails
) -> Bool {
lhs.currency == rhs.currency &&
lhs.balance == rhs.balance &&
lhs.interestEarned == rhs.interestEarned &&
lhs.rate == rhs.rate
}
}
| lgpl-3.0 | 4b836895a414425fcd07abefdcd5fa82 | 26.964912 | 103 | 0.68256 | 5.367003 | false | false | false | false |
duliodenis/cs193p-Spring-2016 | democode/DropIt-L14/DropIt/FallingObjectBehavior.swift | 1 | 1304 | //
// FallingObjectBehavior.swift
// DropIt
//
// Created by CS193p Instructor.
// Copyright © 2016 Stanford University. All rights reserved.
//
import UIKit
class FallingObjectBehavior: UIDynamicBehavior
{
let gravity = UIGravityBehavior()
private let collider: UICollisionBehavior = {
let collider = UICollisionBehavior()
collider.translatesReferenceBoundsIntoBoundary = true
return collider
}()
private let itemBehavior: UIDynamicItemBehavior = {
let dib = UIDynamicItemBehavior()
dib.allowsRotation = true
dib.elasticity = 0.75
return dib
}()
func addBarrier(path: UIBezierPath, named name: String) {
collider.removeBoundaryWithIdentifier(name)
collider.addBoundaryWithIdentifier(name, forPath: path)
}
override init() {
super.init()
addChildBehavior(gravity)
addChildBehavior(collider)
addChildBehavior(itemBehavior)
}
func addItem(item: UIDynamicItem) {
gravity.addItem(item)
collider.addItem(item)
itemBehavior.addItem(item)
}
func removeItem(item: UIDynamicItem) {
gravity.removeItem(item)
collider.removeItem(item)
itemBehavior.removeItem(item)
}
}
| mit | 52b6b0ba0d83731424901ab6e18a7dd8 | 24.057692 | 63 | 0.651573 | 4.825926 | false | false | false | false |
hooman/swift | test/decl/var/usage.swift | 4 | 20902 | // RUN: %target-typecheck-verify-swift
// <rdar://problem/20872721> QoI: warn about unused variables
// <rdar://problem/15975935> warning that you can use 'let' not 'var'
// <rdar://problem/18876585> Compiler should warn me if I set a parameter as 'var' but never modify it
func basicTests() -> Int {
let x = 42 // expected-warning {{immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}} {{3-8=_}}
var y = 12 // expected-warning {{variable 'y' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
_ = 42 // ok
_ = 42 // ok
return y
}
func mutableParameter(_ a : Int, h : Int, var i : Int, j: Int, g: Int) -> Int { // expected-warning {{'var' in this position is interpreted as an argument label}} {{43-46=`var`}}
i += 1 // expected-error {{left side of mutating operator isn't mutable: 'i' is a 'let' constant}}
var j = j
swap(&i, &j) // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}}
return i+g
}
struct X {
func f() {}
mutating func g() {}
}
func testStruct() {
let a = X()
a.f()
var b = X()
b.g()
var c = X() // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
c.f()
}
func takeClosure(_ fn : () -> ()) {}
class TestClass {
func f() {
takeClosure { [weak self] in // self is mutable but never mutated. Ok because it is weak
self?.f()
}
}
}
enum TestEnum {
case Test(Int, Int, Int)
}
func testEnum() -> Int {
let ev = TestEnum.Test(5, 6, 7)
switch ev {
case .Test(var i, var j, var k): // expected-warning {{variable 'i' was never mutated; consider changing to 'let' constant}} {{14-17=let}}
// expected-warning@-1 {{variable 'j' was never mutated; consider changing to 'let' constant}} {{21-24=let}}
// expected-warning@-2 {{variable 'k' was never mutated; consider changing to 'let' constant}} {{28-31=let}}
return i + j + k
default:
return 0
}
}
func nestedFunction() -> Int {
var x = 42 // No warning about being never-set.
func g() {
x = 97
var q = 27 // expected-warning {{variable 'q' was never used}} {{5-10=_}}
}
g()
return x
}
func neverRead() {
var x = 42 // expected-warning {{variable 'x' was written to, but never read}}
x = 97
x = 123
}
func property() -> Int {
var p : Int { // everything ok
return 42
}
return p
}
func testInOut(_ x : inout Int) { // Ok.
}
struct TestStruct {
var property = 42
var mutatingProperty: Int {
mutating get { return 0 }
mutating set {}
}
var nonmutatingProperty: Int {
nonmutating get { return 0 }
nonmutating set {}
}
subscript(mutating index: Int) -> Int {
mutating get { return 0 }
mutating set {}
}
subscript(nonmutating index: Int) -> Int {
nonmutating get { return 0 }
nonmutating set {}
}
}
func testStructMember() -> TestStruct {
var x = TestStruct() // ok
x.property = 17
return x
}
func testMutatingProperty_get() -> TestStruct {
var x = TestStruct() // ok
_ = x.mutatingProperty
return x
}
func testMutatingProperty_set() -> TestStruct {
var x = TestStruct() // ok
x.mutatingProperty = 17
return x
}
func testNonmutatingProperty_get() -> TestStruct {
var x = TestStruct() // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
_ = x.nonmutatingProperty
return x
}
func testNonmutatingProperty_set() -> TestStruct {
var x = TestStruct() // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
x.nonmutatingProperty = 17
return x
}
func testMutatingSubscript_get() -> TestStruct {
var x = TestStruct() // ok
_ = x[mutating: 4]
return x
}
func testMutatingSubscript_set() -> TestStruct {
var x = TestStruct() // ok
x[mutating: 4] = 17
return x
}
func testNonmutatingSubscript_get() -> TestStruct {
var x = TestStruct() // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
_ = x[nonmutating: 4]
return x
}
func testNonmutatingSubscript_set() -> TestStruct {
var x = TestStruct() // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
x[nonmutating: 4] = 17
return x
}
func testSubscript() -> [Int] {
var x = [1,2,3] // ok
x[1] = 27
return x
}
func testSubscriptNeverMutated() -> [Int] {
var x = [1,2,3] // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
_ = x[1]
return x
}
func testTuple(_ x : Int) -> Int {
var x = x
var y : Int // Ok, stored by a tuple
(x, y) = (1,2)
_ = x
_ = y
return y
}
struct TestComputedPropertyStruct {
var x : Int {
get {}
nonmutating set {}
}
}
func test() {
let v = TestComputedPropertyStruct()
v.x = 42
var v2 = TestComputedPropertyStruct() // expected-warning {{variable 'v2' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
v2.x = 42
}
func test4() {
// expected-warning @+1 {{variable 'dest' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var dest = UnsafeMutablePointer<Int>(bitPattern: 0)!
dest[0] = 0
}
func testTuple() {
var tup : (x:Int, y:Int) // expected-warning {{variable 'tup' was written to, but never read}}
tup.x = 1
// <rdar://problem/20927707> QoI: 'variable was never mutated' noisy when only part of a destructured tuple is mutated
var (tupA, tupB) = (1,2) // don't warn about tupB being changeable to a 'let'.
tupA += tupB
}
/// <rdar://problem/20911927> False positive in the "variable was never mutated" warning with IUO
func testForceValueExpr() {
var a: X! = nil // no warning, mutated through the !
a!.g()
}
// <rdar://problem/20894455> "variable was never mutated" diagnostic does not take #if into account
func testBuildConfigs() {
let abc = 42 // no warning.
var mut = 18 // no warning.
#if false
mut = abc // These uses prevent abc/mut from being unused/unmutated.
#endif
}
// same as above, but with a guard statement
func testGuardWithPoundIf(x: Int?) {
guard let x = x else { return }
#if false
_ = x
#endif
}
// <rdar://problem/21091625> Bogus 'never mutated' warning when protocol variable is mutated only by mutating method
protocol Fooable {
mutating func mutFoo()
func immutFoo()
var mutatingProperty: Int { mutating get mutating set }
var nonmutatingProperty: Int { nonmutating get nonmutating set }
}
func testOpenExistential(_ x: Fooable,
y: Fooable) {
var x = x
let y = y
x.mutFoo()
y.immutFoo()
}
func testOpenExistential_mutatingProperty_get(p: Fooable) {
var x = p
_ = x.mutatingProperty
}
func testOpenExistential_mutatingProperty_set(p: Fooable) {
var x = p
x.mutatingProperty = 4
}
func testOpenExistential_nonmutatingProperty_get(p: Fooable) {
var x = p // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
_ = x.nonmutatingProperty
}
func testOpenExistential_nonmutatingProperty_set(p: Fooable) {
var x = p // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
x.nonmutatingProperty = 4
}
func couldThrow() throws {}
func testFixitsInStatementsWithPatterns(_ a : Int?) {
if var b = a, // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} {{6-9=let}}
var b2 = a { // expected-warning {{variable 'b2' was never mutated; consider changing to 'let' constant}} {{7-10=let}}
_ = b
_ = b2
}
for var b in [42] { // expected-warning {{variable 'b' was never mutated; consider removing 'var' to make it constant}} {{7-11=}}
_ = b
}
do {
try couldThrow()
} catch var err { // expected-warning {{variable 'err' was never mutated; consider changing to 'let' constant}} {{11-14=let}}
_ = err
}
switch a {
case var b: _ = b // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} {{10-13=let}}
}
}
// <rdar://22774938> QoI: "never used" in an "if let" should rewrite expression to use != nil
func test(_ a : Int?, b : Any) {
if true == true, let x = a { // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{20-25=_}}
}
if let x = a, let y = a { // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{6-11=_}}
_ = y
}
// Simple case, insert a comparison with nil.
if let x = a { // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}} {{6-14=}} {{15-15= != nil}}
}
// General case, need to insert parentheses.
if let x = a ?? a {} // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}} {{6-14=(}} {{20-20=) != nil}}
// Special case, we can turn this into an 'is' test.
if let x = b as? Int { // expected-warning {{value 'x' was defined but never used; consider replacing with boolean test}} {{6-14=}} {{16-19=is}}
}
// SR-14646. Special case, turn this into an 'is' test with optional value.
let bb: Any? = 3
if let bbb = bb as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{19-22=is}}
if let bbb = (bb) as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{21-24=is}}
func aa() -> Any? { return 1 }
if let aaa = aa() as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{21-24=is}}
if let aaa = (aa()) as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{23-26=is}}
func bb() -> Any { return 1 }
if let aaa = aa() as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{21-24=is}}
if let aaa = (aa()) as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{23-26=is}}
func throwingAA() throws -> Any? { return 1 }
do {
if let aaa = try! throwingAA() as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{36-39=is}}
if let aaa = (try! throwingAA()) as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{38-41=is}}
if let aaa = try throwingAA() as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{35-38=is}}
if let aaa = (try throwingAA()) as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{37-40=is}}
} catch { }
if let aaa = try? throwingAA() as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{6-16=(}} {{41-41=) != nil}}
if let aaa = (try? throwingAA()) as? Int {} // expected-warning {{value 'aaa' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{36-39=is}}
func throwingBB() throws -> Any { return 1 }
do {
if let bbb = try! throwingBB() as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{36-39=is}}
if let bbb = (try! throwingBB()) as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{38-41=is}}
if let bbb = try throwingBB() as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{35-38=is}}
if let bbb = (try throwingBB()) as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{8-18=}} {{37-40=is}}
} catch { }
if let bbb = try? throwingBB() as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{6-16=(}} {{41-41=) != nil}}
if let bbb = (try? throwingBB()) as? Int {} // expected-warning {{value 'bbb' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{36-39=is}}
let cc: (Any?, Any) = (1, 2)
if let (cc1, cc2) = cc as? (Int, Int) {} // expected-warning {{immutable value 'cc1' was never used; consider replacing with '_' or removing it}} expected-warning {{immutable value 'cc2' was never used; consider replacing with '_' or removing it}}
// SR-1112
let xxx: Int? = 0
if let yyy = xxx { } // expected-warning{{with boolean test}} {{6-16=}} {{19-19= != nil}}
var zzz: Int? = 0
zzz = 1
if let yyy = zzz { } // expected-warning{{with boolean test}} {{6-16=}} {{19-19= != nil}}
if let yyy = zzz ?? xxx { } // expected-warning{{with boolean test}} {{6-16=(}} {{26-26=) != nil}}
}
func test2() {
let a = 4 // expected-warning {{initialization of immutable value 'a' was never used; consider replacing with assignment to '_' or removing it}} {{3-8=_}}
var ( b ) = 6 // expected-warning {{initialization of variable 'b' was never used; consider replacing with assignment to '_' or removing it}} {{3-12=_}}
var c: Int = 4 // expected-warning {{variable 'c' was never used; consider replacing with '_' or removing it}} {{7-8=_}}
let (d): Int = 9 // expected-warning {{immutable value 'd' was never used; consider replacing with '_' or removing it}} {{8-9=_}}
}
let optionalString: String? = "check"
if let string = optionalString {} // expected-warning {{value 'string' was defined but never used; consider replacing with boolean test}} {{4-17=}} {{31-31= != nil}}
let optionalAny: Any? = "check"
if let string = optionalAny as? String {} // expected-warning {{value 'string' was defined but never used; consider replacing with boolean test}} {{4-17=}} {{29-32=is}}
// Due to the complexities of global variable tracing, these will not generate warnings
let unusedVariable = ""
var unNeededVar = false
if unNeededVar {}
guard let foo = optionalAny else {}
for i in 0..<10 { // expected-warning {{immutable value 'i' was never used; consider replacing with '_' or removing it}} {{5-6=_}}
print("")
}
// Tests fix to SR-2421
func sr2421() {
let x: Int // expected-warning {{immutable value 'x' was never used; consider removing it}}
x = 42
}
// Tests fix to SR-964
func sr964() {
var noOpSetter: String {
get { return "" }
set { } // No warning
}
var suspiciousSetter: String {
get { return "" }
set {
print(suspiciousSetter) // expected-warning {{setter argument 'newValue' was never used, but the property was accessed}} expected-note {{did you mean to use 'newValue' instead of accessing the property's current value?}} {{13-29=newValue}}
}
}
struct MemberGetterStruct {
var suspiciousSetter: String {
get { return "" }
set {
print(suspiciousSetter) // expected-warning {{setter argument 'newValue' was never used, but the property was accessed}} expected-note {{did you mean to use 'newValue' instead of accessing the property's current value?}} {{15-31=newValue}}
}
}
}
class MemberGetterClass {
var suspiciousSetter: String {
get { return "" }
set {
print(suspiciousSetter) // expected-warning {{setter argument 'newValue' was never used, but the property was accessed}} expected-note {{did you mean to use 'newValue' instead of accessing the property's current value?}} {{15-31=newValue}}
}
}
}
var namedSuspiciousSetter: String {
get { return "" }
set(parameter) {
print(namedSuspiciousSetter) // expected-warning {{setter argument 'parameter' was never used, but the property was accessed}} expected-note {{did you mean to use 'parameter' instead of accessing the property's current value?}} {{13-34=parameter}}
}
}
var okSetter: String {
get { return "" }
set { print(newValue) } // No warning
}
var multiTriggerSetter: String {
get { return "" }
set {
print(multiTriggerSetter) // expected-warning {{setter argument 'newValue' was never used, but the property was accessed}} expected-note {{did you mean to use 'newValue' instead of accessing the property's current value?}} {{13-31=newValue}}
print(multiTriggerSetter)
}
}
}
struct MemberGetterExtension {}
extension MemberGetterExtension {
var suspiciousSetter: String {
get { return "" }
set {
print(suspiciousSetter) // expected-warning {{setter argument 'newValue' was never used, but the property was accessed}} expected-note {{did you mean to use 'newValue' instead of accessing the property's current value?}} {{13-29=newValue}}
}
}
}
func testLocalFunc() {
var unusedVar = 0
// expected-warning@-1 {{initialization of variable 'unusedVar' was never used; consider replacing with assignment to '_' or removing it}}
var notMutatedVar = 0
// expected-warning@-1 {{variable 'notMutatedVar' was never mutated; consider changing to 'let' constant}}
var mutatedVar = 0
// expected-warning@-1 {{variable 'mutatedVar' was written to, but never read}}
func localFunc() {
_ = notMutatedVar
mutatedVar = 1
}
}
// False positive "'var' was never mutated" warning - rdar://60563962
func testForwardReferenceCapture() {
func innerFunc() {
x = 10
}
var x: Int = 1
innerFunc()
print(x)
}
// rdar://47240768 Expand the definition of "simple" pattern to variables bound in patterns
func testVariablesBoundInPatterns() {
enum StringB {
case simple(b: Bool)
case tuple(b: (Bool, Bool))
case optional(b: Bool?)
}
// Because Swift enables all kinds of creative binding forms, make sure that
// variable patterns occuring directly under a `let` or `var` have that
// introducer stripped by the fixit. All other cases are currently too
// complicated for the VarDeclUsageChecker.
switch StringB.simple(b: true) {
case .simple(b: let b) where false: // expected-warning {{immutable value 'b' was never used; consider replacing with '_' or removing it}} {{19-24=_}}
break
case .simple(b: var b) where false: // expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} {{19-24=_}}
break
case var .simple(b: b): // expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} {{23-24=_}}
break
case .tuple(b: let (b1, b2)) where false:
// expected-warning@-1 {{immutable value 'b1' was never used; consider replacing with '_' or removing it}} {{23-25=_}}
// expected-warning@-2 {{immutable value 'b2' was never used; consider replacing with '_' or removing it}} {{27-29=_}}
break
case .tuple(b: (let b1, let b2)) where false:
// expected-warning@-1 {{immutable value 'b1' was never used; consider replacing with '_' or removing it}} {{19-25=_}}
// expected-warning@-2 {{immutable value 'b2' was never used; consider replacing with '_' or removing it}} {{27-33=_}}
break
case .tuple(b: (var b1, var b2)) where false:
// expected-warning@-1 {{variable 'b1' was never used; consider replacing with '_' or removing it}} {{19-25=_}}
// expected-warning@-2 {{variable 'b2' was never used; consider replacing with '_' or removing it}} {{27-33=_}}
break
case var .tuple(b: (b1, b2)) where false:
// expected-warning@-1 {{variable 'b1' was never used; consider replacing with '_' or removing it}} {{23-25=_}}
// expected-warning@-2 {{variable 'b2' was never used; consider replacing with '_' or removing it}} {{27-29=_}}
break
case .tuple(b: let b): // expected-warning {{immutable value 'b' was never used; consider replacing with '_' or removing it}} {{18-23=_}}
break
case .optional(b: let x?) where false: // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{25-26=_}}
break
case .optional(b: let .some(x)) where false: // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{31-32=_}}
break
case let .optional(b: x?): // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{25-26=_}}
break
case let .optional(b: .none): // expected-warning {{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{8-12=}}
break
}
}
// Tests fix to SR-14646
func testUselessCastWithInvalidParam(foo: Any?) -> Int {
class Foo { }
if let bar = foo as? Foo { return 42 } // expected-warning {{value 'bar' was defined but never used; consider replacing with boolean test}} {{6-16=}} {{20-23=is}}
else { return 54 }
}
| apache-2.0 | fafec7aec1ae6018c6ba78369352eff6 | 37.140511 | 253 | 0.649156 | 3.671351 | false | true | false | false |
marcelobusico/reddit-ios-app | Reddit-App/Reddit-App/ListReddits/View/ListRedditsViewController.swift | 1 | 4382 | //
// ListRedditsViewController.swift
// Reddit-App
//
// Created by Marcelo Busico on 11/2/17.
// Copyright © 2017 Busico. All rights reserved.
//
import UIKit
class ListRedditsViewController: UITableViewController {
// MARK: - Constants
private let redditCellReuseIdentifier = "RedditCell"
private let estimatedRowHeight: CGFloat = 200
fileprivate let showImageSegueIdentifier = "showImage"
// MARK: - Properties
fileprivate var presenter: ListRedditsPresenter!
fileprivate var redditModelForDetails: RedditModel?
// MARK: - ViewController lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
//TableView Setup
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = estimatedRowHeight
tableView.separatorStyle = .none
//Pull to refresh setup
refreshControl?.addTarget(self, action: #selector(refreshRequested), for: .valueChanged)
//Presenter Setup
let presenterFactory = ListRedditsPresenterFactory(view: self)
presenter = presenterFactory.presenter
}
override func viewWillAppear(_ animated: Bool) {
presenter.start()
}
override func encodeRestorableState(with coder: NSCoder) {
super.encodeRestorableState(with: coder)
presenter.saveState(coder: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
super.decodeRestorableState(with: coder)
presenter.restoreState(coder: coder)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == showImageSegueIdentifier,
let destinationViewController = segue.destination as? ViewRedditDetailsViewController {
destinationViewController.redditModel = redditModelForDetails
}
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRows = presenter.numberOfElements()
if numberOfRows > 0 {
tableView.separatorStyle = .singleLine
}
return numberOfRows
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let emptyCell = UITableViewCell()
guard let elementModel = presenter.elementModel(forPosition: indexPath.row) else {
return emptyCell
}
guard let redditViewCell = tableView.dequeueReusableCell(withIdentifier: redditCellReuseIdentifier, for: indexPath) as? RedditViewCell else {
return emptyCell
}
redditViewCell.model = elementModel
presenter.loadThumbnailForModel(model: elementModel) { image in
redditViewCell.setupThumbnail(withImage: image)
}
return redditViewCell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
presenter.elementSelected(atPosition: indexPath.row)
}
// MARK: - Pull to refresh handler
@objc func refreshRequested(refreshControl: UIRefreshControl) {
presenter.refresh()
}
}
extension ListRedditsViewController: UIDataSourceModelAssociation {
func modelIdentifierForElement(at indexPath: IndexPath, in view: UIView) -> String? {
guard let elementModel = presenter.elementModel(forPosition: indexPath.row) else {
return nil
}
return elementModel.name
}
func indexPathForElement(withModelIdentifier identifier: String, in view: UIView) -> IndexPath? {
guard let elementPosition = presenter.elementPosition(forName: identifier) else {
return nil
}
return IndexPath(row: elementPosition, section: 0)
}
}
extension ListRedditsViewController: ListRedditsViewProtocol {
func showLoading() {
refreshControl?.beginRefreshing()
}
func hideLoading() {
refreshControl?.endRefreshing()
}
func displayMessage(title: String, message: String) {
let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertViewController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertViewController, animated: true, completion: nil)
}
func refreshRedditsList() {
tableView.reloadData()
}
func showDetailsScreen(forModel model: RedditModel) {
redditModelForDetails = model
performSegue(withIdentifier: showImageSegueIdentifier, sender: self)
}
}
| apache-2.0 | c4c2b14edee05c70c966b0c13567073b | 28.802721 | 145 | 0.745492 | 5.117991 | false | false | false | false |
ul7290/realm-cocoa | RealmSwift-swift1.2/Object.swift | 2 | 13409 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
In Realm you define your model classes by subclassing `Object` and adding properties to be persisted.
You then instantiate and use your custom subclasses instead of using the Object class directly.
```swift
class Dog: Object {
dynamic var name: String = ""
dynamic var adopted: Bool = false
let siblings = List<Dog>()
}
```
### Supported property types
- `String`, `NSString`
- `Int`
- `Int8`, `Int16`, `Int32`, `Int64`
- `Float`
- `Double`
- `Bool`
- `NSDate`
- `NSData`
- `RealmOptional<T>` for optional numeric properties
- `Object` subclasses for to-one relationships
- `List<T: Object>` for to-many relationships
`String`, `NSString`, `NSDate`, `NSData` and `Object` subclass properties can be
optional. `Int`, `Int8`, Int16`, Int32`, `Int64`, `Float`, `Double`, `Bool`
and `List` properties cannot. To store an optional number, instead use
`RealmOptional<Int>`, `RealmOptional<Float>`, `RealmOptional<Double>`, or
`RealmOptional<Bool>` instead, which wraps an optional value of the generic type.
All property types except for `List` and `RealmOptional` *must* be declared as
`dynamic var`. `List` and `RealmOptional` properties must be declared as
non-dynamic `let` properties.
### Querying
You can gets `Results` of an Object subclass via the `objects(_:)` instance method on `Realm`.
### Relationships
See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
*/
public class Object: RLMObjectBase, Equatable, Printable {
// MARK: Initializers
/**
Initialize a standalone (unpersisted) `Object`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
:see: Realm().add(_:)
*/
public required override init() {
super.init()
}
/**
Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
:param: value The value used to populate the object. This can be any key/value coding compliant
object, or a JSON object such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
*/
public init(value: AnyObject) {
self.dynamicType.sharedSchema() // ensure this class' objectSchema is loaded in the partialSharedSchema
super.init(value: value, schema: RLMSchema.partialSharedSchema())
}
// MARK: Properties
/// The `Realm` this object belongs to, or `nil` if the object
/// does not belong to a realm (the object is standalone).
public var realm: Realm? {
if let rlmReam = RLMObjectBaseRealm(self) {
return Realm(rlmReam)
}
return nil
}
/// The `ObjectSchema` which lists the persisted properties for this object.
public var objectSchema: ObjectSchema {
return ObjectSchema(RLMObjectBaseObjectSchema(self))
}
/// Indicates if an object can no longer be accessed.
///
/// An object can no longer be accessed if the object has been deleted from the containing
/// `realm` or if `invalidate` is called on the containing `realm`.
public override var invalidated: Bool { return super.invalidated }
/// Returns a human-readable description of this object.
public override var description: String { return super.description }
#if os(OSX)
/// Helper to return the class name for an Object subclass.
public final override var className: String { return "" }
#else
/// Helper to return the class name for an Object subclass.
public final var className: String { return "" }
#endif
// MARK: Object Customization
/**
Override to designate a property as the primary key for an `Object` subclass. Only properties of
type String and Int can be designated as the primary key. Primary key
properties enforce uniqueness for each value whenever the property is set which incurs some overhead.
Indexes are created automatically for primary key properties.
:returns: Name of the property designated as the primary key, or `nil` if the model has no primary key.
*/
public class func primaryKey() -> String? { return nil }
/**
Override to return an array of property names to ignore. These properties will not be persisted
and are treated as transient.
:returns: `Array` of property names to ignore.
*/
public class func ignoredProperties() -> [String] { return [] }
/**
Return an array of property names for properties which should be indexed. Only supported
for string and int properties.
:returns: `Array` of property names to index.
*/
public class func indexedProperties() -> [String] { return [] }
// MARK: Inverse Relationships
/**
Get an `Array` of objects of type `T` which have this object as the given property value. This can
be used to get the inverse relationship value for `Object` and `List` properties.
:param: type The type of object on which the relationship to query is defined.
:param: propertyName The name of the property which defines the relationship.
:returns: An `Array` of objects of type `T` which have this object as their value for the `propertyName` property.
*/
public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] {
return RLMObjectBaseLinkingObjectsOfClass(self, T.className(), propertyName) as! [T]
}
// MARK: Key-Value Coding & Subscripting
/// Returns or sets the value of the property with the given name.
public subscript(key: String) -> AnyObject? {
get {
if realm == nil {
return self.valueForKey(key)
}
let property = RLMValidatedGetProperty(self, key)
if property.type == .Array {
return self.listForProperty(property)
}
return RLMDynamicGet(self, property)
}
set(value) {
if realm == nil {
self.setValue(value, forKey: key)
}
else {
RLMDynamicValidatedSet(self, key, value)
}
}
}
// MARK: Dynamic list
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the KVC returns.
Returns a List of DynamicObjects for a property name
:warning: This method is useful only in specialized circumstances
:param: propertyName The name of the property to get a List<DynamicObject>
:returns: A List of DynamicObjects
:nodoc:
*/
public func dynamicList(propertyName: String) -> List<DynamicObject> {
return unsafeBitCast(listForProperty(RLMValidatedGetProperty(self, propertyName)), List<DynamicObject>.self)
}
// MARK: Private functions
// FIXME: None of these functions should be exposed in the public interface.
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(value: AnyObject, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
// Helper for getting the list object for a property
internal func listForProperty(prop: RLMProperty) -> RLMListBase {
return object_getIvar(self, prop.swiftIvar) as! RLMListBase
}
}
// MARK: Equatable
/// Returns whether both objects are equal.
/// Objects are considered equal when they are both from the same Realm
/// and point to the same underlying object in the database.
public func == <T: Object>(lhs: T, rhs: T) -> Bool {
return RLMObjectBaseAreEqual(lhs, rhs)
}
/// Object interface which allows untyped getters and setters for Objects.
/// :nodoc:
public final class DynamicObject: Object {
private var listProperties = [String: List<DynamicObject>]()
// Override to create List<DynamicObject> on access
internal override func listForProperty(prop: RLMProperty) -> RLMListBase {
if let list = listProperties[prop.name] {
return list
}
let list = List<DynamicObject>()
listProperties[prop.name] = list
return list
}
/// :nodoc:
public override func valueForUndefinedKey(key: String) -> AnyObject? {
return self[key]
}
/// :nodoc:
public override func setValue(value: AnyObject?, forUndefinedKey key: String) {
self[key] = value
}
/// :nodoc:
public override class func shouldIncludeInDefaultSchema() -> Bool {
return false
}
}
/// :nodoc:
/// Internal class. Do not use directly.
public class ObjectUtil: NSObject {
@objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.ignoredProperties() as NSArray?
}
return nil
}
@objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.indexedProperties() as NSArray?
}
return nil
}
// Get the names of all properties in the object which are of type List<>
@objc private class func getGenericListPropertyNames(obj: AnyObject) -> NSArray {
let reflection = reflect(obj)
var properties = [String]()
// Skip the first property (super):
// super is an implicit property on Swift objects
for i in 1..<reflection.count {
let mirror = reflection[i].1
if mirror.valueType is RLMListBase.Type {
properties.append(reflection[i].0)
}
}
return properties
}
@objc private class func initializeListProperty(object: RLMObjectBase, property: RLMProperty, array: RLMArray) {
(object as! Object).listForProperty(property)._rlmArray = array
}
@objc private class func getOptionalProperties(object: AnyObject) -> NSDictionary {
let reflection = reflect(object)
var properties = [String:AnyObject]()
// Skip the first property (super):
// super is an implicit property on Swift objects
for i in 1..<reflection.count {
let mirror = reflection[i].1
let name = reflection[i].0
if mirror.valueType is Optional<String>.Type || mirror.valueType is Optional<NSString>.Type {
properties[name] = Int(PropertyType.String.rawValue)
} else if mirror.valueType is Optional<NSDate>.Type {
properties[name] = Int(PropertyType.Date.rawValue)
} else if mirror.valueType is Optional<NSData>.Type {
properties[name] = Int(PropertyType.Data.rawValue)
} else if mirror.valueType is Optional<Object>.Type {
properties[name] = Int(PropertyType.Object.rawValue)
} else if mirror.valueType is RealmOptional<Int>.Type ||
mirror.valueType is RealmOptional<Int8>.Type ||
mirror.valueType is RealmOptional<Int16>.Type ||
mirror.valueType is RealmOptional<Int32>.Type ||
mirror.valueType is RealmOptional<Int64>.Type {
properties[name] = Int(PropertyType.Int.rawValue)
} else if mirror.valueType is RealmOptional<Float>.Type {
properties[name] = Int(PropertyType.Float.rawValue)
} else if mirror.valueType is RealmOptional<Double>.Type {
properties[name] = Int(PropertyType.Double.rawValue)
} else if mirror.valueType is RealmOptional<Bool>.Type {
properties[name] = Int(PropertyType.Bool.rawValue)
} else if mirror.value as? RLMOptionalBase != nil {
throwRealmException("'\(mirror.valueType)' is not a a valid RealmOptional type.")
} else if mirror.disposition == .Optional {
properties[name] = NSNull()
}
}
return properties
}
@objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? {
return nil
}
}
| apache-2.0 | 720514b0645aea78b991e464c69972d5 | 35.939394 | 125 | 0.650682 | 4.706564 | false | false | false | false |
between40and2/XALG | frameworks/Framework-XALG/Graph/Algo/Traversal/XALG_Algo_Graph_Traversal_base.swift | 1 | 1273 | //
// XALG_Algo_Graph_Traversal_base.swift
// XALG
//
// Created by Juguang Xiao on 26/03/2017.
//
import Swift
class XALG_Algo_Graph_Traversal_base<G : XALG_ADT_Graph>: XALG_Algo_Graph_base<G> {
var startVertex : VertexType?
typealias VertexType = G.VertexType
var callback_visit : ((XALG_Visit_Vertex<VertexType>) -> Void)?
func travel() throws {
guard graph != nil else { throw XALG_Error_Graph_Algo.graphAbsent }
guard let v_s = startVertex else { throw XALG_Error_Graph_Algo.startVertexAbsent }
if usesRecursion {
recursive_forVertex(v_s)
}else {
iterative_forVertex(v_s)
}
}
func recursive_forVertex(_ v: VertexType) -> Void
{
}
func iterative_forVertex(_ v: VertexType) -> Void
{
}
var usesRecursion : Bool = true
internal var _recursive_depth : Int = 0
var visit_ = [XALG_Visit_Vertex<VertexType>]()
func handleVertex(_ v: VertexType, depth: Int) {
let visit = XALG_Visit_Vertex<VertexType>()
visit.vertex = v
visit.depth = depth // vertex_distance_[v]!
self.callback_visit?(visit)
visit_.append(visit)
}
}
| mit | 6c9b27f946285fe7651eba64930eb08e | 23.480769 | 90 | 0.578162 | 4.003145 | false | false | false | false |
Felix0805/Notes | Notes/Notes/RemindersDetailViewController.swift | 1 | 4953 | //
// ReminderDetailViewController.swift
// Notes
//
// Created by Apple on 2017/1/13.
// Copyright © 2017年 FelixXiao. All rights reserved.
//
import Foundation
import UIKit
class RemindersDetailViewController: UIViewController {
@IBOutlet weak var ReminderDetail: UIView!
@IBOutlet weak var titleItem: UITextField!
@IBOutlet weak var contentsItem: UITextView!
@IBOutlet weak var levelItem: UISlider!
@IBOutlet weak var dateItem: UIDatePicker!
var reminder: RemindersModel?
override func viewDidLoad() {
super.viewDidLoad()
if(reminder == nil) {
titleItem.placeholder = "Title"
}
else {
titleItem.text = reminder?.title
contentsItem.text = reminder?.content
dateItem.setDate((reminder?.date)!, animated: false)
levelItem.setValue(float_t((reminder?.level)!)/10.0, animated: true)
}
let swipe = UISwipeGestureRecognizer(target:self, action:#selector(swipe(_:)))
swipe.direction = .left
self.view.addGestureRecognizer(swipe)
let swipe2 = UISwipeGestureRecognizer(target:self, action:#selector(swipe2(_:)))
swipe2.direction = .right
self.view.addGestureRecognizer(swipe2)
let swipe3 = UISwipeGestureRecognizer(target:self, action:#selector(swipe3(_:)))
swipe3.direction = .up
self.view.addGestureRecognizer(swipe3)
let swipe4 = UISwipeGestureRecognizer(target:self, action:#selector(swipe4(_:)))
swipe4.direction = .down
self.view.addGestureRecognizer(swipe4)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func save(_ sender: AnyObject) {
if(reminder == nil) {
reminder = RemindersModel(title: titleItem.text!, content: contentsItem.text!, date:dateItem.date, level: Int(levelItem.value * 10))
remindersList.append(reminder!)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
var array = NSMutableArray()
var num = 0
let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/reminders.dat"
remindersList.sort(by: reminderSort)
for item in remindersList {
array.insert(item.title, at: num)
num = num + 1
array.insert(item.content, at: num)
num = num + 1
array.insert(formatter.string(from: item.date), at: num)
num = num + 1
array.insert(String(item.level), at: num)
num = num + 1
}
NSKeyedArchiver.archiveRootObject(array, toFile: filePath)
}
else {
reminder?.title = titleItem.text!
reminder?.content = contentsItem.text!
reminder?.level = Int(levelItem.value * 10)
reminder?.date = dateItem.date
var array = NSMutableArray()
var num = 0
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/reminders.dat"
remindersList.sort(by: reminderSort)
for item in remindersList {
array.insert(item.title, at: num)
num = num + 1
array.insert(item.content, at: num)
num = num + 1
array.insert(formatter.string(from: item.date), at: num)
num = num + 1
array.insert(String(item.level), at: num)
num = num + 1
}
NSKeyedArchiver.archiveRootObject(array, toFile: filePath)
}
}
func swipe(_ recognizer:UISwipeGestureRecognizer){
self.view.endEditing(true)
}
func swipe2(_ recognizer:UISwipeGestureRecognizer){
self.view.endEditing(true)
}
func swipe3(_ recognizer:UISwipeGestureRecognizer){
self.view.endEditing(true)
}
func swipe4(_ recognizer:UISwipeGestureRecognizer){
self.view.endEditing(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 | c97c7aed8af8a7385420fcd0fc193daf | 34.106383 | 190 | 0.59798 | 5.040733 | false | false | false | false |
sahara108/Utility | Table/BEBaseViewController.swift | 1 | 2145 | //
// BEBaseViewController.swift
// BlogExample-AssociatedType
//
// Created by Nguyen Tuan on 5/27/17.
// Copyright © 2017 helo. All rights reserved.
//
import UIKit
public class BEBaseViewController<T : BECellDataSource>: UIViewController, UITableViewDataSource, UITableViewDelegate {
var dataSource: [T] = []
var tableView: UITableView
init(tableView tb: UITableView) {
tableView = tb
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func loadView() {
tableView.rowHeight = 60
view = tableView
}
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
T.register(tableView: tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
//clear empty cell
tableView.tableFooterView = UIView()
tableView.reloadData()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - TableView
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let content = dataSource[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: content.cellIdentifier())!
if let signUpCell = cell as? BECellRender {
signUpCell.renderCell(data: content)
}
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let content = dataSource[indexPath.row]
let dynamicHeight = content.cellHeight()
return dynamicHeight > 0 ? dynamicHeight : tableView.rowHeight
}
}
| mit | 78816477d7196b9c590a986bc18f7382 | 28.777778 | 119 | 0.642724 | 5.280788 | false | false | false | false |
wavecos/curso_ios_3 | SuperMarioBook/SuperMarioBook/Service/ServiceProvider.swift | 1 | 5288 | //
// ServiceProvider.swift
// SuperMarioBook
//
// Created by onix on 11/1/14.
// Copyright (c) 2014 tekhne. All rights reserved.
//
import Foundation
import UIKit
class ServiceProvider {
class func characteres() -> [Character] {
let bowser = Character(name: "Bowser",
console: "NES",
year: 1988,
notes: "El archienemigo de Mario es Bowser, también conocido como Rey Koopa, el villano principal de la gran mayoría de los juegos de Mario. Apareció por primera vez en Super Mario Bros. Bowser es un ser maligno, brutal y despiadado que ha secuestrado a la princesa Peach y tratado de conquistar el Reino Champiñón varias veces, pero Mario siempre lo ha derrotado. A pesar de esto, Mario y Bowser siempre han unido fuerzas para combatir a una amenaza mayor.",
image: UIImage(named: "bowser")!)
let donkeyKong = Character(name: "Donkey Kong",
console: "SNES",
year: 1987,
notes: "El primer enemigo de Mario fue Donkey Kong, un gorila que secuestra a su novia Pauline. Donkey Kong apareció por primera vez en el juego del mismo nombre. En dicho juego, Mario tenía que saltar los barriles que lanzaba, y subir escaleras para llegar a la parte superior de la pantalla donde se encontraban ambos. Todos pensaban que Donkey Kong era quien secuestraba a Pauline en este juego, pero posteriormente Rare aclaró que en realidad éste era Cranky y Donkey Kong su hijo, quien lo salvaba en Donkey Kong Jr.",
image: UIImage(named: "donkeykong")!)
let koopaTroopa = Character(name: "Koopa Troopa",
console: "N64",
year: 1992,
notes: "Los Koopa Troopas son tortugas evolucionadas y ayudantes de Bowser, aparecieron por primera vez en Super Mario Bros. (1985). Pueden ser de distintos colores, si tiene caparazón verde no se detiene al borde de una plataforma o precipicio y el de caparazón rojo si lo hace (claro en juegos con movimientos 2D como Super Mario Bros). Una diferencia entre los goombas y los koopa troopas es que a los koopas, Mario les tiene que saltar dos veces para acabarlos, antiguamente caminaban en cuatro patas pero ahora se los ve en dos patas usando zapatos y con pulgares opuestos. También existen koopas con alas denominados Paratroopas, aunque en los juegos clásicos de Mario solo daban saltos, en los juegos mas modernos se los ve volando sin tocar el suelo en ningún momento. Su líder es Bowser (Rey Koopa).",
image: UIImage(named: "koopa")!)
let luigi = Character(name: "Luigi",
console: "NES",
year: 1982,
notes: "Es el hermano menor de Mario, su primera aparición fue en el juego Mario Bros. en 1983. Se dice que es tímido y cobarde, pero en algunos juegos demuestra que tiene valentía suficiente. En Luigi's Mansion para la GameCube tiene que rescatar a su hermano Mario de una mansión encantada plagada de fantasmas, Luigi tuvo que enfrentarse a sus temores para rescatar a su hermano, y desde entonces siempre se le ha identificado a Luigi con \"su\" mansión.",
image: UIImage(named: "luigi")!)
let mario = Character(name: "Mario",
console: "NES",
year: 1980,
notes: "Es un personaje ficticio diseñado por el japonés Shigeru Miyamoto, para la compañía Nintendo. A partir de su aparición en videojuegos, películas y series televisivas, se ha convertido en el icono emblemático de Nintendo, llegando a ser uno de los personajes más famosos y conocidos de videojuegos de todos los tiempos junto a su hermano menor Luigi, quien es su compañero ícono en diversos juegos y lo ayuda a cumplir su misión, y también ha sido el único protagonista en la saga inspirada en el universo de su hermano Mario.",
image: UIImage(named: "mario")!)
let peach = Character(name: "Princesa Peach",
console: "Wii",
year: 1997,
notes: "La Princesa Peach es la princesa del Reino Champiñón. Apareció por primera vez en Super Mario Bros. en 1985. Se dice que ella y Mario son pareja. Ha sido secuestrada por Bowser en numerosas ocasiones, siendo siempre rescatada por Mario. En el año 2006 se cambiaron roles para ser ella quién rescate a Mario en el juego Super Princess Peach para la consola portátil Nintendo DS. Otra aparición en los videojuegos ha sido, por el momento en el juego New Super Mario Bros. U siendo en este juego secuestrada por Bowser en su propio castillo. En Super Mario 3D World,al no ser secuestrada por Bowser, aparece como personaje jugable.",
image: UIImage(named: "peach")!)
let toad = Character(name: "Toad",
console: "N64",
year: 1993,
notes: "Toad es un pequeño humanoide con la cabeza en forma de champiñón. Es el fiel servidor y protector de la princesa Peach. Debido a su nula fuerza y tamaño, siempre termina por suplicar a Mario que sea él quien rescate a Peach cada vez que es raptada. Su frase \"Thank you Mario, but our princess is in another castle\" (en español: \"Muchas gracias Mario, pero nuestra princesa está en otro castillo\"), es conocida por todos los seguidores del fontanero. Apareció por primera vez en Super Mario Bros.",
image: UIImage(named: "toad")!)
return [bowser, donkeyKong, koopaTroopa, luigi, mario, peach, toad]
}
}
| apache-2.0 | e55e3d75576c7bbbd1e988823e797f94 | 77.208955 | 816 | 0.737214 | 3.318556 | false | false | false | false |
tootbot/tootbot | Tootbot/Source/Client/ApplicationProperties.swift | 1 | 2246 | //
// Copyright (C) 2017 Tootbot Contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
public struct ApplicationProperties {
public var clientName: String
public var redirectURI: String
public var scopes: Set<ApplicationScope>
public var websiteURL: URL?
public init(clientName: String, redirectURI: String, scopes: Set<ApplicationScope>, websiteURL: URL?) {
self.clientName = clientName
self.redirectURI = redirectURI
self.scopes = scopes
self.websiteURL = websiteURL
}
}
extension Bundle {
var applicationProperties: ApplicationProperties? {
return applicationProperties(forKey: "ClientProperties")
}
func applicationProperties(forKey key: String) -> ApplicationProperties? {
guard let info = infoDictionary,
let properties = info[key] as? [String: Any],
let clientName = properties["ClientName"] as? String,
let redirectURI = properties["RedirectURI"] as? String,
let scopeString = properties["Scopes"] as? String
else {
return nil
}
let websiteURL: URL?
if let website = info["Website"] as? String {
websiteURL = URL(string: website)
} else {
websiteURL = nil
}
let scopeStrings = scopeString.characters.split(separator: " ").map(String.init)
let scopes = Set(scopeStrings.flatMap({ ApplicationScope(rawValue: $0) }))
return ApplicationProperties(clientName: clientName, redirectURI: redirectURI, scopes: scopes, websiteURL: websiteURL)
}
}
| agpl-3.0 | 8115361642bf8b27d6308bd4d261a134 | 36.433333 | 126 | 0.683882 | 4.728421 | false | false | false | false |
prolificinteractive/Kumi-iOS | Kumi/Core/Animation/CABasicAnimationStyle+JSON.swift | 1 | 1175 | //
// CABasicAnimationStyle+JSON.swift
// Kumi
//
// Created by VIRAKRI JINANGKUL on 6/4/17.
// Copyright © 2017 Prolific Interactive. All rights reserved.
//
extension CABasicAnimationStyle {
public init?(json: JSON) {
var duration: TimeInterval = 0.35
var delay: TimeInterval = 0
var timingFunction: CAMediaTimingFunction = CAMediaTimingFunction(controlPoints: 0, 0, 1, 1)
var isRemovedOnCompletion: Bool = false
if let durationValue = json["duration"].double {
duration = durationValue
}
if let delayValue = json["delay"].double {
delay = delayValue
}
if let timingFunctionValue = CAMediaTimingFunction(json: json["timingFunction"]) {
timingFunction = timingFunctionValue
}
if let isRemovedOnCompletionValue = json["isRemovedOnCompletion"].bool {
isRemovedOnCompletion = isRemovedOnCompletionValue
}
self.init(duration: duration,
delay: delay,
timingFunction: timingFunction,
isRemovedOnCompletion: isRemovedOnCompletion)
}
}
| mit | 43f7222acddd07ab69601b100c0fd3e1 | 26.952381 | 100 | 0.622658 | 5.385321 | false | false | false | false |
NairSurya/Tic-Tac-Toe | Tic-Tac-Toe/CustomButton.swift | 1 | 1740 | //
// CustomButton.swift
// Tic-Tac-Toe
//
// Created by Surya on 25/04/16.
// Copyright © 2016 Surya LLC. All rights reserved.
//
import Foundation
import UIKit
class CustomButton: UIButton {
var value = -1
var cross: UIImage?
var zero: UIImage?
required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
var id = 0;
func setID(id: Int) {
self.id = id;
}
var utils: PubNubUtils?
func setPubNub(utils: PubNubUtils){
self.utils = utils
}
func clear() {
value = -1
self.setImage(nil , forState: .Normal)
}
func initialize() {
cross = UIImage(named: "cross.png")
zero = UIImage(named: "zero.png")
//self.layer.cornerRadius = 15.0;
self.layer.borderWidth = 1.5
self.layer.borderColor = UIColor.redColor().CGColor
//Background
self.backgroundColor = UIColor(white: 1, alpha: 0.0)
}
var myValue: Int?
/** wether its X or O **/
func setMyValue(myVal: Int){
myValue = myVal
}
func setMainValue(value: Int) {
self.value = value
self.setImage(value == 1 ? cross : zero, forState: UIControlState.Normal)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if( value < 0 && GlobalData.instance.myChance == true) {
self.setMainValue(myValue!)
utils?.publish("\(id) \(value) 1 \(GlobalData.macID)")
GlobalData.instance.setMyChance(false)
}
}
} | apache-2.0 | 67cdeb4a553dba264b93b99b645021d4 | 22.2 | 82 | 0.557792 | 4.025463 | false | false | false | false |
nicolaschriste/MoreFoundation | MoreFoundation/Observable/Observable.swift | 1 | 6788 | /// Copyright (c) 2018-19 Nicolas Christe
///
/// 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
/// An observable event
public enum Event<T> {
/// Observable provided a next value
case next(T)
/// Observable did terminates
case terminated
/// `.next` event value, nil if event is not `.next`
public var value: T? {
if case let .next(value) = self {
return value
}
return nil
}
}
// Event are Equatable if value type is Equatable
extension Event: Equatable where T: Equatable {
}
/// Base observable type
public class ObservableType<T> {
/// True if the observable is terminated and will not produce more events.
public fileprivate(set) var terminated = false
/// Subscribe to observable events.
///
/// - Parameter observer: observer to subscribe.
/// - Returns: Disposable. Observer is subscribed until this disposable is deleted.
func subscribe(_ observer: Observer<T>) -> Disposable {
fatal("Must be overriden")
}
}
/// An observer
public class Observer<T> {
/// Observed events handler
public enum EventHandler {
/// All events handler
case onEvent((Event<T>) -> Void)
/// Handler of .next events
case onNext((T) -> Void)
/// Handler of .terminated events
case onTerminated(() -> Void)
}
/// register handlers
private let handlers: [EventHandler]
/// Constructor
///
/// - Parameter handlers: events handlers
public init(_ handlers: [EventHandler]) {
self.handlers = handlers
}
/// Constructor
///
/// - Parameter handlers: events handlers
public convenience init(_ handlers: EventHandler...) {
self.init(handlers)
}
/// Process event
///
/// - Parameter event: event to process
func on(_ event: Event<T>) {
handlers.forEach {
switch ($0, event) {
case let (.onEvent(eventHandler), _):
eventHandler(event)
case let (.onNext(valueHandler), .next(value)):
valueHandler(value)
case let (.onTerminated(terminatedHandler), .terminated):
terminatedHandler()
default: break
}
}
}
}
// Add convenience subscribe
public extension ObservableType {
func subscribe(_ handlers: Observer<T>.EventHandler...) -> Disposable {
return subscribe(Observer(handlers))
}
func subscribe(_ eventHandler: @escaping (Event<T>) -> Void) -> Disposable {
return subscribe(Observer(.onEvent(eventHandler)))
}
}
/// An Observable that generate a sequence of `Event<T>`.
public class Observable<T>: ObservableType<T> {
/// Callback called when the first observer is about to subscribe.
private let willBeObservedCb: () -> Void
/// Callback called when the last observer did unsubscribe.
private let wasObservedCb: () -> Void
/// Map of observers.
private var observers = [ObjectIdentifier: Observer<T>]()
public init(willBeObserved: @escaping () -> Void = {}, wasObserved: @escaping () -> Void = {}) {
self.willBeObservedCb = willBeObserved
self.wasObservedCb = wasObserved
}
deinit {
onTerminated()
}
/// Subscribe to observable events.
///
/// - Parameter observer: observer to subscribe.
/// - Returns: Disposable. Observer is subscribed until this disposable is deleted.
override public func subscribe(_ observer: Observer<T>) -> Disposable {
if observers.isEmpty {
willBeObserved()
}
let identifier = ObjectIdentifier(observer)
observers[identifier] = observer
if terminated {
observer.on(.terminated)
}
return Registration(observable: self, identifier: identifier)
}
/// Send `.next` event to all observers.
///
/// - Parameter value: next value.
public func onNext(_ value: T) {
guard !terminated else {
fatal("onNext called on a terminated observable")
}
self.on(.next(value))
}
/// Send `.terminated` event to all observers.
public func onTerminated() {
guard !terminated else { return }
terminated = true
self.on(.terminated)
}
/// Process events.
///
/// - Parameter event: event to send to observers.
func on(_ event: Event<T>) {
observers.values.forEach {
$0.on(event)
}
}
/// Called when the first observer is about to subscribe
private func willBeObserved() {
self.willBeObservedCb()
}
/// Called when the last observer did unsubscribe
private func wasObserved() {
self.wasObservedCb()
}
/// Unsubscribe an observer
///
/// - Parameter identifier: observer identifier.
private func unsubscribe(_ identifier: ObjectIdentifier) {
observers[identifier] = nil
if observers.isEmpty {
wasObserved()
}
}
/// An observer registration
private class Registration: Disposable {
/// Observabe the observer registered to
private weak var observable: Observable<T>?
/// Observer identifier
private let identifier: ObjectIdentifier
/// Constructor
///
/// - Parameters:
/// - observable: observable the observer registered to
/// - identifier: observer identifier
fileprivate init(observable: Observable<T>, identifier: ObjectIdentifier) {
self.observable = observable
self.identifier = identifier
}
deinit {
observable?.unsubscribe(identifier)
}
}
}
| mit | 08f5410b581526b0e2ecb29c4f232a50 | 29.576577 | 100 | 0.628757 | 4.954745 | false | false | false | false |
techmehra/AJCountryPicker | AJCountryPicker/Source/AJCountryPicker.swift | 1 | 3524 | //
// AJCountryPicker.swift
// AjCountryPicker
//
// Created by Ajay Mehra on 06/08/18.
// Copyright © 2018 Aisha Technologies. All rights reserved.
//
import UIKit
class AJCountryPicker: UIViewController {
// MARK: - IBOutlets
@IBOutlet private var tableView: UITableView!
@IBOutlet private var searchBar: UISearchBar!
@IBOutlet private var searchBarHeightConstraint: NSLayoutConstraint!
// MARK: - Public Properties
public var customCountriesCodes: [String]?
public var showCountryFlags: Bool = true
public var showIndexedSections: Bool = false
public var showSearchBar: Bool = false
public var showCallingCodes: Bool = false
public var country: ((Country) -> ())?
// MARK: - Private properties
private var items: [Country] = []
private var countries: [Country] {
return CountryProvider.countries(customCountriesCode: customCountriesCodes)
}
var isPresented:Bool {
if self.presentingViewController != nil, self.presentingViewController?.presentedViewController == self, self.navigationController?.presentingViewController?.presentedViewController == self.navigationController, self.tabBarController?.presentingViewController is UITabBarController {
return true
}else {
return false
}
}
// MARK: - Private Methods
private func filter(with searchText: String) {
items = countries.filter({ (country) -> Bool in
country.name.compare(searchText, options: [.caseInsensitive, .diacriticInsensitive], range: searchText.startIndex ..< searchText.endIndex) == .orderedSame
})
tableView.reloadData()
}
private func initUI() {
searchBarHeightConstraint.constant = showSearchBar ? 56 : 0
tableView.register(cellType: CountryTableViewCell.self)
items = countries
tableView.tableFooterView = .init()
tableView.reloadData()
}
// MARK: - Overrided Methods
public override func viewDidLoad() {
super.viewDidLoad()
initUI()
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - Table view data source
extension AJCountryPicker: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as CountryTableViewCell
let country: Country = items[indexPath.row]
cell.configure(with: country, showCallingCode: showCallingCodes, showFlag: showCountryFlags)
return cell
}
}
// MARK: - Table view delegate
extension AJCountryPicker: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
country?(items[indexPath.row])
if isPresented {
dismiss(animated: true, completion: nil)
}else {
navigationController?.popViewController(animated: true)
}
}
}
extension AJCountryPicker: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filter(with: searchText)
}
}
| mit | 2beebeeb80c59cdf8a6c81386cc3af20 | 31.321101 | 293 | 0.675844 | 5.28979 | false | false | false | false |
alfishe/mooshimeter-osx | mooshimeter-osx/Device/DeviceCommand.swift | 1 | 15456 | //
// DeviceCommand.swift
// mooshimeter-osx
//
// Created by Dev on 9/21/16.
// Copyright © 2016 alfishe. All rights reserved.
//
import Foundation
class DeviceCommand: NSObject
{
class func getReadCommandCode(type: DeviceCommandType) -> UInt8
{
let result: UInt8 = type.rawValue & 0x7F
return result
}
class func getWriteCommandCode(type: DeviceCommandType) -> UInt8
{
let result: UInt8 = type.rawValue | 0x80
return result
}
/*
* Return max limit allowed for current command type value. For enums - max enumeration index value
*/
class func getCommandPayloadLimit(commandType: DeviceCommandType) -> UInt8?
{
var result: UInt8? = nil
switch commandType
{
case .CRC32:
break
case .Tree:
break
case .Diagnostic:
break
case .PCBVersion:
break
case .Name:
break
case .TimeUTC:
break
case .TimeUTCms:
break
case .Battery:
break
case .Reboot:
result = RebootType.Shipping.rawValue
break
case .SamplingRate:
result = SamplingRateType.Freq8000Hz.rawValue
break
case .SamplingDepth:
result = SamplingDepthType.Depth256.rawValue
break
case .SamplingTrigger:
result = SamplingTriggerType.Continuous.rawValue
break
case .LoggingOn:
break
case .LoggingInterval:
break
case .LoggingStatus:
break
case .LoggingPollDir:
break
case .LoggingInfoIndex:
break
case .LoggingInfoEndTime:
break
case .LoggingInfoBytesNum:
break
case .LoggingStreamIndex:
break
case .LoggingStreamOffset:
break
case .LoggingStreamData:
break
case .Channel1Mapping:
result = Channel1MappingType.Shared.rawValue
break
case .Channel1Range:
break
case .Channel1Analysis:
result = Channel1AnalysisType.Buffer.rawValue
break
case .Channel1Value:
break
case .Channel1Offset:
break
case .Channel1Buf:
break
case .Channel1BufBPS:
break
case .Channel1BufLSBNative:
break
case .Channel2Mapping:
result = Channel2MappingType.Shared.rawValue
break
case .Channel2Range:
break
case .Channel2Analysis:
result = Channel2AnalysisType.Buffer.rawValue
break
case .Channel2Value:
break
case .Channel2Offset:
break
case .Channel2Buf:
break
case .Channel2BufBPS:
break
case .Channel2BufLSBNative:
break
case .Shared:
result = SharedModeType.Diode.rawValue
break
case .RealPwr:
break
}
return result
}
class func getCommandPayload(commandType: DeviceCommandType, value: AnyObject) -> [UInt8]
{
var result = [UInt8]()
let resultType = getResultTypeByCommand(command: commandType.rawValue)
switch resultType
{
case .chooser:
if (value as? DeviceChooser) != nil
{
let chooserValue: UInt8? = getChooserValueForCommand(commandType: commandType, value: value as! DeviceChooser)
if chooserValue != nil
{
result.append(chooserValue!)
}
else
{
print("Unable to serialize chooser")
}
}
break
case .val_U8:
print("Not implemented")
break
case .val_U16:
print("Not implemented")
break
case .val_U32:
print("Not implemented")
break
case .val_S8:
print("Not implemented")
break
case .val_S16:
print("Not implemented")
break
case .val_S32:
print("Not implemented")
break
case .val_STR:
print("Not implemented")
break
case .val_BIN:
print("Not implemented")
break
case .val_FLT:
print("Not implemented")
break
default:
break
}
return result
}
class func getResultTypeByCommand(command: UInt8) -> ResultType
{
var result: ResultType = .notset
switch command
{
case 0:
result = .val_U32
case 1:
result = .val_BIN
case 2:
result = .val_BIN
case 3:
result = .val_U8
case 4:
result = .val_STR
case 5:
result = .val_U32
case 6:
result = .val_U16
case 7:
result = .val_FLT
case 9:
result = .chooser
case 10:
result = .chooser
case 11:
result = .chooser
case 12:
result = .val_U8
case 13:
result = .val_U16
case 14:
result = .val_U8
case 15:
result = .val_U8
case 16:
result = .val_U16
case 17:
result = .val_U32
case 18:
result = .val_U32
case 19:
result = .val_U16
case 20:
result = .val_U32
case 21:
result = .val_BIN
case 22:
result = .chooser
case 23:
result = .val_U8
case 24:
result = .chooser
case 25:
result = .val_FLT
case 26:
result = .val_FLT
case 27:
result = .val_BIN
case 28:
result = .val_U8
case 29:
result = .val_FLT
case 30:
result = .chooser
case 31:
result = .val_U8
case 32:
result = .chooser
case 33:
result = .val_FLT
case 34:
result = .val_FLT
case 35:
result = .val_BIN
case 36:
result = .val_U8
case 37:
result = .val_FLT
case 38:
result = .chooser
case 39:
result = .val_FLT
default:
print("Unknown command code %d", command)
break
}
return result
}
class func getResultSizeType(_ resultType: ResultType) -> Int
{
var result: Int = 0
switch resultType
{
case .plain:
result = 0
case .link:
result = 0
case .chooser:
result = 1
case .val_U8:
result = 1
case .val_U16:
result = 2
case .val_U32:
result = 4
case .val_S8:
result = 1
case .val_S16:
result = 2
case .val_S32:
result = 4
case .val_STR:
result = Constants.DEVICE_COMMAND_PAYLOAD_VARIABLE_LEN
case .val_BIN:
result = Constants.DEVICE_COMMAND_PAYLOAD_VARIABLE_LEN
case .val_FLT:
result = 4
default:
break
}
return result
}
class func getPacketCommandType(data: Data?) -> DeviceCommandType?
{
var result: DeviceCommandType? = nil
if data != nil && data!.count >= 2
{
// Strip first byte from the packet (packet number)
let payloadData = data!.subdata(in: 1..<data!.count)
// Command type is located in the first byte of packet payload
let commandTypeByte: UInt8 = payloadData.first!
result = DeviceCommandType(rawValue: commandTypeByte)
}
return result
}
/**
- parameters:
- data: Packet data bytes
*/
class func getPacketValue(data: Data?) -> (type: ResultType, value: AnyObject)?
{
var result: (type: ResultType, value: AnyObject)? = nil
if data != nil && data!.count > 2
{
// Strip first byte from the packet (packet number)
let payloadData = data!.subdata(in: 1..<data!.count)
// Command type is located in the first byte of packet payload
let commandTypeByte: UInt8 = payloadData.first!
let commandType = DeviceCommandType(rawValue: commandTypeByte)
if commandType != nil
{
var value: AnyObject? = nil
// Resolve result value type based on command type
let valueType = DeviceCommand.getResultTypeByCommand(command: commandType!.rawValue)
let valueData = payloadData.subdata(in: 1..<payloadData.count)
// Parse the value
switch valueType
{
case .val_STR:
if valueData.count >= 2
{
// First two bytes are string length
let length: UInt16 = valueData.to(type: UInt16.self)
if length > 0
{
let stringData = valueData.subdata(in: 2..<2 + Int(length))
value = String(data: stringData, encoding: String.Encoding.utf8) as AnyObject?
}
}
case .chooser:
if valueData.count >= 1
{
value = valueData.to(type: UInt8.self) as AnyObject?
}
case .val_U8:
if valueData.count >= 1
{
value = valueData.to(type: UInt8.self) as AnyObject?
}
case .val_U16:
if valueData.count >= 2
{
value = valueData.to(type: UInt16.self) as AnyObject?
}
case .val_U32:
if valueData.count >= 4
{
value = valueData.to(type: UInt32.self) as AnyObject?
}
case .val_S8:
if valueData.count >= 1
{
value = valueData.to(type: Int8.self) as AnyObject?
}
case .val_S16:
if valueData.count >= 2
{
value = valueData.to(type: Int16.self) as AnyObject?
}
case .val_S32:
if valueData.count >= 4
{
value = valueData.to(type: Int32.self) as AnyObject?
}
case .val_FLT:
if valueData.count >= 4
{
value = valueData.to(type: Float.self) as AnyObject?
}
break
default:
print("getPacketValue - unknown type: \(String(describing: valueType))")
break
}
if value != nil
{
result = (valueType, value!)
}
else
{
print("Unable to parse value for %@", valueType)
}
}
}
return result
}
class func getValue(resultType: ResultType, data: Data) -> AnyObject?
{
var result: AnyObject? = nil
// Parse the value
switch resultType
{
case .chooser:
if data.count >= 1
{
result = data.to(type: UInt8.self) as AnyObject?
}
case .val_U8:
if data.count >= 1
{
result = data.to(type: UInt8.self) as AnyObject?
}
case .val_U16:
if data.count >= 2
{
result = data.to(type: UInt16.self) as AnyObject?
}
case .val_U32:
if data.count >= 4
{
result = data.to(type: UInt32.self) as AnyObject?
}
case .val_S8:
if data.count >= 1
{
result = data.to(type: Int8.self) as AnyObject?
}
case .val_S16:
if data.count >= 2
{
result = data.to(type: Int16.self) as AnyObject?
}
case .val_S32:
if data.count >= 4
{
result = data.to(type: Int32.self) as AnyObject?
}
case .val_FLT:
if data.count >= 4
{
result = data.to(type: Float.self) as AnyObject?
}
break
default:
break
}
return result
}
class func printValue(commandType: DeviceCommandType, valueTuple: (type: ResultType, value: AnyObject)?) -> String
{
var result: String = ""
if valueTuple != nil
{
let type = valueTuple!.type
let value = valueTuple!.value
switch type
{
case .val_STR:
let val: String = value as! String
result = String(val)
case .chooser:
let val: UInt8 = value as! UInt8
result = String(format: "0x%02x", val)
result = result + " " + printChooserValue(commandType: commandType, value: val)
case .val_U8:
let val: UInt8 = value as! UInt8
result = String(format: "0x%02x", val)
case .val_U16:
let val: UInt16 = value as! UInt16
result = String(format: "0x%04x", val)
case .val_U32:
let val: UInt32 = value as! UInt32
result = String(format: "0x%08x", val)
case .val_FLT:
let val: Float = value as! Float
result = String(format: "%0.6f", val)
default:
break
}
}
return result
}
class func printPacketValue(data: Data?) -> String
{
var result: String = ""
let commandType = getPacketCommandType(data: data)
let valueTuple = getPacketValue(data: data)
result = printValue(commandType: commandType!, valueTuple: valueTuple)
return result
}
class func printChooserValue(commandType: DeviceCommandType, value: UInt8) -> String
{
var result: String = ""
let limit = getCommandPayloadLimit(commandType: commandType)
if limit != nil
{
if value > limit!
{
print("CommandType: \(commandType.description) has value: \(value), which is bigger than allowed limit: \(limit!)")
return result
}
}
switch commandType
{
case .Reboot:
result = (RebootType(rawValue: value)?.description)!
case .SamplingRate:
result = (SamplingRateType(rawValue: value)?.description)!
case .SamplingDepth:
result = (SamplingDepthType(rawValue: value)?.description)!
case .SamplingTrigger:
result = (SamplingTriggerType(rawValue: value)?.description)!
case .Channel1Mapping:
result = (Channel1MappingType(rawValue: value)?.description)!
case .Channel1Analysis:
result = (Channel1AnalysisType(rawValue: value)?.description)!
case .Channel2Mapping:
result = (Channel2MappingType(rawValue: value)?.description)!
case .Channel2Analysis:
result = (Channel2AnalysisType(rawValue: value)?.description)!
case .Shared:
result = (SharedModeType(rawValue: value)?.description)!
default:
result = "Chooser not implemented for CommandType: \(String(describing: commandType))"
break
}
return result
}
//MARK: -
//MARK: Send oriented commands
class func getChooserValueForCommand(commandType: DeviceCommandType, value: DeviceChooser) -> UInt8?
{
var result: UInt8? = nil
switch commandType
{
case .Reboot:
result = (value as! RebootType).rawValue
case .SamplingRate:
result = (value as! SamplingRateType).rawValue
case .SamplingDepth:
result = (value as! SamplingDepthType).rawValue
case .SamplingTrigger:
result = (value as! SamplingTriggerType).rawValue
case .Channel1Mapping:
result = (value as! Channel1MappingType).rawValue
case .Channel1Analysis:
result = (value as! Channel1AnalysisType).rawValue
case .Channel2Mapping:
result = (value as! Channel2MappingType).rawValue
case .Channel2Analysis:
result = (value as! Channel2AnalysisType).rawValue
case .Shared:
result = (value as! SharedModeType).rawValue
default:
break
}
return result
}
}
| mit | c6facede747ec7bdafbac04792ba70f5 | 24.212072 | 123 | 0.547137 | 4.347398 | false | false | false | false |
GrouponChina/groupon-up | Groupon UP/Groupon UP/DealTableViewCell.swift | 1 | 6675 | //
// DealTableViewCell.swift
// Groupon UP
//
// Created by Robert Xue on 11/21/15.
// Copyright © 2015 Chang Liu. All rights reserved.
//
import UIKit
import Alamofire
import SnapKit
import AlamofireImage
class DealTableViewCell: UITableViewCell {
private var _cellContentView: UIView!
private var _dealImageView: UIImageView!
private var _dealInfo: UIView!
private var _dealTitle: UILabel!
private var _dealDivision: UILabel!
private var _value: UILabel!
private var _soldQuantityMessage: UILabel!
private var _dealPrice: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubviews()
addLayout()
}
func addSubviews() {
addSubview(cellContentView)
cellContentView.addSubview(dealImageView)
cellContentView.addSubview(dealInfo)
dealInfo.addSubview(dealTitle)
dealInfo.addSubview(dealDivision)
dealInfo.addSubview(value)
dealInfo.addSubview(soldQuantityMessage)
dealInfo.addSubview(dealPrice)
}
func addLayout() {
cellContentView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self).offset(UPDeal.offset)
make.left.equalTo(self).offset(UPDeal.offset)
make.right.equalTo(self).offset(-UPDeal.offset)
make.bottom.equalTo(self).offset(-UPDeal.offset)
make.height.equalTo(285)
}
dealImageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(cellContentView)
make.left.equalTo(cellContentView)
make.right.equalTo(cellContentView)
make.height.equalTo(UPDeal.imageHeight)
make.bottom.lessThanOrEqualTo(self).offset(-UPDeal.dealInfoHeight)
}
dealInfo.snp_makeConstraints { (make) -> Void in
make.top.equalTo(dealImageView.snp_bottom)
make.left.equalTo(dealImageView.snp_left)
make.right.equalTo(dealImageView.snp_right)
}
dealTitle.snp_makeConstraints { (make) -> Void in
make.top.equalTo(dealInfo).offset(UPDeal.titleOffset)
make.left.equalTo(dealInfo).offset(UPDeal.titleOffset)
make.right.equalTo(dealInfo).offset(-UPDeal.titleOffset)
}
dealDivision.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(soldQuantityMessage.snp_top).offset(-2)
make.left.equalTo(dealTitle.snp_left)
make.height.equalTo(UPDeal.divisionHeight)
}
value.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(dealPrice.snp_top)
make.right.equalTo(dealTitle.snp_right)
make.height.equalTo(UPDeal.valueHeight)
}
soldQuantityMessage.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(cellContentView.snp_bottom).offset(-12)
make.left.equalTo(dealDivision.snp_left)
}
dealPrice.snp_makeConstraints { (make) -> Void in
make.right.equalTo(dealTitle.snp_right)
make.bottom.equalTo(cellContentView.snp_bottom).offset(-UPDeal.offset)
}
backgroundColor = UIColor.clearColor()
selectionStyle = .None
}
func setDeal(deal: Deal) {
let imageNsUrl = NSURL(string: deal.dealImages.grid6ImageUrl)!
dealImageView.af_setImageWithURL(imageNsUrl)
dealTitle.text = deal.announcementTitle
dealDivision.text = deal.divisionId
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: deal.value)
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
value.attributedText = attributeString
soldQuantityMessage.text = deal.soldQuantityMessage + " Bought"
dealPrice.text = deal.price
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
extension DealTableViewCell {
var cellContentView: UIView {
if _cellContentView == nil {
_cellContentView = UIView()
_cellContentView.backgroundColor = UIColor.whiteColor()
_cellContentView.layer.shadowColor = UIColor.grayColor().CGColor
_cellContentView.layer.shadowOpacity = 1
_cellContentView.layer.shadowOffset = CGSizeZero
_cellContentView.layer.shadowRadius = 2
_cellContentView.translatesAutoresizingMaskIntoConstraints = true
}
return _cellContentView
}
var dealImageView: UIImageView {
if _dealImageView == nil {
_dealImageView = UIImageView()
_dealImageView.contentMode = .ScaleToFill
}
return _dealImageView
}
var dealInfo: UIView {
if _dealInfo == nil {
_dealInfo = UIView()
_dealInfo.backgroundColor = UIColor.whiteColor()
}
return _dealInfo
}
var dealTitle: UILabel {
if _dealTitle == nil {
_dealTitle = UILabel()
_dealTitle.font = UPDeal.titleFont
_dealTitle.numberOfLines = 2
}
return _dealTitle
}
var dealDivision: UILabel {
if _dealDivision == nil {
_dealDivision = UILabel()
_dealDivision.font = UPDeal.otherFont
_dealDivision.textColor = UPDeal.otherFontColor
}
return _dealDivision
}
var value: UILabel {
if _value == nil {
_value = UILabel()
_value.font = UPDeal.otherFont
_value.textColor = UPDeal.otherFontColor
}
return _value
}
var soldQuantityMessage: UILabel {
if _soldQuantityMessage == nil {
_soldQuantityMessage = UILabel()
_soldQuantityMessage.font = UPDeal.otherFont
_soldQuantityMessage.textColor = UPDeal.otherFontColor
}
return _soldQuantityMessage
}
var dealPrice: UILabel {
if _dealPrice == nil {
_dealPrice = UILabel()
_dealPrice.font = UPDeal.priceFont
_dealPrice.textColor = UPDeal.priceFontColor
}
return _dealPrice
}
} | apache-2.0 | 29de239b2f962243874a141adde780ba | 30.937799 | 128 | 0.61837 | 5.075285 | false | false | false | false |
square/wire | wire-library/wire-runtime-swift/src/main/swift/ProtoCodable+Implementations.swift | 1 | 3744 | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
// MARK: -
extension Bool : ProtoCodable {
// MARK: - ProtoDecodable
public static var protoSyntax: ProtoSyntax? { nil }
public init(from reader: ProtoReader) throws {
self = try reader.readVarint32() == 0 ? false : true
}
// MARK: - ProtoEncodable
public static var protoFieldWireType: FieldWireType { .varint }
/** Encode a `bool` field */
public func encode(to writer: ProtoWriter) throws {
writer.write(self ? UInt8(1) : UInt8(0))
}
}
// MARK: -
extension Data : ProtoCodable {
// MARK: - ProtoDecodable
public static var protoSyntax: ProtoSyntax? { nil }
public init(from reader: ProtoReader) throws {
self = try reader.readData()
}
// MARK: - ProtoEncodable
/** Encode a `bytes` field */
public func encode(to writer: ProtoWriter) throws {
writer.write(self)
}
}
// MARK: -
extension Double : ProtoCodable {
// MARK: - ProtoDecodable
public static var protoSyntax: ProtoSyntax? { nil }
public init(from reader: ProtoReader) throws {
self = try Double(bitPattern: reader.readFixed64())
}
// MARK: - ProtoEncodable
public static var protoFieldWireType: FieldWireType { .fixed64 }
/** Encode a `double` field */
public func encode(to writer: ProtoWriter) throws {
writer.writeFixed64(self.bitPattern)
}
}
// MARK: -
extension Float : ProtoCodable {
// MARK: - ProtoDecodable
public static var protoSyntax: ProtoSyntax? { nil }
public init(from reader: ProtoReader) throws {
self = try Float(bitPattern: reader.readFixed32())
}
// MARK: - ProtoEncodable
public static var protoFieldWireType: FieldWireType { .fixed32 }
/** Encode a `float` field */
public func encode(to writer: ProtoWriter) throws {
writer.writeFixed32(self.bitPattern)
}
}
// MARK: -
extension String : ProtoCodable {
// MARK: - ProtoDecodable
public static var protoSyntax: ProtoSyntax? { nil }
/** Reads a `string` field value from the stream. */
public init(from reader: ProtoReader) throws {
// Credit to the SwiftProtobuf project for this implementation.
let buffer = try reader.readBuffer()
var parser = Unicode.UTF8.ForwardParser()
// Verify that the UTF-8 is valid.
var iterator = buffer.makeIterator()
loop: while true {
switch parser.parseScalar(from: &iterator) {
case .valid:
break
case .error:
throw ProtoDecoder.Error.invalidUTF8StringData(Data(buffer))
case .emptyInput:
break loop
}
}
// This initializer is fast but does not reject broken
// UTF-8 (which is why we validate the UTF-8 above).
self = String(decoding: buffer, as: Unicode.UTF8.self)
}
// MARK: - ProtoEncodable
/** Encode a `string` field */
public func encode(to writer: ProtoWriter) throws {
var copy = self
copy.withUTF8 {
writer.write(UnsafeRawBufferPointer($0))
}
}
}
| apache-2.0 | f03e2f16a26e5433901709d943704d9c | 23.794702 | 76 | 0.636752 | 4.446556 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/views/controls/FeedbackButton.swift | 1 | 2545 | //
// FeedbackButton.swift
// SjekkUt
//
// Created by Henrik Hartz on 31/08/16.
// Copyright © 2016 Den Norske Turistforening. All rights reserved.
//
import Foundation
import uservoice_iphone_sdk
class FeedbackButton: DntTrackButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
trackingIdentifier = "Bruker trykket tilbakemelding"
setupFeedback()
}
func setupFeedback() {
addTarget(self, action: #selector(feedbackClicked), for: .touchUpInside)
setTitleColor(.white, for: .normal)
}
@objc func feedbackClicked(_ sender: AnyObject) {
if let config = UVConfig.init(site:"dnt.uservoice.com") {
config.showKnowledgeBase = false
config.showForum = false
config.showPostIdea = false
config.topicId = 138151
var extraTicketInfo = ""
guard let current = DntNavigationController.current?.topViewController else {
DntApi.instance.logErrorMessage("failed to present feedback button")
return
}
if let versionString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,
let buildString = Bundle.main.infoDictionary?["CFBundleVersion"] as? String{
extraTicketInfo += "DNT SjekkUT for iOS \(versionString) (\(buildString))"
}
if let currentTrack = current as? DntTrackViewController,
let params = currentTrack.trackingParameters,
let theJSONData = try? JSONSerialization.data(withJSONObject: params, options: []),
let theJSONText = String(data: theJSONData, encoding: .utf8) {
extraTicketInfo += "\n\(theJSONText)"
}
if let pos = Location.instance.currentLocation {
extraTicketInfo += "\n\(pos)"
}
config.extraTicketInfo = extraTicketInfo
if let user = DntUser.current() {
config.identifyUser(withEmail:user.email, name: user.fullName(), guid: user.identifier)
}
UserVoice.initialize(config)
UVStyleSheet.instance().tintColor = DntColor.red()
UserVoice.presentContactUsForm(forParentViewController: current, andConfig: config)
}
}
}
| mit | c37dcc12ab52e0055680bbc8a302a38c | 36.411765 | 108 | 0.572327 | 5.267081 | false | true | false | false |
malt03/DebugHead | DebugHead/Classes/CGRect+Extension.swift | 1 | 3514 | //
// CGRect+Extension.swift
// DebugHead
//
// Created by Koji Murata on 2019/04/08.
//
import Foundation
extension CGRect {
func nearSidePoint(for point: CGPoint) -> CGPoint {
let leftDistance = point.x - left
let topDistance = point.y - top
let rightDistance = right - point.x
let bottomDistance = bottom - point.y
let minDistance = min(leftDistance, topDistance, rightDistance, bottomDistance)
switch minDistance {
case leftDistance: return CGPoint(x: left, y: (top...bottom).nearBound(for: point.y))
case rightDistance: return CGPoint(x: right, y: (top...bottom).nearBound(for: point.y))
case topDistance: return CGPoint(x: (left...right).nearBound(for: point.x), y: top)
case bottomDistance: return CGPoint(x: (left...right).nearBound(for: point.x), y: bottom)
default:
// never come
return origin
}
}
func intersection(from point: CGPoint, velocity: CGPoint) -> CGPoint {
let line = Line(from: point, velocity: velocity)
// if let intersection = intersectionLeft, contains(intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
// if let intersection = intersectionRight, contains(intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
// if let intersection = intersectionTop, contains(intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
// if let intersection = intersectionBottom, contains(intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
if let intersection = line.intersection(x: left),
isOnSide(point: intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
if let intersection = line.intersection(x: right),
isOnSide(point: intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
if let intersection = line.intersection(y: top),
isOnSide(point: intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
if let intersection = line.intersection(y: bottom),
isOnSide(point: intersection) && isSameDirection(velocity: velocity, fromPoint: point, toPoint: intersection) { return intersection }
// never come
return origin
}
var left: CGFloat { return origin.x }
var right: CGFloat { return origin.x + width }
var top: CGFloat { return origin.y }
var bottom: CGFloat { return origin.y + height }
func isOnSide(point: CGPoint) -> Bool {
if left == point.x || right == point.x { return (top...bottom).contains(point.y) }
if top == point.y || bottom == point.y { return (left...right).contains(point.x) }
return false
}
}
extension ClosedRange {
func nearBound(for value: Bound) -> Bound {
if value < lowerBound { return lowerBound }
if value > upperBound { return upperBound }
return value
}
}
fileprivate func isSameDirection(velocity: CGPoint, fromPoint: CGPoint, toPoint: CGPoint) -> Bool {
let velocity2 = CGPoint(x: toPoint.x - fromPoint.x, y: toPoint.y - fromPoint.y)
let x = (velocity.x == 0 && velocity2.x == 0) || (velocity.x * velocity2.x > 0)
let y = (velocity.y == 0 && velocity2.y == 0) || (velocity.y * velocity2.y > 0)
return x && y
}
| mit | 7bc80a1323d01fa9da6771025d67d3d1 | 46.486486 | 174 | 0.699203 | 4.057737 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Analytics/Events/Analytics+CallEvents.swift | 1 | 5184 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
import WireDataModel
enum CallEvent {
case initiated,
received,
answered,
established,
ended(reason: String),
screenSharing(duration: TimeInterval)
}
extension CallEvent {
var eventName: String {
switch self {
case .initiated: return "calling.initiated_call"
case .received: return "calling.received_call"
case .answered: return "calling.joined_call"
case .established: return "calling.established_call"
case .ended: return "calling.ended_call"
case .screenSharing: return "calling.screen_share"
}
}
}
extension Analytics {
func tagCallQualityReview(_ feedback: CallQualitySurveyReview) {
var attributes: [String: NSObject] = [:]
attributes["label"] = feedback.label
attributes["score"] = feedback.score
attributes["ignore-reason"] = feedback.ignoreReason
tagEvent("calling.call_quality_review", attributes: attributes)
}
func tag(callEvent: CallEvent,
in conversation: ZMConversation,
callInfo: CallInfo) {
tagEvent(callEvent.eventName,
attributes: attributes(for: callEvent, callInfo: callInfo, conversation: conversation))
}
private func attributes(for event: CallEvent,
callInfo: CallInfo,
conversation: ZMConversation) -> [String: Any] {
var attributes = conversation.attributesForConversation
attributes.merge(attributesForUser(in: conversation), strategy: .preferNew)
attributes.merge(attributesForParticipants(in: conversation), strategy: .preferNew)
attributes.merge(attributesForCallParticipants(with: callInfo), strategy: .preferNew)
attributes.merge(attributesForVideo(with: callInfo), strategy: .preferNew)
attributes.merge(attributesForDirection(with: callInfo), strategy: .preferNew)
switch event {
case .ended(reason: let reason):
attributes.merge(attributesForSetupTime(with: callInfo), strategy: .preferNew)
attributes.merge(attributesForCallDuration(with: callInfo), strategy: .preferNew)
attributes.merge(attributesForVideoToogle(with: callInfo), strategy: .preferNew)
attributes.merge(["reason": reason], strategy: .preferNew)
case .screenSharing(let duration):
attributes["screen_share_direction"] = "incoming"
attributes["screen_share_duration"] = Int(round(duration / 5)) * 5
default:
break
}
return attributes
}
private func attributesForUser(in conversation: ZMConversation) -> [String: Any] {
var userType: String
if SelfUser.current.isWirelessUser {
userType = "temporary_guest"
} else if SelfUser.current.isGuest(in: conversation) {
userType = "guest"
} else {
userType = "user"
}
return ["user_type": userType]
}
private func attributesForVideoToogle(with callInfo: CallInfo) -> [String: Any] {
return ["AV_switch_toggled": callInfo.toggledVideo ? true : false]
}
private func attributesForVideo(with callInfo: CallInfo) -> [String: Any] {
return ["call_video": callInfo.video]
}
private func attributesForDirection(with callInfo: CallInfo) -> [String: Any] {
return ["direction": callInfo.outgoing ? "outgoing" : "incoming"]
}
private func attributesForParticipants(in conversation: ZMConversation) -> [String: Any] {
return ["conversation_participants": conversation.localParticipants.count]
}
private func attributesForCallParticipants(with callInfo: CallInfo) -> [String: Any] {
return ["conversation_participants_in_call_max": callInfo.maximumCallParticipants]
}
private func attributesForSetupTime(with callInfo: CallInfo) -> [String: Any] {
guard let establishedDate = callInfo.establishedDate, let connectingDate = callInfo.connectingDate else {
return [:]
}
return ["setup_time": Int(establishedDate.timeIntervalSince(connectingDate))]
}
private func attributesForCallDuration(with callInfo: CallInfo) -> [String: Any] {
guard let establishedDate = callInfo.establishedDate else {
return [:]
}
return ["duration": Int(-establishedDate.timeIntervalSinceNow)]
}
}
| gpl-3.0 | 42da78fd32322e6d5f28144503583428 | 36.294964 | 113 | 0.667245 | 4.804449 | false | false | false | false |
einsteinx2/iSub | Carthage/Checkouts/KSHLSPlayer/KSHLSPlayer/KSHLSView/Streaming/Provider/KSStreamProvider.swift | 1 | 2570 | //
// KSStreamProvider.swift
// KSHLSPlayer
//
// Created by Ken Sun on 2016/1/19.
// Copyright © 2016年 KS. All rights reserved.
//
import Foundation
public class KSStreamProvider {
struct Config {
/**
Number of segments that should be buffered when output is dried.
*/
static let tsPrebufferSize = 2
/**
HLS version in output playlist.
*/
static let HLSVersion = "2"
}
/**
Base URL of TS segment in output playlist.
*/
let serviceUrl: String
internal var outputPlaylist: String?
/**
TS segment input list.
Segments in this list will be added to output if it's filled or not if it's dropped.
*/
internal var segments: [TSSegment] = []
/**
TS segment output list.
Segments in this list will be added to output playlist.
*/
internal var outputSegments: [TSSegment] = []
/**
Segment data cache.
TS filename -> data
*/
internal var segmentData: [String : NSData] = [:]
internal let segmentFence: AnyObject = NSObject()
public init(serviceUrl: String) {
self.serviceUrl = serviceUrl
}
public func isBufferEnough() -> Bool {
return bufferedSegmentCount() >= Config.tsPrebufferSize
}
public func bufferedSegmentCount() -> Int {
var bufferCount = 0
synced(segmentFence, closure: { [unowned self] in
/**
Start from the next segment of last one in output playlist.
If not found, start from first.
*/
let bufferIndex = self.indexOfNextOutputSegment() ?? 0
for i in bufferIndex..<self.segments.count {
if self.segmentData[self.segments[i].filename()] == nil { break }
bufferCount++
}
})
return bufferCount
}
public func cachedSegmentSize() -> Int {
return segmentData.count
}
/**
Provide latest output playlist.
*/
public func providePlaylist() -> String? {
return outputPlaylist
}
/**
Provide TS segment data with specified filename.
*/
public func provideSegment(filename: String) -> NSData? {
return segmentData[filename]
}
internal func indexOfNextOutputSegment() -> Int? {
if let ts = outputSegments.last where ts != segments.last, let index = segments.indexOf(ts) {
return index + 1
}
return nil
}
} | gpl-3.0 | f37c8afbdecb5def123e530a86df5bca | 25.474227 | 101 | 0.571874 | 4.753704 | false | false | false | false |
ken0nek/swift | test/Generics/generic_types.swift | 1 | 8095 | // RUN: %target-parse-verify-swift
protocol MyFormattedPrintable {
func myFormat() -> String
}
func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {}
extension Int : MyFormattedPrintable {
func myFormat() -> String { return "" }
}
struct S<T : MyFormattedPrintable> {
var c : T
static func f(_ a: T) -> T {
return a
}
func f(_ a: T, b: Int) {
return myPrintf("%v %v %v", a, b, c)
}
}
func makeSInt() -> S<Int> {}
typealias SInt = S<Int>
var a : S<Int> = makeSInt()
a.f(1,b: 2)
var b : Int = SInt.f(1)
struct S2<T> {
@discardableResult
static func f() -> T {
S2.f()
}
}
struct X { }
var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}}
enum Optional<T> {
case element(T)
case none
init() { self = .none }
init(_ t: T) { self = .element(t) }
}
typealias OptionalInt = Optional<Int>
var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element
var uniontest2 : Optional<Int> = OptionalInt.none
var uniontest3 = OptionalInt(1)
// FIXME: Stuff that should work, but doesn't yet.
// var uniontest4 : OptInt = .none
// var uniontest5 : OptInt = .Some(1)
func formattedTest<T : MyFormattedPrintable>(_ a: T) {
myPrintf("%v", a)
}
struct formattedTestS<T : MyFormattedPrintable> {
func f(_ a: T) {
formattedTest(a)
}
}
struct GenericReq<
T : IteratorProtocol, U : IteratorProtocol where T.Element == U.Element
> {}
func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element {
var r = r
return r.next()!
}
func testGetFirst(ir: CountableRange<Int>) {
_ = getFirst(ir.makeIterator()) as Int
}
struct XT<T> {
init(t : T) {
prop = (t, t)
}
static func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
class YT<T> {
init(_ t : T) {
prop = (t, t)
}
deinit {}
class func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
struct ZT<T> {
var x : T, f : Float
}
struct Dict<K, V> {
subscript(key: K) -> V { get {} set {} }
}
class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}}
subscript(key: K) -> V { get {} set {} }
}
typealias XI = XT<Int>
typealias YI = YT<Int>
typealias ZI = ZT<Int>
var xi = XI(t: 17)
var yi = YI(17)
var zi = ZI(x: 1, f: 3.0)
var i : Int = XI.f()
i = XI.f()
i = xi.g()
i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}}
i = yi.g()
var xif : (XI) -> () -> Int = XI.g
var gif : (YI) -> () -> Int = YI.g
var ii : (Int, Int) = xi.prop
ii = yi.prop
xi.prop = ii
yi.prop = ii
var d1 : Dict<String, Int>
var d2 : Dictionary<String, Int>
d1["hello"] = d2["world"]
i = d2["blarg"]
struct RangeOfPrintables<
R : Sequence
where
R.Iterator.Element : MyFormattedPrintable
> {
var r : R
func format() -> String {
var s : String
for e in r {
s = s + e.myFormat() + " "
}
return s
}
}
struct Y {}
struct SequenceY : Sequence, IteratorProtocol {
typealias Iterator = SequenceY
typealias Element = Y
func next() -> Element? { return Y() }
func makeIterator() -> Iterator { return self }
}
func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) {
var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}}
var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}}
}
struct HasNested<T> {
init<U>(_ t: T, _ u: U) {}
func f<U>(_ t: T, u: U) -> (T, U) {}
struct InnerGeneric<U> { // expected-error{{generic type 'InnerGeneric' nested}}
init() {}
func g<V>(_ t: T, u: U, v: V) -> (T, U, V) {}
}
struct Inner { // expected-error{{nested in generic type}}
init (_ x: T) {}
func identity(_ x: T) -> T { return x }
}
}
func useNested(_ ii: Int, hni: HasNested<Int>,
xisi : HasNested<Int>.InnerGeneric<String>,
xfs: HasNested<Float>.InnerGeneric<String>) {
var i = ii, xis = xisi
typealias InnerI = HasNested<Int>.Inner
var innerI = InnerI(5)
typealias InnerF = HasNested<Float>.Inner
var innerF : InnerF = innerI // expected-error{{cannot convert value of type 'InnerI' (aka 'HasNested<Int>.Inner') to specified type 'InnerF' (aka 'HasNested<Float>.Inner')}}
_ = innerI.identity(i)
i = innerI.identity(i)
// Generic function in a generic class
typealias HNI = HasNested<Int>
var id = hni.f(1, u: 3.14159)
id = (2, 3.14159)
hni.f(1.5, 3.14159) // expected-error{{missing argument label 'u:' in call}}
hni.f(1.5, u: 3.14159) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Int'}}
// Generic constructor of a generic struct
HNI(1, 2.71828) // expected-warning{{unused}}
HNI(1.5, 2.71828) // expected-error{{'Double' is not convertible to 'Int'}}
// Generic function in a nested generic struct
var ids = xis.g(1, u: "Hello", v: 3.14159)
ids = (2, "world", 2.71828)
xis = xfs // expected-error{{cannot assign value of type 'HasNested<Float>.InnerGeneric<String>' to type 'HasNested<Int>.InnerGeneric<String>'}}
}
var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}}
var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}}
// Check unqualified lookup of inherited types.
class Foo<T> {
typealias Nested = T
}
class Bar : Foo<Int> {
func f(_ x: Int) -> Nested {
return x
}
struct Inner {
func g(_ x: Int) -> Nested {
return x
}
func withLocal() {
struct Local {
func h(_ x: Int) -> Nested {
return x
}
}
}
}
}
extension Bar {
func g(_ x: Int) -> Nested {
return x
}
/* This crashes for unrelated reasons: <rdar://problem/14376418>
struct Inner2 {
func f(_ x: Int) -> Nested {
return x
}
}
*/
}
// Make sure that redundant typealiases (that map to the same
// underlying type) don't break protocol conformance or use.
class XArray : ArrayLiteralConvertible {
typealias Element = Int
init() { }
required init(arrayLiteral elements: Int...) { }
}
class YArray : XArray {
typealias Element = Int
required init(arrayLiteral elements: Int...) {
super.init()
}
}
var yarray : YArray = [1, 2, 3]
var xarray : XArray = [1, 2, 3]
// Type parameters can be referenced only via unqualified name lookup
struct XParam<T> {
func foo(_ x: T) {
_ = x as T
}
static func bar(_ x: T) {
_ = x as T
}
}
var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of 'XParam<Int>'}}
// Diagnose failure to meet a superclass requirement.
class X1 { }
class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}}
class X3 { }
var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}}
protocol P {
associatedtype AssocP
}
protocol Q {
associatedtype AssocQ
}
struct X4 : P, Q {
typealias AssocP = Int
typealias AssocQ = String
}
struct X5<T, U where T: P, T: Q, T.AssocP == T.AssocQ> { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}}
var y: X5<X4, Int> // expected-error{{'X5' requires the types 'AssocP' (aka 'Int') and 'AssocQ' (aka 'String') be equivalent}}
// Recursive generic signature validation.
class Top {}
class Bottom<T : Bottom<Top>> {} // expected-error {{type may not reference itself as a requirement}}
class X6<T> {
let d: D<T>
init(_ value: T) {
d = D(value)
}
class D<T2> { // expected-error{{generic type 'D' nested in type 'X6' is not allowed}}
init(_ value: T2) {}
}
}
// Invalid inheritance clause
struct UnsolvableInheritance1<T : T.A> {}
// expected-error@-1 {{inheritance from non-protocol, non-class type 'T.A'}}
struct UnsolvableInheritance2<T : U.A, U : T.A> {}
// expected-error@-1 {{inheritance from non-protocol, non-class type 'U.A'}}
// expected-error@-2 {{inheritance from non-protocol, non-class type 'T.A'}}
enum X7<T where X7.X : G> { case X } // expected-error{{'X' is not a member type of 'X7<T>'}}
| apache-2.0 | 3529229525bd405d0fd4f90a75832beb | 23.020772 | 176 | 0.620506 | 3.07444 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.