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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jbourjeli/SwiftLabelPhoto | Photos++/UIAlertController+extension.swift | 1 | 1691 | //
// UIAlertController+extension.swift
// Photos++
//
// Created by Joseph Bourjeli on 10/14/16.
// Copyright © 2016 WorkSmarterComputing. All rights reserved.
//
import UIKit
public extension UIAlertController {
public static func alert(title: String, message: String) -> UIAlertController {
let alertController = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
return alertController
}
public static func yesNoAlert(title: String, message: String, destructiveYes: Bool = false, yesHandler: @escaping (UIAlertAction) -> Void) -> UIAlertController {
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes",
style: (destructiveYes ? .destructive : .default),
handler: yesHandler))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
return alert
}
}
extension UIViewController {
public enum AlertType: String {
case error="Error"
case warning="Warning"
case success="Success"
}
public func presentAlert(ofType alertType: AlertType, withMessage message: String) {
self.present(UIAlertController.alert(title: alertType.rawValue, message: message), animated: true, completion: nil)
}
}
| mit | f502a1e56d426a7c586e55a7530c5e90 | 34.957447 | 165 | 0.591124 | 5.28125 | false | false | false | false |
PJayRushton/stats | Stats/CreateSeason.swift | 1 | 1610 | //
// CreateSeason.swift
// Stats
//
// Created by Parker Rushton on 4/4/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import Foundation
struct CreateSeason: Command {
var name: String
var teamId: String
func execute(state: AppState, core: Core<AppState>) {
let ref = StatsRefs.seasonsRef(teamId: teamId).childByAutoId()
let season = Season(id: ref.key, isCompleted: false, name: name, teamId: teamId)
networkAccess.updateObject(at: ref, parameters: season.jsonObject()) { result in
switch result {
case .success:
self.saveSeasonToPlayers(seasonId: season.id, core: core)
core.fire(event: Selected<Season>(season))
self.setSeasonAsCurrent(season, core: core)
case let .failure(error):
core.fire(event: ErrorEvent(error: error, message: "Error saving season"))
}
}
}
private func setSeasonAsCurrent(_ season: Season, core: Core<AppState>) {
guard var currentTeam = core.state.teamState.currentTeam else { return }
currentTeam.currentSeasonId = season.id
core.fire(command: UpdateObject(currentTeam))
}
private func saveSeasonToPlayers(seasonId: String, core: Core<AppState>) {
let players = core.state.playerState.players(for: teamId)
players.forEach { player in
var updatedPlayer = player
updatedPlayer.seasons[seasonId] = player.isSubForCurrentSeason
core.fire(command: UpdateObject(updatedPlayer))
}
}
}
| mit | 2ade5b380b8112d0fc8873840df902b3 | 33.978261 | 90 | 0.63207 | 4.372283 | false | false | false | false |
snazzware/Mergel | HexMatch/StateMachine/GameSceneState.swift | 2 | 2645 | //
// GameSceneState.swift
// HexMatch
//
// Created by Josh McKee on 1/19/16.
// Copyright © 2016 Josh McKee. All rights reserved.
//
import Foundation
import GameKit
class GameSceneState: GKState {
var scene: GameScene
init(scene: GameScene) {
self.scene = scene
}
}
// Occurs once when app starts
class GameSceneInitialState: GameSceneState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return ((stateClass is GameScenePlayingState.Type) || (stateClass is GameSceneRestartState.Type))
}
}
// Sets up a new game
class GameSceneRestartState: GameSceneState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
let result = (stateClass is GameScenePlayingState.Type)
return result
}
override func didEnter(from previousState: GKState?) {
// Start fresh copy of level
self.scene.resetLevel()
// Enter playing state
GameStateMachine.instance!.enter(GameScenePlayingState.self)
}
}
// Player is making move
class GameScenePlayingState: GameSceneState {
override func didEnter(from previousState: GKState?) {
}
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
let result = ((stateClass is GameSceneGameOverState.Type) || (stateClass is GameSceneRestartState.Type) || (stateClass is GameSceneMergingState.Type))
return result
}
}
// Pieces is merging
class GameSceneMergingState: GameSceneState {
override func didEnter(from previousState: GKState?) {
}
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
let result = (stateClass is GameSceneEnemyState.Type)
return result
}
}
// Enemy is making moves
class GameSceneEnemyState: GameSceneState {
override func didEnter(from previousState: GKState?) {
}
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
let result = (stateClass is GameScenePlayingState.Type || (stateClass is GameSceneGameOverState.Type))
return result
}
}
// Game is over
class GameSceneGameOverState: GameSceneState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
let result = ((stateClass is GameSceneRestartState.Type))
return result
}
override func didEnter(from previousState: GKState?) {
self.scene.showGameOver()
}
override func willExit(to nextState: GKState) {
self.scene.hideGameOver()
}
}
| mit | 9ce19e1950ff5eddffe735676a1ef42a | 23.036364 | 158 | 0.652042 | 5.007576 | false | false | false | false |
choefele/CCHTransportClient | CCHTransportClient Example iOS/CCHTransportClient Example iOS/ViewController.swift | 1 | 1806 | //
// ViewController.swift
// CCHTransportClient Example iOS
//
// Created by Hoefele, Claus on 02.02.15.
// Copyright (c) 2015 Claus Höfele. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
let transportClient = CCHTransportDEBahnClient()
var departures: [CCHTransportDeparture]?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Departures Berlin-Friedrichstraße";
self.transportClient.retrieveDeparturesForDate(nil, stationID: "0732531", maxNumberOfResults: 10) { [unowned self] departures, error in
self.departures = departures as? [CCHTransportDeparture]
self.tableView.reloadData()
}
}
}
extension ViewController {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
if let departure = departures?[indexPath.row] {
cell.textLabel?.text = departure.service.name
cell.detailTextLabel?.text = ViewController.stringForDate(departure.event.date)
}
return cell
}
private static func stringForDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
let theDateFormat = NSDateFormatterStyle.ShortStyle
let theTimeFormat = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = theDateFormat
dateFormatter.timeStyle = theTimeFormat
return dateFormatter.stringFromDate(date)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return departures?.count ?? 0
}
}
| mit | d907eb6d8fc7ea6a4046f083a4d80441 | 30.103448 | 143 | 0.677938 | 5.125 | false | false | false | false |
cscalcucci/Swift_Life | Swift_Life/Matrix.swift | 1 | 2229 | //
// Matrix.swift
// Swift_Life
//
// Created by Christopher Scalcucci on 2/11/16.
// Copyright © 2016 Christopher Scalcucci. All rights reserved.
//
import Foundation
public class Matrix<T> {
public let width: Int
public let height: Int
private var elements: [T]
public init(width: Int, height: Int, repeatedValue: T) {
// Check for nil
assert(width >= 0, "Matrix<T> critical error, Matrix.width >= 0")
assert(height >= 0, "Matrix<T> critical error, Matrix.height >= 0")
self.width = width
self.height = height
elements = Array<T>(count: width*height, repeatedValue: repeatedValue)
}
/// Gets an element in the matrix using it's x and y position
public subscript(x: Int, y: Int) -> T {
get {
assert(x >= 0 && x < self.width, "Matrix<T> critical error, X >= 0 && X < Matrix.width")
assert(y >= 0 && y < self.height, "Matrix<T> critical error, X >= 0 && X < Matrix.height")
return elements[x + (y * width)]
}
set(newValue) {
assert(x >= 0 && x < self.width, "Matrix<T> critical error, X >= 0 && X < Matrix.width")
assert(y >= 0 && y < self.height, "Matrix<T> critical error, X >= 0 && X < Matrix.height")
elements[x + (y * width)] = newValue
}
}
}
extension Matrix: SequenceType {
public func generate() -> MatrixGenerator<T> {
return MatrixGenerator(matrix: self)
}
// public func filter<T>(includeElement: (T) -> Bool) -> Matrix<T> {
// return self._elements.filter(includeElement)
// }
}
public class MatrixGenerator<T>: GeneratorType {
private let matrix: Matrix<T>
private var x = 0
private var y = 0
init(matrix: Matrix<T>) {
self.matrix = matrix
}
public func next() -> (x: Int, y: Int, element: T)? {
// Check for nil
if self.x >= matrix.width { return nil }
if self.y >= matrix.height { return nil }
// Extract the element and increase the counters
let returnValue = (x, y, matrix[x, y])
// Increase the counters
++x; if x >= matrix.width { x = 0; ++y }
return returnValue
}
} | mit | 47f52ef9e25d831156583a8c90657646 | 27.576923 | 102 | 0.568671 | 3.700997 | false | false | false | false |
codepython/SwiftStructures | Source/Factories/Sorting.swift | 1 | 6247 | //
// Sorting.swift
// SwiftStructures
//
// Created by Wayne Bishop on 7/2/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
public class Sorting {
var isKeyFound: Bool = false
/*
binary search algorthim. Find the value at the middle index.
note the use of the tuple to organize the upper and lower search bounds.
*/
func binarySearch(var numberList: Array<Int>, key: Int, range:(imin: Int, imax: Int)) {
var midIndex: Double = round(Double((range.imin + range.imax) / 2))
var midNumber = numberList[Int(midIndex)]
//use recursion to reduce the possible search range
if (midNumber > key ) {
binarySearch(numberList, key: key, range: (range.imin, Int(midIndex) - 1))
//use recursion to increase the possible search range
} else if (midNumber < key ) {
binarySearch(numberList, key: key, range: (Int(midIndex) + 1, range.imax))
} else {
isKeyFound = true
println("value \(key) found..")
}
} //end function
/*
insertion sort algorithm - rank set of random numbers lowest to highest by
inserting numbers based on a sorted and unsorted side.
*/
func insertionSort(var numberList: Array<Int>) -> Array<Int> {
var x, y, key : Int
for (x = 0; x < numberList.count; x++) {
//obtain a key to be evaluated
key = numberList[x]
//iterate backwards through the sorted portion
for (y = x; y > -1; y--) {
println("comparing \(key) and \(numberList[y])")
if (key < numberList[y]) {
//remove item from original position
numberList.removeAtIndex(y + 1)
//insert the number at the key position
numberList.insert(key, atIndex: y)
}
}
} //end for
return numberList
} //end function
/*
bubble sort algorithm - rank items from the lowest to highest by swapping
groups of two items from left to right. The highest item in the set will bubble up to the
right side of the set after the first iteration.
*/
func bubbleSort(var numberList: Array<Int>) -> Array<Int> {
//establish the iteration counters
var x, y, z, passes, key : Int
for (x = 0; x < numberList.count; ++x) {
//outer loop is maintained to track how many iterations to pass through the list
passes = (numberList.count - 1) - x;
for (y = 0; y < passes; y++) {
//obtain the key item to sort
key = numberList[y]
println("comparing \(key) and \(numberList[y + 1])")
if (key > numberList[y + 1]) {
//pull out the value to be swapped
z = numberList[y + 1]
//write the key where the previous value was placed
numberList[y + 1] = key
//place the pulled value in the previous position
numberList[y] = z
} //end if
} //end for
} //end for
return numberList
} //end function
// Quick sort works by dividing and conquering
// Firstly it picks a pivot point then looks at all items in the observed array
// and moves values to the left or right of the pivot based on their value
// it works recursively so that either side will be eventually sorted back to the top
func quickSort(var hops:[Int]) -> [Int] {
if (hops.count <= 1) {
return hops
}
var pivot = hops.removeAtIndex(0)
var leftBucket:[Int] = []
var rightBucket:[Int] = []
(hops.count - 1).times { i in
if (hops[i] <= pivot) {
leftBucket.append(hops[i])
} else {
rightBucket.append(hops[i])
}
}
var mergedArray:[Int] = []
mergedArray += quickSort(leftBucket)
mergedArray += [pivot]
mergedArray += quickSort(rightBucket)
return mergedArray
}
// Merge sort works by breaking down each side and sorting as it comes back up
// Each left & right side is sorted by using pointers as to which value should be included
// to sort, as each side is sorted as it comes back up the "tree" we can be sure that our pointers
// can be safely moved left to right whereby the values are increasing
func mergeSort(input:[Int]) -> [Int] {
if (input.count <= 1) {
return input
}
let mid = Int(floor(Double(input.count / 2)))
let left = Array(input[0..<mid])
let right = Array(input[mid..<input.count])
let leftSide = mergeSort(left)
let rightSide = mergeSort(right)
return sortForMergeSort(leftSide, right: rightSide)
}
func sortForMergeSort(left:[Int], right:[Int]) -> [Int] {
var sortedArray:[Int] = []
var leftCount = 0
var rightCount = 0
(left.count + right.count).times { i in
if (leftCount < left.count && (rightCount >= right.count || left[leftCount] <= right[rightCount])) {
sortedArray.append(left[leftCount++])
} else if (rightCount < right.count && (leftCount >= left.count || right[rightCount] < left[leftCount])) {
sortedArray.append(right[rightCount++])
}
}
return sortedArray
}
}
| mit | 9004c4cbc9350e6b24b92bda26f8d457 | 27.13964 | 110 | 0.502161 | 4.801691 | false | false | false | false |
sdhzwm/BaiSI-Swift- | BaiSi/BaiSi/Classes/FriendTrends(关注)/Model/WMCategory.swift | 1 | 828 | //
// WMCategory.swift
// BaiSi
//
// Created by 王蒙 on 15/7/25.
// Copyright © 2015年 wm. All rights reserved.
//
import UIKit
class WMCategory: NSObject {
var count: Int
var id: String
var name: String
var friends = [WMFriend]()
var currentPage = 1
var total = 0
init(dictionary: [String: AnyObject]) {
let countStr = dictionary["count"] as! String
count = Int(countStr)!
id = dictionary["id"] as! String
name = dictionary["name"] as! String
}
static func categoryFromResults(results: [[String : AnyObject]]) -> [WMCategory] {
var channels = [WMCategory]()
for result in results {
channels.append(WMCategory(dictionary: result))
}
return channels
}
}
| apache-2.0 | d3d2aceee43bb03b9654c6f7a0622a66 | 20.051282 | 86 | 0.563946 | 4.105 | false | false | false | false |
StevenDXC/SwiftDemo | SwifExample/Observable+ObjectMapper.swift | 1 | 1458 | //
// Observable+ObjectMapper.swift
// SwiftExample
//
// Created by Miutrip on 2016/12/8.
// Copyright © 2016年 dx. All rights reserved.
//
import RxSwift
import ObjectMapper
/**
* JSON转换错误
*/
struct ZJObjectError : Error {
let domain: String
let code: Int
let message: String
var _domain: String {
return domain
}
var _code: Int {
return code
}
var _message: String {
return message
}
}
// MARK: - 扩展ObservableType 转换String为为对象
public extension ObservableType where E == String {
public func mapObject<T: Mappable>(_ type: T.Type) -> Observable<T> {
return flatMap { response -> Observable<T> in
guard let result = Mapper<T>().map(JSONString:response) else {
let error = ZJObjectError(domain:"ObjectMapper",code:100,message:"JSON转换错误");
throw error;
}
return Observable.just(result);
}
}
public func mapArray<T: Mappable>(_ type: T.Type) -> Observable<Array<T>> {
return flatMap { response -> Observable<Array<T>> in
guard let result = Mapper<T>().mapArray(JSONString:response) else {
let error = ZJObjectError(domain:"ObjectMapper",code:100,message:"JSON转换错误");
throw error;
}
return Observable.just(result);
}
}
}
| mit | 87b39818840c98534abfca2651c5b3e3 | 23.396552 | 93 | 0.575265 | 4.262048 | false | false | false | false |
saeta/penguin | Sources/PenguinGraphs/ParallelExpander.swift | 1 | 12699 | // Copyright 2020 Penguin Authors
//
// 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 PenguinParallel
/// Represents a set of labels and their corresponding weights for use in the expander label
/// propagation algorithm.
///
/// For example, we may have categories {A, B, C}. Vertex 1 is seeded with label A, and vertex 3 is
/// seeded with label C. Because vertex 1 is connected to vertex 2, it will propagate its label A
/// along. Vertex 3 is also connected to vertex 2, and sends its label C along. Vertex 2 thus should
/// have a computed label of (assuming equal weight to edges 1->2 and 3->2) 50% A, and 50% C.
///
/// Note: a LabelBundle must encode the sparsity associated with the presence or absence of labels.
///
/// - SeeAlso: `ParallelGraph.propagateLabels`
public protocol LabelBundle: MergeableMessage {
/// Initializes where every label has `value`.
init(repeating value: Float)
/// Scales the weights of the labels in this LabelBundle by `scalar`.
mutating func scale(by scalar: Float)
/// Returns scaled weights for the labels in `self` by `scalar`.
func scaled(by scalar: Float) -> Self
/// Adds `scalar` to every label.
mutating func conditionalAdd(_ scalar: Float, where hasValue: Self)
/// Update `self`'s value for every label not contained in `self` and contained in `other`.
mutating func fillMissingFrom(_ other: Self)
/// Add `rhs` to the value of every label in `self`'s label set.
static func += (lhs: inout Self, rhs: Float)
/// Add the weights for all labels in `rhs` to the corresponding labels in `lhs`.
static func += (lhs: inout Self, rhs: Self)
/// Divides lhs by rhs.
static func / (lhs: Self, rhs: Self) -> Self
}
extension LabelBundle {
public func scaled(by scalar: Float) -> Self {
var tmp = self
tmp.scale(by: scalar)
return tmp
}
}
/// A label bundle backed by SIMD-based types.
///
/// - SeeAlso: `LabelBundle`
public struct SIMDLabelBundle<SIMDType> where SIMDType: SIMD, SIMDType.Scalar == Float {
/// The weights corresponding to each label.
private var weights: SIMDType
/// A mask to determine whether the weight is valid; -1 if true, 0 otherwise.
private var validWeightsMask: SIMDType.MaskStorage
/// Constructs a `SIMDLabelBundle` with uninitialized weights for all labels in the bundle.
public init() {
weights = .zero
validWeightsMask = .zero
}
/// Constructs a `SIMDLabelBundle` with provided `weights` and `validWeightsMask`.
///
/// - Parameter weights: a vector of weights to be assigned to each label.
/// - Parameter validWeightsMask: a vector where each element is 0 if the label is not assigned a
/// valid weight, or -1 (all bits set to 1 in 2's complement) if the corresponding weight is
/// valid.
public init(weights: SIMDType, validWeightsMask: SIMDType.MaskStorage) {
self.weights = weights
self.validWeightsMask = validWeightsMask
}
/// Constructs a `SIMDLabelBundle` with provided `weights`.
///
/// Note: all label weights are assumed valid. If you have some labels that are invalid, use
/// `init(weights:validWeightsMask:)` to specify which weights are invalid.
///
/// - Parameter weights: a vector of weights to be assigned to each label.
public init(weights: SIMDType) {
self.weights = weights
self.validWeightsMask = ~.zero // All valid.
}
/// Accesses the weight associated with the given index.
public subscript(index: Int) -> Float? {
get {
guard validWeightsMask[index] != 0 else {
return nil
}
return weights[index]
}
set {
if let newValue = newValue {
weights[index] = newValue
validWeightsMask[index] = -1
} else {
weights[index] = 0
validWeightsMask[index] = 0
}
}
}
}
extension SIMDLabelBundle: LabelBundle {
/// Creates a `SIMDLabelBundle` with `value` set for each label's weight.
///
/// All labels are determined to have valid values.
public init(repeating value: Float) {
weights = .init(repeating: value)
validWeightsMask = ~.zero
}
/// Scales the weights of `self` by `scalar`.
public mutating func scale(by scalar: Float) {
weights *= scalar
assertConsistent()
}
/// Adds `scalar` to every weight of `self` where `hasValue` has valid weight labels.
public mutating func conditionalAdd(_ scalar: Float, where hasValue: Self) {
let newWeights = weights + scalar
weights.replace(with: newWeights, where: SIMDMask(hasValue.validWeightsMask))
// TODO: update validWeightsMask for self!
assertConsistent()
}
/// Sets weights for every label to `other`'s where the label is not defined in `self`, and is
/// defined in `other`.
public mutating func fillMissingFrom(_ other: Self) {
let mask = (~validWeightsMask) & other.validWeightsMask
weights.replace(with: other.weights, where: SIMDMask(mask))
validWeightsMask |= mask
assertConsistent()
}
/// Merges `other` into `self` by summing weights.
public mutating func merge(_ other: Self) {
self += other
assertConsistent()
}
/// Adds `rhs` to every defined label's corresponding weight in `lhs`.
public static func += (lhs: inout Self, rhs: Float) {
lhs.weights += rhs
lhs.weights.replace(with: 0, where: .!SIMDMask(lhs.validWeightsMask)) // Reset to 0
lhs.assertConsistent()
}
/// Adds weights for `rhs` into `lhs`.
/// If a given label does not have a defined weight in `lhs`, but does in `rhs`, the label's
/// weight in `lhs` becomes defined with `rhs`'s corresponding weight.
public static func += (lhs: inout Self, rhs: Self) {
lhs.assertConsistent()
rhs.assertConsistent()
lhs.weights += rhs.weights
lhs.validWeightsMask |= rhs.validWeightsMask
lhs.assertConsistent()
}
/// Divide weights in `lhs` by the weights for the corresponding labels in `rhs`.
///
/// - Precondition: `rhs` must have defined weights for every label defined in `lhs`.
public static func / (lhs: Self, rhs: Self) -> Self {
assert(lhs.validWeightsMask == lhs.validWeightsMask & rhs.validWeightsMask)
let weights = lhs.weights / rhs.weights
return Self(weights: weights, validWeightsMask: lhs.validWeightsMask)
}
/// Asserts that internal invariants hold true.
func assertConsistent(file: StaticString = #file, line: UInt = #line) {
assert(
weights.replacing(with: 0, where: SIMDMask(validWeightsMask)) == .zero,
"""
Not all invalid weights were zero in: \(self):
- weights: \(weights)
- mask: \(validWeightsMask)
- unequal at: \(weights.replacing(with: 0, where: SIMDMask(validWeightsMask)) .!= SIMDType.zero)
""", file: file, line: line)
}
}
extension SIMDLabelBundle: CustomStringConvertible {
/// A string representation of `SIMDLabelBundle`.
public var description: String {
var s = "["
for (weightIndex, maskIndex) in zip(weights.indices, validWeightsMask.indices) {
if validWeightsMask[maskIndex] != 0 {
s.append(" \(weights[weightIndex]) ")
} else {
s.append(" <n/a> ")
}
}
s.append("]")
return s
}
}
/// An optionally labeled vertex that can be used in the Expander algorithm for propagating labels
/// across a partially labeled graph.
///
/// - SeeAlso: `ParallelGraph.propagateLabels`
/// - SeeAlso: `ParallelGraph.computeEdgeWeights`
public protocol LabeledVertex {
/// A datatype that stores partially defined labels.
associatedtype Labels: LabelBundle
/// The sum of weights for all incoming edges.
var totalIncomingEdgeWeight: Float { get set }
/// The apriori known label values.
var seedLabels: Labels { get }
/// A prior for how strong the belief in seed labels is.
var prior: Labels { get }
/// The labels that result from the iterated label propagation computation.
var computedLabels: Labels { get set }
}
/// A message used in `ParallelGraph` algorithms to compute the sum of weights for all incoming
/// edges to a vertex.
public struct IncomingEdgeWeightSumMessage: MergeableMessage {
/// The sum of weights.
var value: Float
/// Creates an `IncomingEdgeWeightSumMessage` from `value`.
public init(_ value: Float) {
self.value = value
}
/// Sums weights of `other` with `self`.
public mutating func merge(_ other: Self) {
value += other.value
}
}
extension ParallelGraph where Self: IncidenceGraph, Self.Vertex: LabeledVertex {
/// Sums the weights of incoming edges into every vertex in parallel.
///
/// Vertices with no incoming edges will be assigned a `totalIncomingEdgeWeight` of 0.
public mutating func computeIncomingEdgeWeightSum<
Mailboxes: MailboxesProtocol,
VertexSimilarities: ParallelCapablePropertyMap
>(
using mailboxes: inout Mailboxes,
_ vertexSimilarities: VertexSimilarities
)
where
Mailboxes.Mailbox.Graph == ParallelProjection,
ParallelProjection: IncidenceGraph,
Mailboxes.Mailbox.Message == IncomingEdgeWeightSumMessage,
VertexSimilarities.Value == Float,
VertexSimilarities.Key == EdgeId,
VertexSimilarities.Graph == Self
{
// Send
step(mailboxes: &mailboxes) { (context, vertex) in
assert(context.inbox == nil, "Unexpected message in inbox \(context.inbox!)")
for edge in context.edges {
let edgeWeight = context.getEdgeProperty(for: edge, in: vertexSimilarities)
context.send(IncomingEdgeWeightSumMessage(edgeWeight), to: context.destination(of: edge))
}
}
if !mailboxes.deliver() {
fatalError("No messages sent?")
}
// Receive
step(mailboxes: &mailboxes) { (context, vertex) in
if let incomingSum = context.inbox {
vertex.totalIncomingEdgeWeight = incomingSum.value
} else {
// This is safe (i.e. doesn't trigger a division by 0) because the calculation occurs only
/// when there's incoming messages.
vertex.totalIncomingEdgeWeight = 0
}
vertex.computedLabels = vertex.seedLabels
}
}
/// Propagates labels from a few seed vertices to all connected vertices in `self`.
///
/// This algorithm is based on the paper: S. Ravi and Q. Diao. Large Scale Distributed
/// Semi-Supervised Learning Using Streaming Approximation. AISTATS, 2016.
public mutating func propagateLabels<
Mailboxes: MailboxesProtocol,
VertexSimilarities: ParallelCapablePropertyMap
>(
m1: Float,
m2: Float,
m3: Float,
using mailboxes: inout Mailboxes,
_ vertexSimilarities: VertexSimilarities,
maxStepCount: Int,
shouldExitEarly: (Int, Self) -> Bool = { (_, _) in false }
)
where
Mailboxes.Mailbox.Graph == ParallelProjection,
ParallelProjection: IncidenceGraph,
Mailboxes.Mailbox.Message == Self.Vertex.Labels,
VertexSimilarities.Value == Float,
VertexSimilarities.Key == EdgeId,
VertexSimilarities.Graph == Self
{
for stepNumber in 0..<maxStepCount {
step(mailboxes: &mailboxes) { (context, vertex) in
// Receive the incoming (merged) message.
if let neighborContributions = context.inbox {
// Compute the new computed label bundle for `vertex`.
var numerator = neighborContributions.scaled(by: m2)
numerator += vertex.prior.scaled(by: m3)
numerator += vertex.seedLabels.scaled(by: m1)
var denominator = Self.Vertex.Labels(repeating: m2 * vertex.totalIncomingEdgeWeight + m3)
denominator.conditionalAdd(m1, where: vertex.seedLabels)
var newLabels = numerator / denominator
newLabels.fillMissingFrom(vertex.seedLabels)
vertex.computedLabels = newLabels
}
// Send along our new computed labels to all our neighbors.
for edge in context.edges {
let edgeWeight = context.getEdgeProperty(for: edge, in: vertexSimilarities)
context.send(
vertex.computedLabels.scaled(by: edgeWeight),
to: context.destination(of: edge))
}
}
if !mailboxes.deliver() {
fatalError("Could not deliver messages at step \(stepNumber).")
}
if shouldExitEarly(stepNumber, self) { return }
}
}
}
| apache-2.0 | e4850e7d53947014289666231ca7128c | 35.076705 | 104 | 0.685251 | 4.329697 | false | false | false | false |
fgengine/quickly | Quickly/Compositions/Standart/QTitleShapeComposition.swift | 1 | 4003 | //
// Quickly
//
open class QTitleShapeComposable : QComposable {
public var titleStyle: QLabelStyleSheet
public var shapeModel: QShapeView.Model
public var shapeWidth: CGFloat
public var shapeSpacing: CGFloat
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
titleStyle: QLabelStyleSheet,
shapeModel: QShapeView.Model,
shapeWidth: CGFloat = 16,
shapeSpacing: CGFloat = 4
) {
self.titleStyle = titleStyle
self.shapeModel = shapeModel
self.shapeWidth = shapeWidth
self.shapeSpacing = shapeSpacing
super.init(edgeInsets: edgeInsets)
}
}
open class QTitleShapeComposition< Composable: QTitleShapeComposable > : QComposition< Composable > {
public private(set) lazy var titleView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var shapeView: QShapeView = {
let view = QShapeView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _shapeWidth: CGFloat?
private var _shapeSpacing: CGFloat?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
private var _shapeConstraints: [NSLayoutConstraint] = [] {
willSet { self.shapeView.removeConstraints(self._shapeConstraints) }
didSet { self.shapeView.addConstraints(self._shapeConstraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right)
let titleTextSize = composable.titleStyle.size(width: availableWidth - (composable.shapeWidth + composable.shapeSpacing))
let shapeSzie = composable.shapeModel.size
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + max(titleTextSize.height, shapeSzie.height) + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets || self._shapeSpacing != composable.shapeSpacing {
self._edgeInsets = composable.edgeInsets
self._shapeSpacing = composable.shapeSpacing
self._constraints = [
self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.titleView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.titleView.trailingLayout == self.shapeView.leadingLayout.offset(-composable.shapeSpacing),
self.titleView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.shapeView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.shapeView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.shapeView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom)
]
}
if self._shapeWidth != composable.shapeWidth {
self._shapeWidth = composable.shapeWidth
self._shapeConstraints = [
self.shapeView.widthLayout == composable.shapeWidth
]
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.titleView.apply(composable.titleStyle)
self.shapeView.model = composable.shapeModel
}
}
| mit | 62bfcfb4a65399f0ab6b89c11ae815ca | 41.585106 | 129 | 0.683987 | 5.301987 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetrySdk/Trace/SpanProcessors/BatchSpanProcessor.swift | 1 | 6007 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import OpenTelemetryApi
/// Implementation of the SpanProcessor that batches spans exported by the SDK then pushes
/// to the exporter pipeline.
/// All spans reported by the SDK implementation are first added to a synchronized queue (with a
/// maxQueueSize maximum size, after the size is reached spans are dropped) and exported
/// every scheduleDelayMillis to the exporter pipeline in batches of maxExportBatchSize.
/// If the queue gets half full a preemptive notification is sent to the worker thread that
/// exports the spans to wake up and start a new export cycle.
/// This batchSpanProcessor can cause high contention in a very high traffic service.
public struct BatchSpanProcessor: SpanProcessor {
fileprivate var worker: BatchWorker
public init(spanExporter: SpanExporter, scheduleDelay: TimeInterval = 5, exportTimeout: TimeInterval = 30,
maxQueueSize: Int = 2048, maxExportBatchSize: Int = 512, willExportCallback: ((inout [SpanData]) -> Void)? = nil)
{
worker = BatchWorker(spanExporter: spanExporter,
scheduleDelay: scheduleDelay,
exportTimeout: exportTimeout,
maxQueueSize: maxQueueSize,
maxExportBatchSize: maxExportBatchSize,
willExportCallback: willExportCallback)
worker.start()
}
public let isStartRequired = false
public let isEndRequired = true
public func onStart(parentContext: SpanContext?, span: ReadableSpan) {}
public func onEnd(span: ReadableSpan) {
if !span.context.traceFlags.sampled {
return
}
worker.addSpan(span: span)
}
public func shutdown() {
worker.cancel()
worker.shutdown()
}
public func forceFlush(timeout: TimeInterval? = nil) {
worker.forceFlush(explicitTimeout: timeout)
}
}
/// BatchWorker is a thread that batches multiple spans and calls the registered SpanExporter to export
/// the data.
/// The list of batched data is protected by a NSCondition which ensures full concurrency.
private class BatchWorker: Thread {
let spanExporter: SpanExporter
let scheduleDelay: TimeInterval
let maxQueueSize: Int
let exportTimeout: TimeInterval
let maxExportBatchSize: Int
let willExportCallback: ((inout [SpanData]) -> Void)?
let halfMaxQueueSize: Int
private let cond = NSCondition()
var spanList = [ReadableSpan]()
var queue: OperationQueue
init(spanExporter: SpanExporter, scheduleDelay: TimeInterval, exportTimeout: TimeInterval, maxQueueSize: Int, maxExportBatchSize: Int, willExportCallback: ((inout [SpanData]) -> Void)?) {
self.spanExporter = spanExporter
self.scheduleDelay = scheduleDelay
self.exportTimeout = exportTimeout
self.maxQueueSize = maxQueueSize
halfMaxQueueSize = maxQueueSize >> 1
self.maxExportBatchSize = maxExportBatchSize
self.willExportCallback = willExportCallback
queue = OperationQueue()
queue.name = "BatchWorker Queue"
queue.maxConcurrentOperationCount = 1
}
func addSpan(span: ReadableSpan) {
cond.lock()
defer { cond.unlock() }
if spanList.count == maxQueueSize {
// TODO: Record a counter for dropped spans.
return
}
// TODO: Record a gauge for referenced spans.
spanList.append(span)
// Notify the worker thread that at half of the queue is available. It will take
// time anyway for the thread to wake up.
if spanList.count >= halfMaxQueueSize {
cond.broadcast()
}
}
override func main() {
repeat {
autoreleasepool {
var spansCopy: [ReadableSpan]
cond.lock()
if spanList.count < maxExportBatchSize {
repeat {
cond.wait(until: Date().addingTimeInterval(scheduleDelay))
} while spanList.isEmpty
}
spansCopy = spanList
spanList.removeAll()
cond.unlock()
self.exportBatch(spanList: spansCopy, explicitTimeout: nil)
}
} while true
}
func shutdown() {
forceFlush(explicitTimeout: nil)
spanExporter.shutdown()
}
public func forceFlush(explicitTimeout: TimeInterval?) {
var spansCopy: [ReadableSpan]
cond.lock()
spansCopy = spanList
spanList.removeAll()
cond.unlock()
// Execute the batch export outside the synchronized to not block all producers.
exportBatch(spanList: spansCopy, explicitTimeout: explicitTimeout)
}
private func exportBatch(spanList: [ReadableSpan], explicitTimeout: TimeInterval?) {
let exportOperation = BlockOperation { [weak self] in
self?.exportAction(spanList: spanList)
}
let timeoutTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timeoutTimer.setEventHandler { exportOperation.cancel() }
let maxTimeOut = min(explicitTimeout ?? TimeInterval.greatestFiniteMagnitude, exportTimeout)
timeoutTimer.schedule(deadline: .now() + .milliseconds(Int(maxTimeOut.toMilliseconds)), leeway: .milliseconds(1))
timeoutTimer.activate()
queue.addOperation(exportOperation)
queue.waitUntilAllOperationsAreFinished()
timeoutTimer.cancel()
}
private func exportAction(spanList: [ReadableSpan]) {
stride(from: 0, to: spanList.endIndex, by: maxExportBatchSize).forEach {
var spansToExport = spanList[$0 ..< min($0 + maxExportBatchSize, spanList.count)].map { $0.toSpanData() }
willExportCallback?(&spansToExport)
spanExporter.export(spans: spansToExport)
}
}
}
| apache-2.0 | 70eb10d2e3f10babb34bb1f44d68ef0c | 38.261438 | 191 | 0.654237 | 5.372987 | false | false | false | false |
lenglengiOS/BuDeJie | 百思不得姐/Pods/Charts/Charts/Classes/Renderers/HorizontalBarChartRenderer.swift | 20 | 19741 | //
// HorizontalBarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class HorizontalBarChartRenderer: BarChartRenderer
{
public override init(dataProvider: BarChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(dataProvider: dataProvider, animator: animator, viewPortHandler: viewPortHandler)
}
internal override func drawDataSet(context context: CGContext, dataSet: BarChartDataSet, index: Int)
{
guard let dataProvider = dataProvider, barData = dataProvider.barData else { return }
CGContextSaveGState(context)
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let drawBarShadowEnabled: Bool = dataProvider.isDrawBarShadowEnabled
let dataSetOffset = (barData.dataSetCount - 1)
let groupSpace = barData.groupSpace
let groupSpaceHalf = groupSpace / 2.0
let barSpace = dataSet.barSpace
let barSpaceHalf = barSpace / 2.0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
let barWidth: CGFloat = 0.5
let phaseY = _animator.phaseY
var barRect = CGRect()
var barShadow = CGRect()
var y: Double
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
let e = entries[j]
// calculate the x-position, depending on datasetcount
let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(e.xIndex) + groupSpaceHalf
let values = e.values
if (!containsStacks || values == nil)
{
y = e.value
let bottom = x - barWidth + barSpaceHalf
let top = x + barWidth - barSpaceHalf
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY
}
else
{
left *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = viewPortHandler.contentLeft
barShadow.origin.y = barRect.origin.y
barShadow.size.width = viewPortHandler.contentWidth
barShadow.size.height = barRect.size.height
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
CGContextFillRect(context, barRect)
}
else
{
let vals = values!
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value
let bottom = x - barWidth + barSpaceHalf
let top = x + barWidth - barSpaceHalf
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY
}
else
{
left *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
barShadow.origin.x = viewPortHandler.contentLeft
barShadow.origin.y = barRect.origin.y
barShadow.size.width = viewPortHandler.contentWidth
barShadow.size.height = barRect.size.height
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// fill the stack
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let bottom = x - barWidth + barSpaceHalf
let top = x + barWidth - barSpaceHalf
var right: CGFloat, left: CGFloat
if isInverted
{
left = y >= yStart ? CGFloat(y) : CGFloat(yStart)
right = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
else
{
right = y >= yStart ? CGFloat(y) : CGFloat(yStart)
left = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
// multiply the height of the rect with the phase
right *= phaseY
left *= phaseY
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (k == 0 && !viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height))
{
// Skip to next bar
break
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsBottom(barRect.origin.y))
{
break
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor)
CGContextFillRect(context, barRect)
}
}
}
CGContextRestoreGState(context)
}
internal override func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5
let top = x - barWidth + barspacehalf
let bottom = x + barWidth - barspacehalf
let left = CGFloat(y1)
let right = CGFloat(y2)
rect.origin.x = left
rect.origin.y = top
rect.size.width = right - left
rect.size.height = bottom - top
trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY)
}
public override func getTransformedValues(trans trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: dataProvider!.barData!, phaseY: _animator.phaseY)
}
public override func drawValues(context context: CGContext)
{
// if values are drawn
if (passesCheck())
{
guard let dataProvider = dataProvider, barData = dataProvider.barData else { return }
var dataSets = barData.dataSets
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
let textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right
let valueOffsetPlus: CGFloat = 5.0
var posOffset: CGFloat
var negOffset: CGFloat
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
let dataSet = dataSets[i] as! BarChartDataSet
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
let valueFont = dataSet.valueFont
let valueTextColor = dataSet.valueTextColor
let yOffset = -valueFont.lineHeight / 2.0
let formatter = dataSet.valueFormatter
let trans = dataProvider.getTransformer(dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i)
// if only single values are drawn (sum)
if (!dataSet.isStacked)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break
}
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue
}
let val = entries[j].value
let valueText = formatter!.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if (isInverted)
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: textAlign,
color: valueTextColor)
}
}
else
{
// if each value of a potential stack should be drawn
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
let e = entries[j]
let values = e.values
// we still draw stacked bars, but there is one non-stacked in between
if (values == nil)
{
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break
}
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue
}
let val = e.value
let valueText = formatter!.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if (isInverted)
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: textAlign,
color: valueTextColor)
}
else
{
let vals = values!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: CGFloat(y) * _animator.phaseY, y: 0.0))
}
trans.pointValuesToPixel(&transformed)
for (var k = 0; k < transformed.count; k++)
{
let val = vals[k]
let valueText = formatter!.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if (isInverted)
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
let x = transformed[k].x + (val >= 0 ? posOffset : negOffset)
let y = valuePoints[j].y
if (!viewPortHandler.isInBoundsTop(y))
{
break
}
if (!viewPortHandler.isInBoundsX(x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: textAlign,
color: valueTextColor)
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
guard let dataProvider = dataProvider, barData = dataProvider.barData else { return false }
return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleY
}
} | apache-2.0 | a4a8a4ae34c6af04c3763604c8c05bed | 42.010893 | 155 | 0.414518 | 7.02027 | false | false | false | false |
hffmnn/Swiftz | Swiftz/Chan.swift | 1 | 1895 | //
// Chan.swift
// swiftz
//
// Created by Maxwell Swadling on 5/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
import Darwin
/// Channels are unbounded FIFO streams of values with a read and write terminals. Writing to a
/// channel places a value at the tail end of the channel. Reading from a channel pops a value from
/// its head. If no such value exists the read blocks until a value is placed in the channel.
public final class Chan<A> : K1<A> {
var stream : [A]
let mutex : UnsafeMutablePointer<pthread_mutex_t> = nil
let cond : UnsafeMutablePointer<pthread_cond_t> = nil
let matt : UnsafeMutablePointer<pthread_mutexattr_t> = nil
public override init() {
self.stream = []
super.init()
var mattr : UnsafeMutablePointer<pthread_mutexattr_t> = UnsafeMutablePointer.alloc(sizeof(pthread_mutexattr_t))
mutex = UnsafeMutablePointer.alloc(sizeof(pthread_mutex_t))
cond = UnsafeMutablePointer.alloc(sizeof(pthread_cond_t))
pthread_mutexattr_init(mattr)
pthread_mutexattr_settype(mattr, PTHREAD_MUTEX_RECURSIVE)
matt = UnsafeMutablePointer(mattr)
pthread_mutex_init(mutex, matt)
pthread_cond_init(cond, nil)
stream = []
}
deinit {
mutex.destroy()
cond.destroy()
matt.destroy()
}
/// Writes a value to a channel.
public func write(a : A) {
pthread_mutex_lock(mutex)
stream.append(a)
pthread_mutex_unlock(mutex)
pthread_cond_signal(cond)
}
/// Reads a value from the channel.
public func read() -> A {
pthread_mutex_lock(mutex)
while (stream.isEmpty) {
pthread_cond_wait(cond, mutex)
}
let v = stream.removeAtIndex(0)
pthread_mutex_unlock(mutex)
return v
}
}
/// Write | Writes a value to a channel.
public func <-<A>(chan : Chan<A>, value : A) -> Void {
chan.write(value)
}
/// Read | Reads a value from the channel.
public prefix func <-<A>(chan : Chan<A>) -> A {
return chan.read()
}
| bsd-3-clause | 380c33eedb97979fc97d96d0788959d5 | 26.463768 | 113 | 0.702375 | 3.222789 | false | false | false | false |
bykoianko/omim | iphone/Maps/Core/BackgroundFetchScheduler/BackgroundFetchTask/BackgroundFetchTask.swift | 3 | 2393 | @objc class BackgroundFetchTask: NSObject {
var frameworkType: BackgroundFetchTaskFrameworkType { return .none }
private var backgroundTaskIdentifier = UIBackgroundTaskInvalid
private var completionHandler: BackgroundFetchScheduler.FetchResultHandler?
func start(completion: @escaping BackgroundFetchScheduler.FetchResultHandler) {
completionHandler = completion
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName:description,
expirationHandler: {
self.finish(.failed)
})
if backgroundTaskIdentifier != UIBackgroundTaskInvalid { fire() }
}
fileprivate func fire() {
finish(.failed)
}
fileprivate func finish(_ result: UIBackgroundFetchResult) {
guard backgroundTaskIdentifier != UIBackgroundTaskInvalid else { return }
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
backgroundTaskIdentifier = UIBackgroundTaskInvalid
completionHandler?(result)
}
}
@objc(MWMBackgroundStatisticsUpload)
final class BackgroundStatisticsUpload: BackgroundFetchTask {
override fileprivate func fire() {
Alohalytics.forceUpload(self.finish)
}
override var description: String {
return "Statistics upload"
}
}
@objc(MWMBackgroundEditsUpload)
final class BackgroundEditsUpload: BackgroundFetchTask {
override fileprivate func fire() {
MWMEditorHelper.uploadEdits(self.finish)
}
override var description: String {
return "Edits upload"
}
}
@objc(MWMBackgroundUGCUpload)
final class BackgroundUGCUpload: BackgroundFetchTask {
override var frameworkType: BackgroundFetchTaskFrameworkType { return .full }
override fileprivate func fire() {
MWMUGCHelper.uploadEdits(self.finish)
}
override var description: String {
return "UGC upload"
}
}
@objc(MWMBackgroundDownloadMapNotification)
final class BackgroundDownloadMapNotification: BackgroundFetchTask {
override var frameworkType: BackgroundFetchTaskFrameworkType { return .full }
override fileprivate func fire() {
LocalNotificationManager.shared().showDownloadMapNotificationIfNeeded(self.finish)
}
override var description: String {
return "Download map notification"
}
}
| apache-2.0 | a3b5ed884e2319962741d040d74a501c | 30.486842 | 94 | 0.714166 | 5.780193 | false | false | false | false |
DaiYue/HAMLeetcodeSwiftSolutions | solutions/15_3Sum.playground/Contents.swift | 1 | 1475 | // #15 3Sum https://leetcode.com/problems/3sum/
// 我用的还是 hash 方法,先找第一个数、再找第二个数…… 去重的方法就是要求三个数的序关系,这样就不会重了。
// 看到一个题解用的是先排序,然后先定第一个数,第二个数左头,第三个数右头。然后大了挪小的、小了挪大的…… 这样。算是另一种思路吧。
// 时间复杂度:O(n^2) 空间复杂度:O(n)
class Solution {
func threeSum(_ nums: [Int]) -> [[Int]] {
var numDict : [Int:Int] = [:]
for i in nums {
if numDict[i] == nil {
numDict[i] = 1
} else {
numDict[i] = numDict[i]! + 1
}
}
var results : [[Int]] = []
for (num1, count1) in numDict {
numDict[num1] = count1 - 1
for (num2, count2) in numDict {
let num3 = 0 - num1 - num2
guard count2 > 0 && num1 <= num2 && num2 <= num3 else {
continue
}
if (num2 == num3 && count2 >= 2) || (num2 != num3 && numDict[num3] != nil) {
results.append([num1, num2, num3])
}
}
numDict[num1] = count1
}
return results
}
}
Solution().threeSum([-1, 0, 1, 2, -1, -4])
Solution().threeSum([1,2,-2,-1])
Solution().threeSum([0, 0, 0])
| mit | 699b048d39fc1f029f3dee467bf3697f | 28.97561 | 92 | 0.438568 | 3.103535 | false | false | false | false |
alpascual/DigitalWil | PKHUD/Window.swift | 1 | 2583 | //
// HUDWindow.swift
// PKHUD
//
// Created by Philip Kluz on 6/16/14.
// Copyright (c) 2014 NSExceptional. All rights reserved.
//
import UIKit
/// The window used to display the PKHUD within. Placed atop the applications main window.
internal class Window: UIWindow {
required internal init(coder aDecoder: NSCoder!) {
self.frameView = FrameView()
super.init(coder: aDecoder)
}
internal let frameView: FrameView
internal init(frameView: FrameView = FrameView()) {
self.frameView = frameView
super.init(frame: UIApplication.sharedApplication().delegate!.window!!.bounds)
rootViewController = WindowRootViewController()
windowLevel = UIWindowLevelNormal + 1.0
backgroundColor = UIColor.clearColor()
addSubview(backgroundView)
addSubview(frameView)
}
internal override func layoutSubviews() {
super.layoutSubviews()
frameView.center = center
backgroundView.frame = bounds
}
internal func showFrameView() {
layer.removeAllAnimations()
makeKeyAndVisible()
frameView.center = center
frameView.alpha = 1.0
hidden = false
}
private var willHide = false
internal func hideFrameView(animated anim: Bool) {
let completion: (finished: Bool) -> (Void) = { finished in
if finished {
self.hidden = true
self.resignKeyWindow()
}
self.willHide = false
}
if hidden {
return
}
willHide = true
if anim {
UIView.animateWithDuration(0.8, animations: { self.frameView.alpha = 0.0 }, completion)
} else {
completion(finished: true)
}
}
private let backgroundView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white:0.0, alpha:0.25)
view.alpha = 0.0;
return view;
}()
internal func showBackground(animated anim: Bool) {
if anim {
UIView.animateWithDuration(0.175) {
self.backgroundView.alpha = 1.0
}
} else {
backgroundView.alpha = 1.0;
}
}
internal func hideBackground(animated anim: Bool) {
if anim {
UIView.animateWithDuration(0.65) {
self.backgroundView.alpha = 0.0
}
} else {
backgroundView.alpha = 0.0;
}
}
}
| mit | 30cc35c6aeeb80e52cbee7d06d3c18b2 | 25.628866 | 99 | 0.55904 | 4.996132 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/first-bad-version.swift | 2 | 647 | /**
* https://leetcode.com/problems/first-bad-version/
*
*
*/
/**
* The knows API is defined in the parent class VersionControl.
* func isBadVersion(_ version: Int) -> Bool{}
*/
class Solution : VersionControl {
func firstBadVersion(_ n: Int) -> Int {
var left = 1
var right = n
// left will be the index of first element with satisfied requirements.
while left < right {
let mid = left + (right - left) / 2
if isBadVersion(mid) == false {
left = mid + 1
} else {
right = mid
}
}
return left
}
}
| mit | fbed5638f36fd0681fe3a8f91fe8b026 | 23.884615 | 79 | 0.513138 | 4.094937 | false | false | false | false |
treejames/firefox-ios | Sync/Synchronizers/TabsSynchronizer.swift | 3 | 7480 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
private let log = Logger.syncLogger
private let TabsStorageVersion = 1
public class TabsSynchronizer: BaseSingleCollectionSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "tabs")
}
override var storageVersion: Int {
return TabsStorageVersion
}
var tabsRecordLastUpload: Timestamp {
set(value) {
self.prefs.setLong(value, forKey: "lastTabsUpload")
}
get {
return self.prefs.unsignedLongForKey("lastTabsUpload") ?? 0
}
}
private func createOwnTabsRecord(tabs: [RemoteTab]) -> Record<TabsPayload> {
let guid = self.scratchpad.clientGUID
let jsonTabs: [JSON] = optFilter(tabs.map { $0.toJSON() })
let tabsJSON = JSON([
"id": guid,
"clientName": self.scratchpad.clientName,
"tabs": jsonTabs
])
log.debug("Sending tabs JSON \(tabsJSON.toString(pretty: true))")
let payload = TabsPayload(tabsJSON)
return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds)
}
private func uploadOurTabs(localTabs: RemoteClientsAndTabs, toServer tabsClient: Sync15CollectionClient<TabsPayload>) -> Success{
// check to see if our tabs have changed or we're in a fresh start
let lastUploadTime: Timestamp? = (self.tabsRecordLastUpload == 0) ? nil : self.tabsRecordLastUpload
let expired = lastUploadTime < (NSDate.now() - (OneMinuteInMilliseconds))
if !expired {
log.debug("Not uploading tabs: already did so at \(lastUploadTime).")
return succeed()
}
return localTabs.getTabsForClientWithGUID(nil) >>== { tabs in
if let lastUploadTime = lastUploadTime {
// TODO: track this in memory so we don't have to hit the disk to figure out when our tabs have
// changed and need to be uploaded.
if tabs.every({ $0.lastUsed < lastUploadTime }) {
return succeed()
}
}
let tabsRecord = self.createOwnTabsRecord(tabs)
log.debug("Uploading our tabs: \(tabs.count).")
// We explicitly don't send If-Unmodified-Since, because we always
// want our upload to succeed -- we own the record.
return tabsClient.put(tabsRecord, ifUnmodifiedSince: nil) >>== { resp in
if let ts = resp.metadata.lastModifiedMilliseconds {
// Protocol says this should always be present for success responses.
log.debug("Tabs record upload succeeded. New timestamp: \(ts).")
self.tabsRecordLastUpload = ts
}
return succeed()
}
}
}
public func synchronizeLocalTabs(localTabs: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult {
func onResponseReceived(response: StorageResponse<[Record<TabsPayload>]>) -> Success {
func afterWipe() -> Success {
log.info("Fetching tabs.")
let doInsert: (Record<TabsPayload>) -> Deferred<Result<(Int)>> = { record in
let remotes = record.payload.remoteTabs
log.debug("\(remotes)")
log.info("Inserting \(remotes.count) tabs for client \(record.id).")
let ins = localTabs.insertOrUpdateTabsForClientGUID(record.id, tabs: remotes)
ins.upon() { res in
if let inserted = res.successValue {
if inserted != remotes.count {
log.warning("Only inserted \(inserted) tabs, not \(remotes.count). Malformed or missing client?")
}
}
}
return ins
}
let ourGUID = self.scratchpad.clientGUID
let records = response.value
let responseTimestamp = response.metadata.lastModifiedMilliseconds
log.debug("Got \(records.count) tab records.")
// We can only insert tabs for clients that we know locally, so
// first we fetch the list of IDs and intersect the two.
// TODO: there's a much more efficient way of doing this.
return localTabs.getClientGUIDs()
>>== { clientGUIDs in
let filtered = records.filter({ $0.id != ourGUID && clientGUIDs.contains($0.id) })
if filtered.count != records.count {
log.debug("Filtered \(records.count) records down to \(filtered.count).")
}
let allDone = all(filtered.map(doInsert))
return allDone.bind { (results) -> Success in
if let failure = find(results, { $0.isFailure }) {
return deferResult(failure.failureValue!)
}
self.lastFetched = responseTimestamp!
return succeed()
}
}
}
// If this is a fresh start, do a wipe.
if self.lastFetched == 0 {
log.info("Last fetch was 0. Wiping tabs.")
return localTabs.wipeRemoteTabs()
>>== afterWipe
}
return afterWipe()
}
if let reason = self.reasonToNotSync(storageClient) {
return deferResult(SyncStatus.NotStarted(reason))
}
let keys = self.scratchpad.keys?.value
let encoder = RecordEncoder<TabsPayload>(decode: { TabsPayload($0) }, encode: { $0 })
if let encrypter = keys?.encrypter(self.collection, encoder: encoder) {
let tabsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter)
if !self.remoteHasChanges(info) {
// upload local tabs if they've changed or we're in a fresh start.
uploadOurTabs(localTabs, toServer: tabsClient)
return deferResult(.Completed)
}
return tabsClient.getSince(self.lastFetched)
>>== onResponseReceived
>>> { self.uploadOurTabs(localTabs, toServer: tabsClient) }
>>> { deferResult(.Completed) }
}
log.error("Couldn't make tabs factory.")
return deferResult(FatalError(message: "Couldn't make tabs factory."))
}
}
extension RemoteTab {
public func toJSON() -> JSON? {
let tabHistory = optFilter(history.map { $0.absoluteString })
if !tabHistory.isEmpty {
return JSON([
"title": title,
"icon": icon?.absoluteString ?? NSNull(),
"urlHistory": tabHistory,
"lastUsed": lastUsed.description,
])
}
return nil
}
}
| mpl-2.0 | cb72e0df4951d03b25ac385ed947d25e | 41.022472 | 155 | 0.563102 | 5.385169 | false | false | false | false |
mkondakov/MovingHelper | MovingHelper/ModelControllers/TaskLoader.swift | 1 | 1312 | //
// TaskLoader.swift
// MovingHelper
//
// Created by Ellen Shapiro on 6/7/15.
// Copyright (c) 2015 Razeware. All rights reserved.
//
import UIKit
/*
Struct to load tasks from JSON.
*/
public struct TaskLoader {
static func loadSavedTasksFromJSONFile(fileName: FileName) -> [Task]? {
let path = fileName.jsonFileName().pathInDocumentsDirectory()
if let data = NSData(contentsOfFile: path) {
return tasksFromData(data)
} else {
return nil
}
}
/**
- returns: The stock moving tasks included with the app.
*/
public static func loadStockTasks() -> [Task] {
if let path = NSBundle.mainBundle()
.pathForResource(FileName.StockTasks.rawValue, ofType: "json"),
data = NSData(contentsOfFile: path),
tasks = tasksFromData(data) {
return tasks
}
//Fall through case
NSLog("Tasks did not load!")
return [Task]()
}
private static func tasksFromData(data: NSData) -> [Task]? {
let error = NSErrorPointer()
if let arrayOfTaskDictionaries = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as? [NSDictionary] {
return Task.tasksFromArrayOfJSONDictionaries(arrayOfTaskDictionaries)
} else {
NSLog("Error loading data: " + error.debugDescription)
return nil
}
}
} | mit | 80d83cf9f78181100a6a584af038af62 | 24.745098 | 120 | 0.661585 | 4.245955 | false | false | false | false |
hooman/swift | test/Concurrency/Runtime/async_task_locals_groups.swift | 1 | 3113 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) | %FileCheck %s
// REQUIRES: rdar82092187
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
@available(SwiftStdlib 5.5, *)
enum TL {
@TaskLocal
static var number = 0
}
@available(SwiftStdlib 5.5, *)
@discardableResult
func printTaskLocal<V>(
_ key: TaskLocal<V>,
_ expected: V? = nil,
file: String = #file, line: UInt = #line
) -> V? {
let value = key.get()
print("\(key) (\(value)) at \(file):\(line)")
if let expected = expected {
assert("\(expected)" == "\(value)",
"Expected [\(expected)] but found: \(value), at \(file):\(line)")
}
return expected
}
// ==== ------------------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
func groups() async {
// no value
_ = await withTaskGroup(of: Int.self) { group in
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0)
}
// no value in parent, value in child
let x1: Int = await withTaskGroup(of: Int.self) { group in
group.spawn {
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0)
// inside the child task, set a value
_ = TL.$number.withValue(1) {
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (1)
}
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0)
return TL.$number.get() // 0
}
return await group.next()!
}
assert(x1 == 0)
// value in parent and in groups
await TL.$number.withValue(2) {
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2)
let x2: Int = await withTaskGroup(of: Int.self) { group in
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2)
group.spawn {
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2)
async let childInsideGroupChild = printTaskLocal(TL.$number)
_ = await childInsideGroupChild // CHECK: TaskLocal<Int>(defaultValue: 0) (2)
return TL.$number.get()
}
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2)
return await group.next()!
}
assert(x2 == 2)
}
}
@available(SwiftStdlib 5.5, *)
func taskInsideGroup() async {
Task {
print("outside") // CHECK: outside
_ = await withTaskGroup(of: Int.self) { group -> Int in
print("in group") // CHECK: in group
printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0)
for _ in 0..<5 {
Task {
printTaskLocal(TL.$number)
print("some task")
}
}
return 0
}
}
// CHECK: some task
// CHECK: some task
// CHECK: some task
// CHECK: some task
await Task.sleep(5 * 1_000_000_000)
// await t.value
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await groups()
await taskInsideGroup()
}
}
| apache-2.0 | 4860c9d5f8506d177c0e37ddb3ad4155 | 25.606838 | 130 | 0.603919 | 3.688389 | false | false | false | false |
zakkhoyt/ColorPicKit | ColorPicKit/Classes/HSLASliderGroup.swift | 1 | 3919 | //
// HSLASliderGroup.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 10/26/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
@IBDesignable public class HSLASliderGroup: SliderGroup {
public override var intrinsicContentSize: CGSize {
get {
if showAlphaSlider {
let height = 3 * spacing + 4.0 * sliderHeight
return CGSize(width: bounds.width, height: height)
} else {
let height = 2 * spacing + 3.0 * sliderHeight
return CGSize(width: bounds.width, height: height)
}
}
}
fileprivate var hslaSlider: HSLASlider!
fileprivate var saturationSlider: GradientSlider!
fileprivate var lightnessSlider: GradientSlider!
fileprivate var alphaSlider: GradientSlider!
override func configureSliders() {
let hsla = color.hsla()
hslaSlider = HSLASlider()
hslaSlider.value = hsla.hue
addSubview(hslaSlider)
sliders.append(hslaSlider)
saturationSlider = GradientSlider()
saturationSlider.color1 = UIColor.black
saturationSlider.color2 = UIColor.white
saturationSlider.value = hsla.saturation
addSubview(saturationSlider)
sliders.append(saturationSlider)
lightnessSlider = GradientSlider()
lightnessSlider.color1 = UIColor.white
lightnessSlider.color2 = UIColor.black
lightnessSlider.value = hsla.lightness
addSubview(lightnessSlider)
sliders.append(lightnessSlider)
if showAlphaSlider {
alphaSlider = GradientSlider()
alphaSlider.color1 = UIColor.clear
alphaSlider.color2 = UIColor.white
alphaSlider.value = hsla.alpha
addSubview(alphaSlider)
sliders.append(alphaSlider)
}
}
override func colorFromSliders() -> UIColor {
guard let _ = hslaSlider,
let _ = saturationSlider,
let _ = lightnessSlider,
let _ = alphaSlider else {
print("sliders not configured");
return UIColor.clear
}
let hue = hslaSlider.value
let saturation = saturationSlider.value
let lightness = lightnessSlider.value
let alpha = alphaSlider.value
let hsla = HSLA(hue: hue, saturation: saturation, lightness: lightness, alpha: alpha)
return hsla.color()
}
override func slidersFrom(color: UIColor) {
let hsla = color.hsla()
hslaSlider.value = hsla.hue
saturationSlider.value = hsla.saturation
lightnessSlider.value = hsla.lightness
alphaSlider.value = hsla.alpha
updateSliderColors()
}
override func updateSliderColors() {
if self.realtimeMix {
let hue = hslaSlider.value
let saturation = saturationSlider.value
let lightness = lightnessSlider.value
// Hue
hslaSlider.lightness = lightness
hslaSlider.saturation = saturation
// Saturation
saturationSlider.color1 = HSLA(hue: hue, saturation: 0.0, lightness: lightness).color()
saturationSlider.color2 = HSLA(hue: hue, saturation: 1.0, lightness: lightness).color()
// Brightness
lightnessSlider.color1 = HSLA(hue: hue, saturation: saturation, lightness: 0.0).color()
lightnessSlider.color2 = HSLA(hue: hue, saturation: saturation, lightness: 1.0).color()
hslaSlider.knobView.color = self.color
saturationSlider.knobView.color = self.color
lightnessSlider.knobView.color = self.color
alphaSlider.knobView.color = self.color
}
}
}
| mit | a4886b14bc8b5398a75ed383df710b79 | 31.92437 | 99 | 0.59903 | 5.426593 | false | false | false | false |
il-Logical/ILImageEditor | ILImageEditor/CompressorExtension.swift | 1 | 1891 | //
// CompressorExtension.swift
// ILImageEditor
//
// Created by Muqtadir Ahmed on 20/08/17.
// Copyright © 2017 Muqtadir Ahmed. All rights reserved.
//
internal extension UIImage {
func compress(compressionRatio ratio: CGFloat, compressionQuality quality: CGFloat) -> UIImage? {
var toHeight = size.height,
toWidth = size.width,
imgRatio = toWidth / toHeight
let maxHeight = toHeight / ratio,
maxWidth = toWidth / ratio,
maxRatio = maxWidth / maxHeight
// Adjust width according to maxHeight.
if (toHeight > maxHeight || toWidth > maxWidth) {
if imgRatio < maxRatio {
imgRatio = maxHeight / toHeight
toWidth = imgRatio * toWidth
toHeight = maxHeight
}
// Adjust height according to maxWidth.
else if imgRatio > maxRatio {
imgRatio = maxWidth / toWidth
toHeight = imgRatio * toHeight
toWidth = maxWidth
}
else {
toHeight = maxHeight
toWidth = maxWidth
}
}
// Draw the image in the new designed frame.
let rect = CGRect(origin: .zero, size: CGSize(width: toWidth, height: toHeight))
UIGraphicsBeginImageContext(rect.size)
draw(in: rect)
guard var img = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
// Apply quality compression.
if quality != 1.0 {
guard let imageData = UIImageJPEGRepresentation(img, quality) else { return nil }
guard let temp = UIImage(data: imageData) else { return nil }
img = temp
}
return img
}
}
| mit | 64021f2e73af3c1cf1dcd334e486cb40 | 31.033898 | 101 | 0.543915 | 5.70997 | false | false | false | false |
benlangmuir/swift | test/Parse/line-directive.swift | 1 | 2845 | // RUN: %target-typecheck-verify-swift
// RUN: not %target-swift-frontend -c %s 2>&1 | %FileCheck %s
let x = 0 // We need this because of the #sourceLocation-ends-with-a-newline requirement.
#sourceLocation()
x // expected-error {{parameterless closing #sourceLocation() directive without prior opening #sourceLocation(file:,line:) directive}}
#sourceLocation(file: "x", line: 0) // expected-error{{the line number needs to be greater}}
#sourceLocation(file: "x", line: -1) // expected-error{{expected starting line number}}
#sourceLocation(file: "x", line: 1.5) // expected-error{{expected starting line number}}
#sourceLocation(file: x.swift, line: 1) // expected-error{{expected filename string literal}}
#sourceLocation(file: "x.swift", line: 42)
x x ; // should be ignored by expected_error because it is in a different file
x
#sourceLocation()
_ = x
x x // expected-error{{consecutive statements}} {{2-2=;}}
// expected-warning @-1 2 {{unused}}
// rdar://19582475
public struct S { // expected-note{{in declaration of 'S'}}
// expected-error@+8{{expected 'func' keyword in operator function declaration}}
// expected-error@+7{{operator '/' declared in type 'S' must be 'static'}}
// expected-error@+6{{expected '(' in argument list of function declaration}}
// expected-error@+5{{operators must have one or two arguments}}
// expected-error@+4{{member operator '/()' must have at least one argument of type 'S'}}
// expected-error@+3{{expected '{' in body of function declaration}}
// expected-error@+2{{consecutive declarations on a line must be separated by ';}}
// expected-error@+1{{expected declaration}}
/ ###line 25 "line-directive.swift"
}
// expected-error@+1{{#line directive was renamed to #sourceLocation}}
#line 32000 "troops_on_the_water"
#sourceLocation()
// expected-error@+1 {{expected expression}}
try #sourceLocation(file: "try.swift", line: 100)
#sourceLocation()
// expected-error@+3 {{expected statement}}
// expected-error@+2 {{#line directive was renamed to #sourceLocation}}
LABEL:
#line 200 "labeled.swift"
#sourceLocation()
class C {
#sourceLocation(file: "sr5242.swift", line: 100)
func foo() {}
let bar = 12
#sourceLocation(file: "sr5242.swift", line: 200)
}
enum E {
#sourceLocation(file: "sr5242.swift", line: 300)
case A, B
case C, D
#sourceLocation()
}
#sourceLocation(file: "sr8772.swift", line: 400)
2., 3
// CHECK: sr8772.swift:400:2: error: expected member name following '.'
// CHECK: sr8772.swift:400:3: error: consecutive statements on a line must be separated by ';'
// CHECK: sr8772.swift:400:3: error: expected expression
// https://github.com/apple/swift/issues/55049
class I55049 {
#sourceLocation(file: "issue-55049.swift", line: 1_000)
let bar = 12
#sourceLocation(file: "issue-55049.swift", line: 2_000)
}
#line 1_000 "issue-55049.swift"
class I55049_1 {}
| apache-2.0 | b6e7b3ec0406d4441f16b61d1bd04d16 | 35.012658 | 134 | 0.707909 | 3.482252 | false | false | false | false |
thankmelater23/MyFitZ | MyFitZ/JSNViewController.swift | 1 | 4096 | //
// ViewController.swift
// JOSNSwiftDemo
//
// Created by Shinkangsan on 12/5/16.
// Copyright © 2016 Sheldon. All rights reserved.
//
import UIKit
class JSNViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
@IBOutlet weak var tableView: UITableView!
var nameArray = [String]()
var dobArray = [String]()
var imgURLArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
// 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.
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "actors"))
if let actorArray = jsonObj!.value(forKey: "actors") as? NSArray {
for actor in actorArray{
if let actorDict = actor as? NSDictionary {
if let name = actorDict.value(forKey: "name") {
self.nameArray.append(name as! String)
}
if let name = actorDict.value(forKey: "dob") {
self.dobArray.append(name as! String)
}
if let name = actorDict.value(forKey: "image") {
self.imgURLArray.append(name as! String)
}
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData)
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.nameLabel.text = nameArray[indexPath.row]
cell.dobLabel.text = dobArray[indexPath.row]
let imgURL = NSURL(string: imgURLArray[indexPath.row])
if imgURL != nil {
let data = NSData(contentsOf: (imgURL as? URL)!)
cell.imgView.image = UIImage(data: data as! Data)
}
return cell
}
///for showing next detailed screen with the downloaded info
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.imageString = imgURLArray[indexPath.row]
vc.nameString = nameArray[indexPath.row]
vc.dobString = dobArray[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
}
| mit | dba7c9406e75d15b1f9da0866031885c | 34.608696 | 140 | 0.567766 | 5.388158 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/Extensions/ImageSource+BackwardCompatibility.swift | 1 | 2248 | import ImageSource
public extension ImageSource {
func fullResolutionImage<T: InitializableWithCGImage>(_ completion: @escaping (T?) -> ()) {
fullResolutionImage(deliveryMode: .best, resultHandler: completion)
}
@discardableResult
func imageFittingSize<T: InitializableWithCGImage>(_ size: CGSize, resultHandler: @escaping (T?) -> ()) -> ImageRequestId {
return imageFittingSize(size, contentMode: .aspectFill, deliveryMode: .progressive, resultHandler: resultHandler)
}
func fullResolutionImage<T: InitializableWithCGImage>(deliveryMode: ImageDeliveryMode, resultHandler: @escaping (T?) -> ()) {
var options = ImageRequestOptions()
options.size = .fullResolution
options.deliveryMode = deliveryMode
requestImage(options: options) { (result: ImageRequestResult<T>) in
resultHandler(result.image)
}
}
@discardableResult
func requestImage<T: InitializableWithCGImage>(
options: ImageRequestOptions,
resultHandler: @escaping (T?) -> ())
-> ImageRequestId
{
return requestImage(options: options) { (result: ImageRequestResult<T>) in
resultHandler(result.image)
}
}
@available(*, deprecated, message: "Use ImageSource.requestImage(options:resultHandler:) instead")
@discardableResult
func imageFittingSize<T: InitializableWithCGImage>(
_ size: CGSize,
contentMode: ImageContentMode,
deliveryMode: ImageDeliveryMode,
resultHandler: @escaping (T?) -> ())
-> ImageRequestId
{
var options = ImageRequestOptions()
options.deliveryMode = deliveryMode
switch contentMode {
case .aspectFit:
options.size = .fitSize(size)
case .aspectFill:
options.size = .fillSize(size)
}
return requestImage(options: options) { (result: ImageRequestResult<T>) in
resultHandler(result.image)
}
}
}
@available(*, deprecated, message: "Use ImageSizeOption instead (see ImageSource.requestImage(options:resultHandler:))")
public enum ImageContentMode {
case aspectFit
case aspectFill
}
| mit | 54c34f72378d57f5b57746f01dd81a5d | 33.584615 | 129 | 0.649911 | 5.252336 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Character/CharacterSheetHeader.swift | 2 | 2527 | //
// CharacterSheetHeader.swift
// Neocom
//
// Created by Artem Shimanski on 1/13/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
struct CharacterSheetHeader: View {
var characterName: String?
var characterImage: UIImage?
var corporationName: String?
var corporationImage: UIImage?
var allianceName: String?
var allianceImage: UIImage?
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
private var title: some View {
VStack(alignment: .leading, spacing: 0) {
Text(characterName ?? "").font(.title)
if corporationName != nil {
HStack {
if corporationImage != nil {
Icon(Image(uiImage: corporationImage!))
}
Text(corporationName!)
}
}
if allianceName != nil {
HStack {
if allianceImage != nil {
Icon(Image(uiImage: allianceImage!))
}
Text(allianceName!)
}
}
}
.padding(8)
.background(Color(.systemFill).cornerRadius(8))
.padding()
.colorScheme(.dark)
}
var body: some View {
let image = Image(uiImage: characterImage ?? UIImage()).resizable().scaledToFit()
return Group {
if horizontalSizeClass == .regular {
image.frame(maxWidth: 512)
.cornerRadius(8)
// .padding(15)
.overlay(title, alignment: .bottomLeading)
// .frame(maxWidth: .infinity)
}
else {
image.overlay(title, alignment: .bottomLeading)
}
}
}
}
struct CharacterSheetHeader_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
List {
CharacterSheetHeader(characterName: "Artem Valiant",
characterImage: UIImage(named: "character"),
corporationName: "Necrorise Squadron",
corporationImage: UIImage(named: "corporation"),
allianceName: "Red Alert",
allianceImage: UIImage(named: "alliance"))
}.listStyle(GroupedListStyle())
}.navigationViewStyle(StackNavigationViewStyle())
}
}
| lgpl-2.1 | cdfc276164e6f37ba1d80cb21c3ae32c | 31.805195 | 89 | 0.513856 | 5.539474 | false | false | false | false |
saviofigueiredo/OnkyoSdk | OnkyoSdk/Classes/Socket/Socket.swift | 1 | 5328 | //
// Socket.swift
// Onkyo
//
// Created by Savio Mendes de Figueiredo on 1/5/17.
// Copyright © 2017 Savio Mendes de Figueiredo. All rights reserved.
//
import Foundation
import Darwin
struct Packet {
var address: String
var packet: Data
}
class Socket {
fileprivate let socketDescriptor: Int32
init? () {
var socketAddress: sockaddr_in = sockaddr_in(type: sockaddr_in.SocketAddressType.local)
var broadcast: Int = 1;
socketDescriptor = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)
guard socketDescriptor != -1 else {
return nil
}
var internetAddress = socketAddress.getInternetAddress()
guard bind(socketDescriptor, &internetAddress, socklen_t(MemoryLayout<sockaddr_in>.size)) != -1 else {
return nil
}
guard setsockopt(socketDescriptor, SOL_SOCKET, SO_BROADCAST, &broadcast, socklen_t(MemoryLayout<Int32>.size)) != -1 else {
return nil
}
}
init? (address: String, port: UInt16) {
var socketAddress: sockaddr_in = sockaddr_in(address: address, port: port)
socketDescriptor = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)
guard inet_pton(AF_INET, address.cString(using: .ascii), &socketAddress.sin_addr) != -1 else {
print ("Error code is \(errno)")
print ("Error message is \(String(utf8String: strerror(errno)))")
close(socketDescriptor)
return nil
}
var internetAddress = socketAddress.getInternetAddress()
guard connect(socketDescriptor, &internetAddress, socklen_t(MemoryLayout<sockaddr_in>.size)) != -1 else {
close(socketDescriptor)
return nil
}
}
deinit {
close (socketDescriptor)
}
func sendPacket(packet: Data) {
var array = [UInt8](repeating: 0, count: packet.count)
packet.copyBytes(to: &array, count: packet.count)
let bytesSentCount = send(socketDescriptor, array, array.count, 0)
guard bytesSentCount == array.count else {
print ("Number of sent bytes \(bytesSentCount) does not match the number of bytes to be sent \(array.count).")
close (socketDescriptor)
return
}
var buffer = [UInt8](repeating: 0, count: 100)
let bytesReceivedCount = recv(socketDescriptor, &buffer, 99, 0)
if bytesReceivedCount < 1 {
print ("Error code is \(errno)")
print ("Error message is \(String(utf8String: strerror(errno)))")
close(socketDescriptor)
return
}
}
func sendPacket(broadcastAddress: String, port: UInt16, packet: Data) {
print ("Package will be broadcasted to \(broadcastAddress)")
var destinationAddress: sockaddr_in = sockaddr_in(address: broadcastAddress, port: port)
var internetAddress = destinationAddress.getInternetAddress()
var array = [UInt8](repeating: 0, count: packet.count)
packet.copyBytes(to: &array, count: packet.count)
let numbytes = sendto(socketDescriptor, array, array.count, 0, &internetAddress, socklen_t(MemoryLayout<sockaddr_in>.size))
print ("\(numbytes) have been sent to \(broadcastAddress)")
print (String(data: packet, encoding: String.Encoding.utf8)!)
}
func getResponses() -> [Packet] {
var destinationAddress: sockaddr_in = sockaddr_in()
var buffer = [UInt8](repeating: 0, count: 100)
var fileDescriptorSet: fd_set = fd_set()
var packets: [Packet] = []
while true {
var ready: Int32
repeat {
fileDescriptorSet.clear()
fileDescriptorSet.set(socketDescriptor)
var timeout: timeval = timeval(tv_sec: 2, tv_usec: 0)
ready = Darwin.select(socketDescriptor + 1, &fileDescriptorSet, nil, nil, &timeout)
} while ready == -1 && errno == EINTR
if ready == 0 {
break
}
if fileDescriptorSet.isSet(socketDescriptor) {
var addr_len: socklen_t = socklen_t(MemoryLayout<sockaddr_in>.size)
var internetAddress = destinationAddress.getInternetAddress()
let bytesReceivedCount = recvfrom(socketDescriptor, &buffer, 100, 0, &internetAddress, &addr_len)
if bytesReceivedCount == -1 {
break
}
let deviceAddress = String(cString: inet_ntoa(sockaddr_in(address: &internetAddress).sin_addr), encoding: .ascii)!
print ("The device address is \(deviceAddress)")
print ("Packet received ([UInt8]) is \(buffer)")
print ("Packet received (String) is \(String(data: Data(bytes: buffer), encoding: String.Encoding.utf8)!)")
packets.append(Packet(address: deviceAddress, packet: Data(bytes: buffer)))
}
}
return packets
}
}
| mit | 6b211edbd0201af361ef889e9659f179 | 34.513333 | 131 | 0.569176 | 4.743544 | false | false | false | false |
esttorhe/MammutAPI | Sources/MammutAPI/Models/Status.swift | 1 | 2489 | //
// Created by Esteban Torres on 16.04.17.
// Copyright (c) 2017 Esteban Torres. All rights reserved.
//
import Foundation
public class Status {
let id: Int
let createdAt: Date
let inReplyToId: String?
let inReplyToAccountId: String?
let sensitive: Bool
let spoilerText: String?
let visibility: StatusVisibility
let application: Application?
let account: Account
let mediaAttachments: [Attachment]
let mentions: [Mention]
let tags: [Tag]
let uri: String
let content: String
let url: URL
let reblogsCount: Int
let favouritesCount: Int
let reblog: Status?
let favourited: Bool
let reblogged: Bool
init(
id: Int,
createdAt: Date,
inReplyToId: String?,
inReplyToAccountId: String?,
sensitive: Bool,
spoilerText: String?,
visibility: StatusVisibility,
application: Application?,
account: Account,
mediaAttachments: [Attachment],
mentions: [Mention],
tags: [Tag],
uri: String,
content: String,
url: URL,
reblogsCount: Int,
favouritesCount: Int,
reblog: Status?,
favourited: Bool,
reblogged: Bool
) {
self.id = id
self.createdAt = createdAt
self.inReplyToId = inReplyToId
self.inReplyToAccountId = inReplyToAccountId
self.sensitive = sensitive
self.spoilerText = spoilerText
self.visibility = visibility
self.application = application
self.account = account
self.mediaAttachments = mediaAttachments
self.mentions = mentions
self.tags = tags
self.uri = uri
self.content = content
self.url = url
self.reblogsCount = reblogsCount
self.favouritesCount = favouritesCount
self.reblog = reblog
self.favourited = favourited
self.reblogged = reblogged
}
}
// MARK: - Equatable
extension Status: Equatable {
public static func ==(lhs: Status, rhs: Status) -> Bool {
return (
lhs.id == rhs.id &&
lhs.url == rhs.url &&
lhs.visibility == rhs.visibility &&
lhs.account == rhs.account &&
lhs.content == rhs.content &&
lhs.uri == rhs.uri &&
lhs.createdAt == rhs.createdAt
)
}
} | mit | 3d9963407a4a085f7a0bb237078c7273 | 26.977528 | 61 | 0.568903 | 4.842412 | false | false | false | false |
becvert/cordova-plugin-websocket-server | src/ios/WebSocketServer.swift | 1 | 16551 | import Foundation
@objc(WebSocketServer) public class WebSocketServer : CDVPlugin, PSWebSocketServerDelegate {
fileprivate var wsserver: PSWebSocketServer?
fileprivate var port: Int?
fileprivate var origins: [String]?
fileprivate var protocols: [String]?
fileprivate var UUIDSockets: [String: PSWebSocket]!
fileprivate var socketsUUID: [PSWebSocket: String]!
fileprivate var didCloseUUIDs: [String]!
fileprivate var startCallbackId: String?
fileprivate var stopCallbackId: String?
fileprivate var didStopOrDidFail: Bool = false
override public func pluginInitialize() {
UUIDSockets = [:]
socketsUUID = [:]
didCloseUUIDs = []
}
override public func onAppTerminate() {
if let server = wsserver {
server.stop()
wsserver = nil
UUIDSockets.removeAll()
socketsUUID.removeAll()
didCloseUUIDs.removeAll()
}
}
@objc public func getInterfaces(_ command: CDVInvokedUrlCommand) {
commandDelegate?.run(inBackground: {
var obj = [String: [String: [String]]]()
var intfobj: [String: [String]]
var ipv4Addresses: [String]
var ipv6Addresses: [String]
for intf in Interface.allInterfaces() {
if !intf.isLoopback {
if let ifobj = obj[intf.name] {
intfobj = ifobj
ipv4Addresses = intfobj["ipv4Addresses"]!
ipv6Addresses = intfobj["ipv6Addresses"]!
} else {
intfobj = [:]
ipv4Addresses = []
ipv6Addresses = []
}
if intf.family == .ipv6 {
if ipv6Addresses.firstIndex(of: intf.address!) == nil {
ipv6Addresses.append(intf.address!)
}
} else if intf.family == .ipv4 {
if ipv4Addresses.firstIndex(of: intf.address!) == nil {
ipv4Addresses.append(intf.address!)
}
}
if (!ipv4Addresses.isEmpty) || (!ipv6Addresses.isEmpty) {
intfobj["ipv4Addresses"] = ipv4Addresses
intfobj["ipv6Addresses"] = ipv6Addresses
obj[intf.name] = intfobj
}
}
}
#if DEBUG
print("WebSocketServer: getInterfaces: \(obj)")
#endif
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: obj)
pluginResult?.setKeepCallbackAs(false)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
})
}
@objc public func start(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("WebSocketServer: start")
#endif
if didStopOrDidFail {
wsserver = nil
didStopOrDidFail = false
}
if wsserver != nil {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Server already running")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
return
}
port = command.argument(at: 0) as? Int
if port! < 0 || port! > 65535 {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Port number error")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
return
}
origins = command.argument(at: 1) as? [String]
protocols = command.argument(at: 2) as? [String]
let tcpNoDelay = command.argument(at: 3) as? Bool
if let server = PSWebSocketServer(host: nil, port: UInt(port!)) {
startCallbackId = command.callbackId
wsserver = server
server.delegate = self
if tcpNoDelay != nil {
server.setTcpNoDelay(tcpNoDelay!)
}
commandDelegate?.run(inBackground: {
server.start()
})
let pluginResult = CDVPluginResult(status: CDVCommandStatus_NO_RESULT)
pluginResult?.setKeepCallbackAs(true)
}
}
@objc public func stop(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("WebSocketServer: stop")
#endif
if didStopOrDidFail {
wsserver = nil
didStopOrDidFail = false
}
if wsserver == nil {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Server is not running")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
return
}
if let server = wsserver {
stopCallbackId = command.callbackId
commandDelegate?.run(inBackground: {
server.stop()
})
let pluginResult = CDVPluginResult(status: CDVCommandStatus_NO_RESULT)
pluginResult?.setKeepCallbackAs(true)
}
}
@objc public func send(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("WebSocketServer: send")
#endif
let uuid = command.argument(at: 0) as? String
let msg = command.argument(at: 1) as? String
if uuid != nil && msg != nil {
if let webSocket = UUIDSockets[uuid!] {
commandDelegate?.run(inBackground: {
webSocket.send(msg)
})
} else {
#if DEBUG
print("WebSocketServer: Send: unknown socket.")
#endif
}
} else {
#if DEBUG
print("WebSocketServer: Send: UUID or msg not specified.")
#endif
}
}
@objc public func send_binary(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("WebSocketServer: send_binary")
#endif
let uuid = command.argument(at: 0) as? String
let msg = command.argument(at: 1) as? String
if uuid != nil && msg != nil {
if let webSocket = UUIDSockets[uuid!] {
commandDelegate?.run(inBackground: {
webSocket.send(NSData(base64Encoded: msg!, options: .ignoreUnknownCharacters))
})
} else {
#if DEBUG
print("WebSocketServer: Send: unknown socket.")
#endif
}
} else {
#if DEBUG
print("WebSocketServer: Send: UUID or msg not specified.")
#endif
}
}
@objc public func close(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("WebSocketServer: close")
#endif
let uuid = command.argument(at: 0) as? String
let code = command.argument(at: 1, withDefault: -1) as! Int
let reason = command.argument(at: 2) as? String
if uuid != nil {
if let webSocket = UUIDSockets[uuid!] {
commandDelegate?.run(inBackground: {
if (code == -1) {
webSocket.close()
} else {
webSocket.close(withCode: code, reason: reason)
}
})
} else {
#if DEBUG
print("WebSocketServer: Close: unknown socket.")
#endif
}
} else {
#if DEBUG
print("WebSocketServer: Close: UUID not specified.")
#endif
}
}
public func serverDidStart(_ server: PSWebSocketServer!) {
#if DEBUG
print("WebSocketServer: Server did start…")
#endif
let status: NSDictionary = NSDictionary(objects: ["0.0.0.0", Int(server.realPort)], forKeys: ["addr" as NSCopying, "port" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (status as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: startCallbackId)
}
public func serverDidStop(_ server: PSWebSocketServer!) {
#if DEBUG
print("WebSocketServer: Server did stop…")
#endif
didStopOrDidFail = true
UUIDSockets.removeAll()
socketsUUID.removeAll()
didCloseUUIDs.removeAll()
let status: NSDictionary = NSDictionary(objects: ["0.0.0.0", Int(server.realPort)], forKeys: ["addr" as NSCopying, "port" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (status as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(false)
commandDelegate?.send(pluginResult, callbackId: stopCallbackId)
}
public func server(_ server: PSWebSocketServer!, didFailWithError error: Error!) {
#if DEBUG
print("WebSocketServer: Server did fail with error: \(error)")
#endif
// normally already stopped. just making sure!
wsserver?.stop()
didStopOrDidFail = true
UUIDSockets.removeAll()
socketsUUID.removeAll()
didCloseUUIDs.removeAll()
let status: NSDictionary = NSDictionary(objects: ["onFailure", "0.0.0.0", port!, error.localizedDescription], forKeys: ["action" as NSCopying, "addr" as NSCopying, "port" as NSCopying, "reason" as String as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (status as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(false)
commandDelegate?.send(pluginResult, callbackId: startCallbackId)
}
public func server(_ server: PSWebSocketServer!, acceptWebSocketFrom address: Data, with request: URLRequest, trust: SecTrust, response: AutoreleasingUnsafeMutablePointer<HTTPURLResponse?>) -> Bool {
#if DEBUG
print("WebSocketServer: Server should accept request: \(request)")
#endif
if let o = origins {
let origin = request.value(forHTTPHeaderField: "Origin")
if o.firstIndex(of: origin!) == nil {
#if DEBUG
print("WebSocketServer: Origin denied: \(origin)")
#endif
return false
}
}
if let _ = protocols {
if let acceptedProtocol = getAcceptedProtocol(request) {
let headerFields = [ "Sec-WebSocket-Protocol" : acceptedProtocol ]
let r = HTTPURLResponse.init(url: request.url!, statusCode: 200, httpVersion: "1.1", headerFields: headerFields )!
response.pointee = r
} else {
#if DEBUG
let secWebSocketProtocol = request.value(forHTTPHeaderField: "Sec-WebSocket-Protocol")
print("WebSocketServer: Sec-WebSocket-Protocol denied: \(secWebSocketProtocol)")
#endif
return false
}
}
return true;
}
public func server(_ server: PSWebSocketServer!, webSocketDidOpen webSocket: PSWebSocket!) {
#if DEBUG
print("WebSocketServer: WebSocket did open")
#endif
// clean previously closed sockets
for closedUUID in didCloseUUIDs {
if let webSocket = UUIDSockets[closedUUID] {
socketsUUID.removeValue(forKey: webSocket)
}
UUIDSockets.removeValue(forKey: closedUUID)
}
didCloseUUIDs.removeAll()
var uuid: String!
while uuid == nil || UUIDSockets[uuid] != nil {
// prevent collision
uuid = UUID().uuidString
}
UUIDSockets[uuid] = webSocket
socketsUUID[webSocket] = uuid
let remoteAddr = webSocket.remoteHost!
var acceptedProtocol = ""
if (protocols != nil) {
acceptedProtocol = getAcceptedProtocol(webSocket.urlRequest)!
}
let httpFields = webSocket.urlRequest.allHTTPHeaderFields!
var resource = ""
if (webSocket.urlRequest.url!.query != nil) {
resource = String(cString: (webSocket.urlRequest.url!.query?.cString(using: String.Encoding.utf8))! )
}
let conn: NSDictionary = NSDictionary(objects: [uuid!, remoteAddr, acceptedProtocol, httpFields, resource], forKeys: ["uuid" as NSCopying, "remoteAddr" as NSCopying, "acceptedProtocol" as NSCopying, "httpFields" as NSCopying, "resource" as NSCopying])
let status: NSDictionary = NSDictionary(objects: ["onOpen", conn], forKeys: ["action" as NSCopying, "conn" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (status as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: startCallbackId)
}
public func server(_ server: PSWebSocketServer!, webSocket: PSWebSocket!, didReceiveMessage message: Any) {
#if DEBUG
print("WebSocketServer: Websocket did receive message: \(message)")
#endif
if let uuid = socketsUUID[webSocket] {
let objects: [Any];
if let data = message as? NSData{
objects = ["onMessage", uuid, data.base64EncodedString(), true];
} else {
objects = ["onMessage", uuid, message, false];
}
let status: NSDictionary = NSDictionary(objects: objects, forKeys: ["action" as NSCopying, "uuid" as NSCopying, "msg" as NSCopying, "is_binary" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (status as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: startCallbackId)
} else {
#if DEBUG
print("WebSocketServer: unknown socket")
#endif
}
}
public func server(_ server: PSWebSocketServer!, webSocket: PSWebSocket!, didCloseWithCode code: Int, reason: String, wasClean: Bool) {
#if DEBUG
print("WebSocketServer: WebSocket did close with code: \(code), reason: \(reason), wasClean: \(wasClean)")
#endif
if let uuid = socketsUUID[webSocket] {
didCloseUUIDs.append(uuid)
let status: NSDictionary = NSDictionary(objects: ["onClose", uuid, code, reason, wasClean], forKeys: ["action" as NSCopying, "uuid" as NSCopying, "code" as NSCopying, "reason" as NSCopying, "wasClean" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (status as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: startCallbackId)
} else {
#if DEBUG
print("WebSocketServer: unknown socket")
#endif
}
}
public func server(_ server: PSWebSocketServer!, webSocket: PSWebSocket!, didFailWithError error: Error!) {
#if DEBUG
print("WebSocketServer: WebSocket did fail with error: \(error)")
#endif
if (webSocket.readyState == PSWebSocketReadyState.open) {
webSocket.close(withCode: 1011, reason: "")
}
}
fileprivate func getAcceptedProtocol(_ request: URLRequest) -> String? {
var acceptedProtocol: String?
if let secWebSocketProtocol = request.value(forHTTPHeaderField: "Sec-WebSocket-Protocol") {
let requestedProtocols = secWebSocketProtocol.components(separatedBy: ", ")
for requestedProtocol in requestedProtocols {
if protocols!.firstIndex(of: requestedProtocol) != nil {
// returns first matching protocol.
// assumes in order of preference.
acceptedProtocol = requestedProtocol
break
}
}
#if DEBUG
print("WebSocketServer: Sec-WebSocket-Protocol: \(secWebSocketProtocol)")
print("WebSocketServer: Accepted Protocol: \(acceptedProtocol)")
#endif
}
return acceptedProtocol
}
}
| mit | 27512bb4607f32733f4aebd47cfbac5c | 35.689579 | 259 | 0.571282 | 5.423468 | false | false | false | false |
Clipy/Magnet | Lib/MagnetTests/KeyComboTests.swift | 1 | 20094 | //
// KeyComboTests.swift
//
// MagnetTests
// GitHub: https://github.com/clipy
// HP: https://clipy-app.com
//
// Copyright © 2015-2020 Clipy Project.
//
import XCTest
import Sauce
import Carbon
@testable import Magnet
final class KeyComboTests: XCTestCase {
// MARK: - Tests
func testFunctionInitializer() {
var keyCombo: KeyCombo?
// F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [])
XCTAssertNotNil(keyCombo)
// Shift + Control + Comman + Option + F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [.shift, .control, .command, .option])
XCTAssertNotNil(keyCombo)
}
func testDoubledTapKeyComboInitializer() {
var keyCombo: KeyCombo?
// Shift double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .shift)
XCTAssertNotNil(keyCombo)
// Empty double tap
keyCombo = KeyCombo(doubledCocoaModifiers: [])
XCTAssertNil(keyCombo)
// Shift + Control double tap
keyCombo = KeyCombo(doubledCocoaModifiers: [.shift, .command])
XCTAssertNil(keyCombo)
// Function double tap
keyCombo = KeyCombo(doubledCocoaModifiers: [.function])
XCTAssertNil(keyCombo)
}
func testDoubledTapKeyComboCharacter() {
var keyCombo: KeyCombo?
// Shift double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .shift)
XCTAssertEqual(keyCombo?.characters, "")
// Control double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .control)
XCTAssertEqual(keyCombo?.characters, "")
// Command double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .command)
XCTAssertEqual(keyCombo?.characters, "")
// Option double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .option)
XCTAssertEqual(keyCombo?.characters, "")
}
func testCharacter() {
var keyCombo: KeyCombo?
// Command + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.command])
XCTAssertEqual(keyCombo?.characters, "a")
// Shift + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.shift])
XCTAssertEqual(keyCombo?.characters, "A")
// Option + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.option])
XCTAssertEqual(keyCombo?.characters, "å")
// Option + Shift + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.option, .shift])
XCTAssertEqual(keyCombo?.characters, "Å")
// Option + Shift + 1
keyCombo = KeyCombo(key: .one, cocoaModifiers: [.option, .shift])
XCTAssertEqual(keyCombo?.characters, "⁄")
// Option + Shift + KeyPad 1
keyCombo = KeyCombo(key: .keypadOne, cocoaModifiers: [.option, .shift])
XCTAssertEqual(keyCombo?.characters, "1")
// Option + ;
keyCombo = KeyCombo(key: .semicolon, cocoaModifiers: [.option])
XCTAssertEqual(keyCombo?.characters, "…")
// Shift + F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [.shift])
XCTAssertEqual(keyCombo?.characters, "F1")
// Option double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .option)
XCTAssertEqual(keyCombo?.characters, "")
}
func testKeyEquivalent() {
var keyCombo: KeyCombo?
// Command + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.command])
XCTAssertEqual(keyCombo?.keyEquivalent, "a")
// Shift + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.shift])
XCTAssertEqual(keyCombo?.keyEquivalent, "A")
// Option + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.option])
XCTAssertEqual(keyCombo?.keyEquivalent, "a")
// Option + Shift + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.option, .shift])
XCTAssertEqual(keyCombo?.keyEquivalent, "A")
// Option + Shift + 1
keyCombo = KeyCombo(key: .one, cocoaModifiers: [.option, .shift])
XCTAssertEqual(keyCombo?.keyEquivalent, "1")
// Option + Shift + Keypad 1
keyCombo = KeyCombo(key: .keypadOne, cocoaModifiers: [.option, .shift])
XCTAssertEqual(keyCombo?.keyEquivalent, "1")
// Option + ;
keyCombo = KeyCombo(key: .semicolon, cocoaModifiers: [.option])
XCTAssertEqual(keyCombo?.keyEquivalent, ";")
// Shift + F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [.shift])
XCTAssertEqual(keyCombo?.keyEquivalent, "F1")
// Option double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .option)
XCTAssertEqual(keyCombo?.keyEquivalent, "")
}
func testKeyEquivalentModifierMaskString() {
var keyCombo: KeyCombo?
// Shift + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.shift])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⇧")
// Control + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.control])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌃")
// Command + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.command])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌘")
// Option + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.option])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌥")
// Shift + Control + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.shift, .control])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌃⇧")
// Shift + Control + Option + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.shift, .control, .option])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌃⌥⇧")
// Command + Option + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.command, .option])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌥⌘")
// Command + Shift + Option + Control + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.command, .shift, .option, .control])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌃⌥⇧⌘")
// Command + Option + Function + CapsLock + NumericPad + Help + a
keyCombo = KeyCombo(key: .a, cocoaModifiers: [.command, .option, .function, .capsLock, .numericPad, .help])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌥⌘")
// F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "")
// Command + F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [.command])
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⌘")
// Shift Double tap
keyCombo = KeyCombo(doubledCocoaModifiers: .shift)
XCTAssertEqual(keyCombo?.keyEquivalentModifierMaskString, "⇧")
}
func testNSCodingMigrationV3_0() {
var oldKeyCombo: v2_0_0KeyCombo?
var archivedData: Data?
var unarchivedKeyCombo: KeyCombo?
NSKeyedUnarchiver.setClass(KeyCombo.self, forClassName: "MagnetTests.v2_0_0KeyCombo")
// Shift + v
oldKeyCombo = v2_0_0KeyCombo(keyCode: kVK_ANSI_V, modifiers: shiftKey, doubledModifiers: false)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .v)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// F3
oldKeyCombo = v2_0_0KeyCombo(keyCode: kVK_F3, modifiers: Int(NSEvent.ModifierFlags.function.rawValue), doubledModifiers: false)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .f3)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, Int(NSEvent.ModifierFlags.function.rawValue))
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// Control double tap
oldKeyCombo = v2_0_0KeyCombo(keyCode: 0, modifiers: controlKey, doubledModifiers: true)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .a)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, controlKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, true)
// Shift + @
oldKeyCombo = v2_0_0KeyCombo(keyCode: Int(Key.atSign.QWERTYKeyCode), modifiers: shiftKey, doubledModifiers: false)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .leftBracket)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
}
func testNSCodingMigrationV3_1() {
var oldKeyCombo: v3_1_0KeyCombo?
var archivedData: Data?
var unarchivedKeyCombo: KeyCombo?
NSKeyedUnarchiver.setClass(KeyCombo.self, forClassName: "MagnetTests.v3_1_0KeyCombo")
// Shift + v
oldKeyCombo = v3_1_0KeyCombo(key: .v, modifiers: shiftKey, doubledModifiers: false)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .v)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// F3
oldKeyCombo = v3_1_0KeyCombo(key: .f3, modifiers: Int(NSEvent.ModifierFlags.function.rawValue), doubledModifiers: false)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .f3)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, Int(NSEvent.ModifierFlags.function.rawValue))
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// Control double tap
oldKeyCombo = v3_1_0KeyCombo(key: .a, modifiers: controlKey, doubledModifiers: true)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .a)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, controlKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, true)
// Shift + @
oldKeyCombo = v3_1_0KeyCombo(key: .atSign, modifiers: shiftKey, doubledModifiers: false)
archivedData = NSKeyedArchiver.archivedData(withRootObject: oldKeyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .leftBracket)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
}
func testNSCoding() {
var keyCombo: KeyCombo?
var archivedData: Data?
var unarchivedKeyCombo: KeyCombo?
// Shift + Control + c
keyCombo = KeyCombo(key: .c, cocoaModifiers: [.shift, .control])
archivedData = NSKeyedArchiver.archivedData(withRootObject: keyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [])
archivedData = NSKeyedArchiver.archivedData(withRootObject: keyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// Option double tap
keyCombo = KeyCombo(doubledCocoaModifiers: [.option])
archivedData = NSKeyedArchiver.archivedData(withRootObject: keyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// Shift + @
keyCombo = KeyCombo(key: .atSign, cocoaModifiers: [.shift])
archivedData = NSKeyedArchiver.archivedData(withRootObject: keyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// Control + [
keyCombo = KeyCombo(key: .leftBracket, cocoaModifiers: [.control])
archivedData = NSKeyedArchiver.archivedData(withRootObject: keyCombo!)
unarchivedKeyCombo = NSKeyedUnarchiver.unarchiveObject(with: archivedData!) as? KeyCombo
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
}
func testCodableMigrationV3_0() throws {
var oldKeyCombo: v2_0_0KeyCombo?
var archivedData: Data?
var unarchivedKeyCombo: KeyCombo?
// Shift + v
oldKeyCombo = v2_0_0KeyCombo(keyCode: kVK_ANSI_V, modifiers: shiftKey, doubledModifiers: false)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .v)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// F3
oldKeyCombo = v2_0_0KeyCombo(keyCode: kVK_F3, modifiers: Int(NSEvent.ModifierFlags.function.rawValue), doubledModifiers: false)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .f3)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, Int(NSEvent.ModifierFlags.function.rawValue))
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// Control double tap
oldKeyCombo = v2_0_0KeyCombo(keyCode: 0, modifiers: controlKey, doubledModifiers: true)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .a)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, controlKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, true)
// Shift + @
oldKeyCombo = v2_0_0KeyCombo(keyCode: Int(Key.atSign.QWERTYKeyCode), modifiers: shiftKey, doubledModifiers: false)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .leftBracket)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
}
func testCodableMigrationV3_1() throws {
var oldKeyCombo: v3_1_0KeyCombo?
var archivedData: Data?
var unarchivedKeyCombo: KeyCombo?
// Shift + v
oldKeyCombo = v3_1_0KeyCombo(key: .v, modifiers: shiftKey, doubledModifiers: false)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .v)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// F3
oldKeyCombo = v3_1_0KeyCombo(key: .f3, modifiers: Int(NSEvent.ModifierFlags.function.rawValue), doubledModifiers: false)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .f3)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, Int(NSEvent.ModifierFlags.function.rawValue))
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
// Control double tap
oldKeyCombo = v3_1_0KeyCombo(key: .a, modifiers: controlKey, doubledModifiers: true)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .a)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, controlKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, true)
// Shift + @
oldKeyCombo = v3_1_0KeyCombo(key: .atSign, modifiers: shiftKey, doubledModifiers: false)
archivedData = try JSONEncoder().encode(oldKeyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(unarchivedKeyCombo?.key, .leftBracket)
XCTAssertEqual(unarchivedKeyCombo?.modifiers, shiftKey)
XCTAssertEqual(unarchivedKeyCombo?.doubledModifiers, false)
}
func testCodable() throws {
var keyCombo: KeyCombo?
var archivedData: Data?
var unarchivedKeyCombo: KeyCombo?
// Shift + Control + c
keyCombo = KeyCombo(key: .c, cocoaModifiers: [.shift, .control])
archivedData = try JSONEncoder().encode(keyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// F1
keyCombo = KeyCombo(key: .f1, cocoaModifiers: [])
archivedData = try JSONEncoder().encode(keyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// Option double tap
keyCombo = KeyCombo(doubledCocoaModifiers: [.option])
archivedData = try JSONEncoder().encode(keyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// Shift + @
keyCombo = KeyCombo(key: .atSign, cocoaModifiers: [.shift])
archivedData = try JSONEncoder().encode(keyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
// Control + [
keyCombo = KeyCombo(key: .leftBracket, cocoaModifiers: [.control])
archivedData = try JSONEncoder().encode(keyCombo!)
unarchivedKeyCombo = try JSONDecoder().decode(KeyCombo.self, from: archivedData!)
XCTAssertNotNil(unarchivedKeyCombo)
XCTAssertEqual(keyCombo, unarchivedKeyCombo)
}
}
| mit | 04e2f811b2d8ad3a298c13bfc0b71b67 | 50.539846 | 135 | 0.688214 | 5.382282 | false | true | false | false |
turingcorp/gattaca | gattaca/View/Basic/VToast.swift | 1 | 4032 | import UIKit
class VToast:UIView
{
private static let kHeight:CGFloat = 60
private weak var timer:Timer?
private let kAnimationDuration:TimeInterval = 0.4
private let kTimeOut:TimeInterval = 3.5
private let kFontSize:CGFloat = 17
private let kLabelMargin:CGFloat = 15
class func messageFail(message:String)
{
VToast.message(message:message, color:UIColor.colourFail)
}
class func messageSuccess(message:String)
{
VToast.message(message:message, color:UIColor.colourSuccess)
}
private class func message(message:String, color:UIColor)
{
DispatchQueue.main.async
{
let toast:VToast = VToast(
message:message,
color:color)
let rootView:UIView = UIApplication.shared.keyWindow!.rootViewController!.view
rootView.addSubview(toast)
let screenHeight:CGFloat = UIScreen.main.bounds.size.height
let remain:CGFloat = screenHeight - kHeight
let top:CGFloat = remain / 2.0
NSLayoutConstraint.topToTop(
view:toast,
toView:rootView,
constant:top)
NSLayoutConstraint.equalsHorizontal(
view:toast,
toView:rootView)
NSLayoutConstraint.height(
view:toast,
constant:kHeight)
rootView.layoutIfNeeded()
toast.animate(open:true)
}
}
private convenience init(message:String, color:UIColor)
{
self.init()
clipsToBounds = true
backgroundColor = color
alpha = 0
translatesAutoresizingMaskIntoConstraints = false
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.bold(size:kFontSize)
label.textColor = UIColor.white
label.textAlignment = NSTextAlignment.center
label.numberOfLines = 0
label.backgroundColor = UIColor.clear
label.text = message
let button:UIButton = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.clear
button.addTarget(
self,
action:#selector(actionButton(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(label)
addSubview(button)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self,
margin:kLabelMargin)
}
func alertTimeOut(sender timer:Timer?)
{
timer?.invalidate()
animate(open:false)
}
//MARK: selectors
func actionButton(sender button:UIButton)
{
button.isUserInteractionEnabled = false
timer?.invalidate()
alertTimeOut(sender:timer)
}
//MARK: private
private func scheduleTimer()
{
self.timer = Timer.scheduledTimer(
timeInterval:kTimeOut,
target:self,
selector:#selector(alertTimeOut(sender:)),
userInfo:nil,
repeats:false)
}
private func animate(open:Bool)
{
let alpha:CGFloat
if open
{
alpha = 1
}
else
{
alpha = 0
}
UIView.animate(
withDuration:kAnimationDuration,
animations:
{ [weak self] in
self?.alpha = alpha
})
{ [weak self] (done:Bool) in
if open
{
self?.scheduleTimer()
}
else
{
self?.removeFromSuperview()
}
}
}
}
| mit | 332a5bb3ae842b129b7c9257d0b29f8a | 25.88 | 90 | 0.547371 | 5.639161 | false | false | false | false |
embryoconcepts/TIY-Assignments | 37 -- Venue Menu/VenueMenu/VenueMenu/VenueSearchViewController.swift | 1 | 3053 | //
// VenueSearchViewController.swift
// VenueMenu
//
// Created by Jennifer Hamilton on 11/25/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
protocol FoursquareAPIResultsProtocol
{
func didReceiveFoursquareAPIResults(results: NSDictionary)
}
class VenueSearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, FoursquareAPIResultsProtocol
{
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var tableView: UITableView!
var delegate: VenueSearchDelegate?
var venues = [NSManagedObject]()
var apiDelegate: APIController!
override func viewDidLoad()
{
super.viewDidLoad()
title = "Venue Search"
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Search Bar
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
let term = searchBar.text
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
searchQueryToAPIController(term!)
}
// MARK: - Foursquare API
func searchQueryToAPIController(searchTerm: String)
{
self.apiDelegate = APIController(foursquareDelegate: self)
apiDelegate.searchFoursquareFor(searchTerm)
}
func didReceiveFoursquareAPIResults(results: NSDictionary)
{
var venuesArray = [NSManagedObject]()
venuesArray = Venue.searchResultsJSON(results)
self.venues = venuesArray
tableView.reloadData()
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return venues.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let cell = tableView.dequeueReusableCellWithIdentifier("SearchResultCell", forIndexPath: indexPath)
let aVenue = venues[indexPath.row]
cell.textLabel!.text = aVenue.valueForKey("name") as? String
cell.detailTextLabel!.text = aVenue.valueForKey("address") as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let venue = venues[indexPath.row]
delegate?.venueWasSelected(venue)
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Action Handlers
@IBAction func cancelButtonPressed(sender: UIBarButtonItem)
{
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| cc0-1.0 | 537dadb72fe432fd3df1b05f272056ec | 27.523364 | 144 | 0.687746 | 5.620626 | false | false | false | false |
Alamofire/Alamofire | Tests/AuthenticationTests.swift | 1 | 7127 | //
// AuthenticationTests.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import Foundation
import XCTest
final class BasicAuthenticationTestCase: BaseTestCase {
func testHTTPBasicAuthenticationFailsWithInvalidCredentials() {
// Given
let session = Session()
let endpoint = Endpoint.basicAuth()
let expectation = self.expectation(description: "\(endpoint.url) 401")
var response: DataResponse<Data?, AFError>?
// When
session.request(endpoint)
.authenticate(username: "invalid", password: "credentials")
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertEqual(response?.response?.statusCode, 401)
XCTAssertNil(response?.data)
XCTAssertNil(response?.error)
}
func testHTTPBasicAuthenticationWithValidCredentials() {
// Given
let session = Session()
let user = "user1", password = "password"
let endpoint = Endpoint.basicAuth(forUser: user, password: password)
let expectation = self.expectation(description: "\(endpoint.url) 200")
var response: DataResponse<Data?, AFError>?
// When
session.request(endpoint)
.authenticate(username: user, password: password)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertEqual(response?.response?.statusCode, 200)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
}
func testHTTPBasicAuthenticationWithStoredCredentials() {
// Given
let session = Session()
let user = "user2", password = "password"
let endpoint = Endpoint.basicAuth(forUser: user, password: password)
let expectation = self.expectation(description: "\(endpoint.url) 200")
var response: DataResponse<Data?, AFError>?
// When
let credential = URLCredential(user: user, password: password, persistence: .forSession)
URLCredentialStorage.shared.setDefaultCredential(credential,
for: .init(host: endpoint.host.rawValue,
port: endpoint.port,
protocol: endpoint.scheme.rawValue,
realm: endpoint.host.rawValue,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic))
session.request(endpoint)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertEqual(response?.response?.statusCode, 200)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
}
func testHiddenHTTPBasicAuthentication() {
// Given
let session = Session()
let endpoint = Endpoint.hiddenBasicAuth()
let expectation = self.expectation(description: "\(endpoint.url) 200")
var response: DataResponse<Data?, AFError>?
// When
session.request(endpoint)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertEqual(response?.response?.statusCode, 200)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
}
}
// MARK: -
// Disabled due to HTTPBin flakiness.
final class HTTPDigestAuthenticationTestCase: BaseTestCase {
func _testHTTPDigestAuthenticationWithInvalidCredentials() {
// Given
let session = Session()
let endpoint = Endpoint.digestAuth()
let expectation = self.expectation(description: "\(endpoint.url) 401")
var response: DataResponse<Data?, AFError>?
// When
session.request(endpoint)
.authenticate(username: "invalid", password: "credentials")
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertEqual(response?.response?.statusCode, 401)
XCTAssertNil(response?.data)
XCTAssertNil(response?.error)
}
func _testHTTPDigestAuthenticationWithValidCredentials() {
// Given
let session = Session()
let user = "user", password = "password"
let endpoint = Endpoint.digestAuth(forUser: user, password: password)
let expectation = self.expectation(description: "\(endpoint.url) 200")
var response: DataResponse<Data?, AFError>?
// When
session.request(endpoint)
.authenticate(username: user, password: password)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertEqual(response?.response?.statusCode, 200)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
}
}
| mit | 4881ff15b577047d9f4083033f883f93 | 34.994949 | 126 | 0.620317 | 5.448777 | false | true | false | false |
expiredchocolate/SJWebView | SJWebview/SJWebView.swift | 1 | 8391 | //
// SJWebView.swift
// SJWebview
//
// Created by 过保的chocolate on 2017/4/18.
// Copyright © 2017年 SJ. All rights reserved.
//
import UIKit
import WebKit
import SnapKit
/* 使用前必读:
* 所有可配置的参数均要在 webView 开始加载到视图上之前配置
* 可配置参数:
* 1.scriptName 需要注册H5的名字(有交互的H5 必填)
* 2.scriptArray 注入JS 的参数(有注入JS的H5 必填)
* 3.cachePolicy 缓存策略(默认不使用缓存 选填)
* 4.progressColor 进度条颜色(默认是橙色 选填)
* 回调的参数:
* 1.startRequestHandler 开始加载
* 2.didFinishLoadHandler 完成加载
* 3.userContentAction H5传回的参数
* 配置步骤:
* 1.配置必要的参数
* 2.将webview 添加进视图
* 3.调用 startLoading() 发起请求
* 4.监听回调
*
* 有使用问题或者是建议欢迎写在这里 https://github.com/expiredchocolate/SJWebView/issues
*/
typealias ScriptResult = (userContentController: WKUserContentController, receiveMessage: WKScriptMessage)
class SJWebview: UIView {
public var scriptName: String?
/// 存放JS 的数组
public var scriptArray: [String] = []
/// 开始加载
public var startRequestHandler: (() -> Void)?
/// 完成加载
public var didFinishLoadHandler: (() ->Void)?
/// 缓存策略 default is no Caache
public var cachePolicy: NSURLRequest.CachePolicy = .reloadIgnoringLocalAndRemoteCacheData
/// 进度条颜色 defaule is orangeColor
public var progressColor: UIColor = .orange
/// 存放请求地址的数组
fileprivate var snapShotsArray: [(request: URLRequest,view: UIView)] = []
/// H5的传值回调
fileprivate var scriptHandler: ((ScriptResult) -> Void)?
lazy var webView: WKWebView = {
let webView: WKWebView
if let scriptName = self.scriptName {
let userContentController: WKUserContentController = WKUserContentController()
userContentController.add(self, name: scriptName)
// 注入js
for script in self.scriptArray {
let userScript: WKUserScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: true)
userContentController.addUserScript(userScript)
}
// WKWebView的配置
let configuration: WKWebViewConfiguration = WKWebViewConfiguration()
configuration.userContentController = userContentController
// 显示WKWebView
webView = WKWebView(frame: .zero, configuration: configuration)
} else {
webView = WKWebView(frame: .zero)
}
// 设置代理
webView.navigationDelegate = self
webView.uiDelegate = self
// 开启手势 后退前进
webView.allowsBackForwardNavigationGestures = true
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
return webView
}()
/// 进度条
fileprivate lazy var progressView: UIProgressView = {
let view: UIProgressView = UIProgressView()
view.tintColor = self.progressColor
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
setupViews()
}
/// 开始发起请求
///
/// - Parameters:
/// - urlString: 请求的地址
/// - unLoad: 没有地址不能加载
public func startLoading(_ urlString: String, unLoad: @escaping (()-> Void)) {
guard let url = URL.init(string: urlString) else {
unLoad()
return
}
// 设置请求缓存策略
let request: URLRequest = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: 10.0)
// 发起请求
webView.load(request)
}
/// H5回调
public func userContentAction(webView didReceive: @escaping ((_ userContentController: WKUserContentController, _ receiveMessage: WKScriptMessage) -> Void)) {
scriptHandler = didReceive
}
/// 调用H5的方法
public func evaluateJavaScript(_ source: String) {
webView.evaluateJavaScript(source) { (any, error) in
print("----- 回调H5方法成功\(source)")
}
}
/// 监听进度条
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.estimatedProgress) {
progressView.alpha = 1.0
progressView.setProgress(Float(webView.estimatedProgress), animated: true)
if webView.estimatedProgress >= 1.0 {
UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseOut, animations: {
self.progressView.alpha = 0.0
}, completion: { (finfished: Bool) in
self.progressView.setProgress(0.0, animated: false)
})
}
}
}
deinit {
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
if let scriptName = scriptName {
webView.configuration.userContentController.removeScriptMessageHandler(forName: scriptName)
}
webView.navigationDelegate = nil
webView.uiDelegate = nil
}
}
// MARK: UI
extension SJWebview {
fileprivate func setupViews() {
addSubview(webView)
webView.snp.makeConstraints { (maker) in
maker.edges.equalToSuperview()
}
addSubview(progressView)
progressView.snp.makeConstraints { (maker) in
maker.top.left.right.equalToSuperview()
maker.height.equalTo(3)
}
}
/// 请求链接处理
func pushCurrentSnapshotView(WithRequest request: URLRequest) {
let lastRequest: URLRequest? = snapShotsArray.last?.request
if request.url?.absoluteString == "about:blank" { return }
// 如果url一样就不进行push
if lastRequest?.url?.absoluteString == request.url?.absoluteString { return }
if let currentSnapShotView: UIView = self.webView.snapshotView(afterScreenUpdates: true) {
snapShotsArray.append((request: request, view:currentSnapShotView))
}
}
}
// MARK: - WKScriptMessageHandler 协议
extension SJWebview: WKScriptMessageHandler {
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == scriptName {
scriptHandler?(userContentController: userContentController, receiveMessage: message)
} else {
print("----- 未执行 js 方法, 方法名不匹配: \(message.name)")
}
}
// H5的弹窗信息
public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
print("----- H5的信息是:\(message)")
completionHandler()
}
// 完成加载
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("----- H5页面加载完成")
didFinishLoadHandler?()
}
}
extension SJWebview: WKNavigationDelegate {
// 开始加载时
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
progressView.isHidden = false
}
// 服务器开始请求的时候调用
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
switch navigationAction.navigationType {
case .linkActivated, .formSubmitted, .other:
pushCurrentSnapshotView(WithRequest: navigationAction.request)
default: break
}
startRequestHandler?()
decisionHandler(.allow)
}
}
extension SJWebview: WKUIDelegate {
}
| mit | a872592eb57ff62f918da648942b9d8e | 30.958678 | 177 | 0.621541 | 4.954516 | false | false | false | false |
tottakai/Thongs | Thongs/Classes/Thongs.swift | 1 | 3510 | import Foundation
public enum Thongs {
public typealias Composer = (NSAttributedString) -> NSAttributedString
public static func string(_ string: String) -> NSAttributedString {
return NSAttributedString(string: string)
}
public static func font(_ font: UIFont) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.beginEditing()
s.addAttribute(NSAttributedStringKey.font, value: font, range: NSMakeRange(0, attributedString.length))
s.endEditing()
return s
}
}
public static func color(_ color: UIColor) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSMakeRange(0, attributedString.length))
return s
}
}
public static func kerning(_ kerning: Double) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSAttributedStringKey.kern, value: kerning, range: NSMakeRange(0, attributedString.length))
return s
}
}
public static func underline(_ color: UIColor, style: NSUnderlineStyle) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSAttributedStringKey.underlineColor, value: color, range: NSMakeRange(0, attributedString.length))
s.addAttribute(NSAttributedStringKey.underlineStyle, value: style.rawValue, range: NSMakeRange(0, attributedString.length))
return s
}
}
public static func strikethrough(_ color: UIColor, style: NSUnderlineStyle) -> Composer {
return { attributedString in
let s = attributedString.mutableCopy() as! NSMutableAttributedString
s.addAttribute(NSAttributedStringKey.strikethroughColor, value: color, range: NSMakeRange(0, attributedString.length))
s.addAttribute(NSAttributedStringKey.strikethroughStyle, value: style.rawValue, range: NSMakeRange(0, attributedString.length))
return s
}
}
public static func concat(_ comp1: NSAttributedString) -> Composer {
return { comp2 in
let s = comp1.mutableCopy() as! NSMutableAttributedString
s.append(comp2)
return s
}
}
}
// Operators
precedencegroup LiftPrecedence {
associativity: left
higherThan: ConcatenationPrecedence
}
infix operator ~~> : LiftPrecedence
public func ~~> (composer: @escaping Thongs.Composer, text: String) -> NSAttributedString {
return { composer(Thongs.string(text)) }()
}
precedencegroup CompositionPrecedence {
associativity: left
higherThan: LiftPrecedence
}
infix operator <*> : CompositionPrecedence
public func <*> (composer1: @escaping Thongs.Composer, composer2: @escaping Thongs.Composer) -> Thongs.Composer {
return { str in
composer2(composer1(str))
}
}
//concat(a)(b)
precedencegroup ConcatenationPrecedence {
associativity: right
higherThan: AssignmentPrecedence
}
infix operator <+> : ConcatenationPrecedence
public func <+> (text1: NSAttributedString, text2: NSAttributedString) -> NSAttributedString {
return Thongs.concat(text1)(text2)
}
| mit | 381ac88d0dfe2e1106c4b14f529e27e1 | 33.07767 | 139 | 0.683191 | 5.358779 | false | false | false | false |
Tatoeba/tatoeba-ios | Tatoeba/Models/Library.swift | 1 | 1054 | //
// Library.swift
// Tatoeba
//
// Created by Jack Cook on 8/12/17.
// Copyright © 2017 Tatoeba. All rights reserved.
//
import Foundation
struct Library {
let name: String
let license: String
init(data: [String: String]) {
guard let name = data["Name"], let license = data["License"] else {
fatalError("Error loading libraries from plist file")
}
self.name = name
self.license = license.replacingOccurrences(of: "\\n", with: "\n")
}
static func loadAllLibraries() -> [Library] {
if let url = Bundle.main.url(forResource: "Libraries", withExtension: "plist"), let contents = NSArray(contentsOf: url) as? [[String: String]] {
var libraries = [Library]()
for data in contents {
let library = Library(data: data)
libraries.append(library)
}
return libraries.sorted(by: { $0.name < $1.name })
}
return [Library]()
}
}
| mit | 7d87abb950d930d738ae60bf06f93c18 | 26 | 152 | 0.54226 | 4.35124 | false | false | false | false |
brentdax/swift | stdlib/public/SDK/MetalKit/MetalKit.swift | 20 | 1797 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import MetalKit // Clang module
@available(macOS 10.11, iOS 9.0, tvOS 9.0, *)
extension MTKMesh {
public class func newMeshes(asset: MDLAsset, device: MTLDevice) throws -> (modelIOMeshes: [MDLMesh], metalKitMeshes: [MTKMesh]) {
var modelIOMeshes: NSArray?
let metalKitMeshes = try MTKMesh.__newMeshes(from: asset, device: device, sourceMeshes: &modelIOMeshes)
return (modelIOMeshes: modelIOMeshes as! [MDLMesh], metalKitMeshes: metalKitMeshes)
}
}
@available(swift 4)
@available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
public func MTKModelIOVertexDescriptorFromMetalWithError(_ metalDescriptor: MTLVertexDescriptor) throws -> MDLVertexDescriptor {
var error: NSError? = nil
let result = __MTKModelIOVertexDescriptorFromMetalWithError(metalDescriptor, &error)
if let error = error {
throw error
}
return result
}
@available(swift 4)
@available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
public func MTKMetalVertexDescriptorFromModelIOWithError(_ modelIODescriptor: MDLVertexDescriptor) throws -> MTLVertexDescriptor? {
var error: NSError? = nil
let result = __MTKMetalVertexDescriptorFromModelIOWithError(modelIODescriptor, &error)
if let error = error {
throw error
}
return result
}
| apache-2.0 | 33df7c25a705fd5e37e3c82217e6372f | 39.840909 | 133 | 0.664997 | 4.382927 | false | false | false | false |
moove-it/step-control-ios | step-control-ios/Constants.swift | 1 | 375 | import UIKit
struct Constants {
struct Colors {
static let foregroundCGColor = UIColor.white.cgColor
static let unselectedCGColor = UIColor.gray.cgColor
static let selectedCGColor = UIColor.orange.cgColor
static let completedCGColor = UIColor.orange.cgColor
static let selectedColor = UIColor.orange
static let unselectedColor = UIColor.gray
}
}
| mit | ad5f56cfb11151abfb3ed27cc9b3989b | 30.25 | 56 | 0.762667 | 4.87013 | false | false | false | false |
wang-chuanhui/CHSDK | Add/RefreshControl/RefreshControl.swift | 1 | 7588 | //
// RefreshControl.swift
// CHSDK
//
// Created by 王传辉 on 2017/8/4.
// Copyright © 2017年 王传辉. All rights reserved.
//
import UIKit
open class RefreshControl: UIControl {
var beginRefreshingCompletion: (() -> ())?
var endRefreshingCompletion: (() -> ())?
var refreshingBegin: (() -> ())?
weak var scrollView: UIScrollView?
var originalInset = UIEdgeInsets.zero
var panGestureRecognizer: UIPanGestureRecognizer?
var isRefreshing: Bool {
return refreshState == .refreshing || refreshState == .willRefresh
}
var refreshState: RefreshState = .idle {
didSet {
if refreshState == oldValue {
return
}
content.refreshState = refreshState
refreshStateDidChange(newState: refreshState, oldState: oldValue)
DispatchQueue.main.async {
self.setNeedsLayout()
}
}
}
var pullingPercent: CGFloat = 0.0 {
didSet {
content.pullingPercent = pullingPercent
}
}
var content: RefreshContentProtocol
public convenience init() {
self.init(frame: CGRect.zero)
}
public override init(frame: CGRect) {
content = type(of: self).contentType.init()
super.init(frame: frame)
if let view = content as? UIView {
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
view.topAnchor.constraint(equalTo: topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
prepare()
}
public required init?(coder aDecoder: NSCoder) {
content = RefreshControl.contentType.init()
super.init(coder: aDecoder)
if let view = content as? UIView {
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
view.topAnchor.constraint(equalTo: topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
prepare()
}
public convenience init(refreshingBegin: @escaping (() -> ())) {
self.init(frame: CGRect.zero)
self.refreshingBegin = refreshingBegin
}
public convenience init(target: Any, action: Selector) {
self.init(frame: CGRect.zero)
addTarget(target, action: action)
}
open class var contentType: RefreshContentProtocol.Type {
return RefreshContentView.self
}
open func refreshStateDidChange(newState: RefreshState, oldState: RefreshState) {
}
}
extension RefreshControl {
open override func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents = .valueChanged) {
super.addTarget(target, action: action, for: controlEvents)
}
open override func removeTarget(_ target: Any?, action: Selector?, for controlEvents: UIControlEvents = .valueChanged) {
super.removeTarget(target, action: action, for: controlEvents)
}
}
extension RefreshControl {
open func prepare() {
autoresizingMask = .flexibleWidth
backgroundColor = UIColor.clear
}
open override func layoutSubviews() {
placeSubviews()
super.layoutSubviews()
}
open func placeSubviews() {
}
}
extension RefreshControl {
public func beginRefreshing(with completion: (() -> ())? = nil) {
beginRefreshingCompletion = completion
DispatchQueue.main.async {
UIView.animate(withDuration: RefreshConfig.fastAnimationDuration) {
self.alpha = 1
}
self.pullingPercent = 1
if self.window != nil {
self.refreshState = .refreshing
}else {
if self.refreshState != .refreshing {
self.refreshState = .willRefresh
self.setNeedsDisplay()
}
}
}
}
public func endRefreshing(with completion: (() -> ())? = nil) {
endRefreshingCompletion = completion
DispatchQueue.main.async {
self.refreshState = .idle
}
}
func executeRefreshingBegin() {
DispatchQueue.main.async {[weak self] in
self?.refreshingBegin?()
self?.sendActions(for: UIControlEvents.valueChanged)
self?.beginRefreshingCompletion?()
}
}
}
extension RefreshControl {
open func scrollViewContentOffsetDidChange(_ change: [NSKeyValueChangeKey: Any]?) {
}
open func scrollViewContentSizeDidChange(_ change: [NSKeyValueChangeKey: Any]?) {
}
open func scrollViewPanStateDidChange(_ change: [NSKeyValueChangeKey: Any]?) {
}
}
extension RefreshControl {
open override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
removeObservers()
guard let scrollView = newSuperview as? UIScrollView else {
return
}
var frame = self.frame
frame.origin.x = 0
frame.size.width = scrollView.frame.width
self.frame = frame
self.scrollView = scrollView
scrollView.alwaysBounceVertical = true
originalInset = scrollView.contentInset
addObservers()
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
if refreshState == .willRefresh {
refreshState = .refreshing
}
}
}
extension RefreshControl {
func addObservers() {
let options: NSKeyValueObservingOptions = [.new, .old]
scrollView?.addObserver(self, forKeyPath: RefreshConfig.contentOffset, options: options, context: nil)
scrollView?.addObserver(self, forKeyPath: RefreshConfig.contentSize, options: options, context: nil)
panGestureRecognizer = scrollView?.panGestureRecognizer
panGestureRecognizer?.addObserver(self, forKeyPath: RefreshConfig.panState, options: options, context: nil)
}
func removeObservers() {
scrollView?.removeObserver(self, forKeyPath: RefreshConfig.contentSize)
scrollView?.removeObserver(self, forKeyPath: RefreshConfig.contentOffset)
panGestureRecognizer?.removeObserver(self, forKeyPath: RefreshConfig.panState)
panGestureRecognizer = nil
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if isUserInteractionEnabled == false {
return
}
switch keyPath ?? "" {
case RefreshConfig.contentSize:
scrollViewContentSizeDidChange(change)
case RefreshConfig.contentOffset:
if isHidden {
break
}
scrollViewContentOffsetDidChange(change)
case RefreshConfig.panState:
if isHidden {
break
}
scrollViewPanStateDidChange(change)
default:
break
}
}
}
| mit | 0586a88e0aba748ad6066c854d1d6a4a | 26.241007 | 156 | 0.610722 | 5.568382 | false | false | false | false |
inoity/nariko | Nariko/Classes/BubbleControl.swift | 1 | 13200 | //
// BubbleControl.swift
// BubbleControl-Swift
//
// Created by Cem Olcay on 11/12/14.
// Copyright (c) 2014 Cem Olcay. All rights reserved.
//
import UIKit
// MARK: - Animation Constants
private let BubbleControlMoveAnimationDuration: TimeInterval = 0.5
private let BubbleControlSpringDamping: CGFloat = 0.6
private let BubbleControlSpringVelocity: CGFloat = 0.6
let closeButton = UIButton(frame: CGRect(x: 0, y: 20, width: 40, height: 40))
// MARK: - UIView Extension
extension UIView {
// MARK: Frame Extensions
var x: CGFloat {
get {
return self.frame.origin.x
} set (value) {
self.frame = CGRect (x: value, y: self.y, width: self.w, height: self.h)
}
}
var y: CGFloat {
get {
return self.frame.origin.y
} set (value) {
self.frame = CGRect (x: self.x, y: value, width: self.w, height: self.h)
}
}
var w: CGFloat {
get {
return self.frame.size.width
} set (value) {
self.frame = CGRect (x: self.x, y: self.y, width: value, height: self.h)
}
}
var h: CGFloat {
get {
return self.frame.size.height
} set (value) {
self.frame = CGRect (x: self.x, y: self.y, width: self.w, height: value)
}
}
var position: CGPoint {
get {
return self.frame.origin
} set (value) {
self.frame = CGRect (origin: value, size: self.frame.size)
}
}
var size: CGSize {
get {
return self.frame.size
} set (value) {
self.frame = CGRect (origin: self.frame.origin, size: size)
}
}
var left: CGFloat {
get {
return self.x
} set (value) {
self.x = value
}
}
var right: CGFloat {
get {
return self.x + self.w
} set (value) {
self.x = value - self.w
}
}
var top: CGFloat {
get {
return self.y
} set (value) {
self.y = value
}
}
var bottom: CGFloat {
get {
return self.y + self.h
} set (value) {
self.y = value - self.h
}
}
func leftWithOffset (_ offset: CGFloat) -> CGFloat {
return self.left - offset
}
func rightWithOffset (_ offset: CGFloat) -> CGFloat {
return self.right + offset
}
func topWithOffset (_ offset: CGFloat) -> CGFloat {
return self.top - offset
}
func botttomWithOffset (_ offset: CGFloat) -> CGFloat {
return self.bottom + offset
}
func spring (_ animations: @escaping ()->Void, completion:((Bool)->Void)?) {
UIView.animate(withDuration: BubbleControlMoveAnimationDuration,
delay: 0,
usingSpringWithDamping: BubbleControlSpringDamping,
initialSpringVelocity: BubbleControlSpringVelocity,
options: UIViewAnimationOptions(),
animations: animations,
completion: completion)
}
func moveY (_ y: CGFloat) {
var moveRect = self.frame
moveRect.origin.y = y
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func moveX (_ x: CGFloat) {
var moveRect = self.frame
moveRect.origin.x = x
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func movePoint (_ x: CGFloat, y: CGFloat) {
var moveRect = self.frame
moveRect.origin.x = x
moveRect.origin.y = y
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func movePoint (_ point: CGPoint) {
var moveRect = self.frame
moveRect.origin = point
spring({ () -> Void in
self.frame = moveRect
}, completion: nil)
}
func setScale(_ s: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DScale(transform, s, s, s)
self.layer.transform = transform
}
func alphaTo(_ to: CGFloat) {
UIView.animate(withDuration: BubbleControlMoveAnimationDuration,
animations: {
self.alpha = to
})
}
func bubble() {
self.setScale(1.2)
spring({ () -> Void in
self.setScale(1)
}, completion: nil)
}
}
// MARK: - BubbleControl
class BubbleControl: UIControl {
var WINDOW: UIWindow?
var screenShot: UIImage?
// MARK: Constants
let snapOffsetMin: CGFloat = 0
let snapOffsetMax: CGFloat = 0
// MARK: Optionals
var contentView: UIView?
var snapsInside: Bool = false
var movesBottom: Bool = false
// MARK: Actions
var didToggle: ((Bool) -> ())?
var didNavigationBarButtonPressed: (() -> ())?
var setOpenAnimation: ((_ contentView: UIView, _ backgroundView: UIView?)->())?
var setCloseAnimation: ((_ contentView: UIView, _ backgroundView: UIView?) -> ())?
// MARK: Bubble State
enum BubbleControlState {
case snap // snapped to edge
case drag // dragging around
}
var bubbleState: BubbleControlState = .snap {
didSet {
if bubbleState == .snap {
setupSnapInsideTimer()
} else {
snapOffset = snapOffsetMin
}
}
}
// MARK: Snap
fileprivate var snapOffset: CGFloat!
fileprivate var snapInTimer: Timer?
fileprivate var snapInInterval: TimeInterval = 2
// MARK: Toggle
fileprivate var positionBeforeToggle: CGPoint?
var toggle: Bool = false {
didSet {
didToggle? (toggle)
if toggle {
openContentView()
} else {
closeContentView()
}
}
}
// MARK: Image
var imageView: UIImageView?
var image: UIImage? {
didSet {
imageView?.image = image
}
}
// MARK: Init
init (win: UIWindow, size: CGSize) {
super.init(frame: CGRect (origin: CGPoint.zero, size: size))
defaultInit(win)
}
init (win: UIWindow, image: UIImage) {
let size = image.size
super.init(frame: CGRect (origin: CGPoint.zero, size: size))
self.image = image
defaultInit(win)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
func defaultInit (_ win: UIWindow) {
self.WINDOW = win
// self
snapOffset = snapOffsetMin
layer.cornerRadius = w/2
// image view
imageView = UIImageView(frame:CGRect(x: 50, y: 0, width: size.width - 50, height: size.height))
imageView?.isUserInteractionEnabled = false
imageView?.clipsToBounds = true
addSubview(imageView!)
closeButton.setTitle("✕", for: .normal)
closeButton.titleLabel!.font = UIFont.systemFont(ofSize: 16)
closeButton.setTitleColor(UIColor.white, for: .normal)
closeButton.backgroundColor = UIColor.black
closeButton.layer.cornerRadius = 20
closeButton.addTarget(NarikoTool.sharedInstance, action: #selector(NarikoTool.removeBubbleForce), for: .touchUpInside)
closeButton.isHidden = true
addSubview(closeButton)
// events
addTarget(self, action: #selector(BubbleControl.touchDown), for: UIControlEvents.touchDown)
addTarget(self, action: #selector(BubbleControl.touchUp), for: UIControlEvents.touchUpInside)
addTarget(self, action: #selector(BubbleControl.touchDrag(_:event:)), for: UIControlEvents.touchDragInside)
// place
center.x = WINDOW!.w - w/2 + snapOffset
center.y = 84 + h/2
snap()
}
// MARK: Snap To Edge
func snap() {
var targetX = WINDOW!.leftWithOffset(snapOffset + 50)
if center.x > WINDOW!.w/2 {
targetX = WINDOW!.rightWithOffset(snapOffset) - w
}
// move to snap position
moveX(targetX)
}
func snapInside() {
print("snap inside !")
if !toggle && bubbleState == .snap {
snapOffset = snapOffsetMax
snap()
}
}
func setupSnapInsideTimer() {
if !snapsInside {
return
}
if let timer = snapInTimer {
if timer.isValid {
timer.invalidate()
}
}
snapInTimer = Timer.scheduledTimer(timeInterval: snapInInterval,
target: self,
selector: #selector(BubbleControl.snapInside),
userInfo: nil,
repeats: false)
}
func lockInWindowBounds() {
if top < 64 {
var rect = frame
rect.origin.y = 64
frame = rect
}
if left < -50 {
var rect = frame
rect.origin.x = -50
frame = rect
}
if bottom > WINDOW!.h {
var rect = frame
rect.origin.y = WINDOW!.botttomWithOffset(-h)
frame = rect
}
if right > WINDOW!.w {
var rect = frame
rect.origin.x = WINDOW!.rightWithOffset(-w)
frame = rect
}
}
// MARK: Events
func touchDown() {
bubble()
}
func touchUp() {
if bubbleState == .snap {
toggle = !toggle
} else {
bubbleState = .snap
snap()
}
}
func touchDrag (_ sender: BubbleControl, event: UIEvent) {
if closeButton.isHidden {
bubbleState = .drag
if toggle {
toggle = false
}
let touch = event.allTouches!.first!
if touch.location(in: nil).x == touch.previousLocation(in: nil).x && touch.location(in: nil).y == touch.previousLocation(in: nil).y{
bubbleState = .snap
} else {
let location = touch.location(in: WINDOW!)
center = location
lockInWindowBounds()
}
}
}
func navButtonPressed (_ sender: AnyObject) {
didNavigationBarButtonPressed? ()
}
func degreesToRadians (_ angle: CGFloat) -> CGFloat {
return (CGFloat (M_PI) * angle) / 180.0
}
// MARK: Toggle
func openContentView() {
if let v = contentView {
screenShotMethod()
let win = WINDOW!
win.addSubview(v)
win.bringSubview(toFront: self)
snapOffset = snapOffsetMin
snap()
positionBeforeToggle = frame.origin
if let anim = setOpenAnimation {
anim(v, win.subviews[0])
} else {
v.bottom = win.bottom
}
if movesBottom {
movePoint(CGPoint (x: win.center.x - w/2, y: win.bottom - h - snapOffset))
} else {
moveY(v.top - h - snapOffset)
}
closeButton.isHidden = false
NarikoTool.sharedInstance.textView.becomeFirstResponder()
}
}
func screenShotMethod() {
//Create the UIImage
print("shot")
self.isHidden = true
UIGraphicsBeginImageContext(WINDOW!.frame.size)
WINDOW!.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print(image)
screenShot = image
//Save it to the camera roll
// UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
self.isHidden = false
}
func closeContentView() {
if let v = contentView {
if let anim = setCloseAnimation {
anim (v, (WINDOW?.subviews[0])! as UIView)
} else {
v.removeFromSuperview()
}
if (bubbleState == .snap) {
setupSnapInsideTimer()
if positionBeforeToggle != nil {
movePoint(positionBeforeToggle!)
}
}
}
closeButton.isHidden = true
}
}
| mit | 5786365fe82fcd5b6b54979df58828aa | 24.627184 | 144 | 0.499015 | 4.95979 | false | false | false | false |
JasonPan/ADSSocialFeedScrollView | ADSSocialFeedScrollView/Providers/WordPress/Data/WordPressPost.swift | 1 | 4302 | //
// WordPressPost.swift
// ADSSocialFeedScrollView
//
// Created by Jason Pan on 7/03/2016.
// Copyright © 2016 ANT Development Studios. All rights reserved.
//
import Foundation
import StringExtensionHTML
class WordPressPost: PostProtocol {
var title: String
var excerptText: String!
var link: NSURL
var publishDate: NSDate!
var image: String!
var mediaURLString: String?
internal var retrieveCount = 0
//*********************************************************************************************************
// MARK: - Constructors
//*********************************************************************************************************
init(title: String, link: String, excerptText: String, publishDate: NSDate, mediaURLString: String?) {
self.title = title
self.link = NSURL(string: link)!
self.excerptText = excerptText
self.publishDate = publishDate
self.mediaURLString = mediaURLString
self.excerptText = self.excerptText.stringByReplacingOccurrencesOfString("\n", withString: "")
// self.retrieveCount = 0
}
//*********************************************************************************************************
// MARK: - PostProtocol
//*********************************************************************************************************
var createdAtDate: NSDate! {
return self.publishDate
}
//*********************************************************************************************************
// MARK: - Retrieve imageURLString from mediaURLString
//
// NOTE: - Lazy loading necessary due to delay caused by async retrieval. May change behaviour back
// to WordPressPostCollection in future release.
//*********************************************************************************************************
internal func retrieveImageSourceURLForPost(post: WordPressPost, completionHandler: () -> Void) {
if let mediaURLString = post.mediaURLString, requestURL = NSURL(string: mediaURLString) {
performGetRequest(requestURL, completion: {
data, HTTPStatusCode, error in
if let data = data, jsonString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
var str = jsonString.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: jsonString.rangeOfString(jsonString))
str = str.stringByDecodingHTMLEntities
let newStrippedData = str.dataUsingEncoding(NSUTF8StringEncoding)
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(newStrippedData!, options: NSJSONReadingOptions(rawValue: 0))
if let JSON = JSON as? NSDictionary {
let imageURLString = JSON["media_details"]?["sizes"]??["medium"]??["source_url"]
// let imageURLString = JSON["media_details"]?["sizes"]??["large"]??["source_url"]
print("imageURLString: \(imageURLString)")
post.image = imageURLString as? String
completionHandler()
}else {
print("JSON PARSE FAIL: \(JSON)")
completionHandler()
}
}catch {
// NOTE: Required for WordPress image retrieval issue - reattempts request.
self.retrieveImageSourceURLForPost(post, completionHandler: completionHandler)
// completionHandler()
}
}else {
completionHandler()
}
})
}else {
// TODO: Add handler
print("retrieving image for url failed: \(post.mediaURLString)")
completionHandler()
}
}
} | mit | ab4a17703a042cd4a23ecc846db075ac | 40.76699 | 184 | 0.474076 | 6.892628 | false | false | false | false |
natecook1000/swift | validation-test/stdlib/CollectionOld.swift | 3 | 6815 | // RUN: %target-run-simple-swift-swift3 --stdlib-unittest-in-process | tee %t.txt
// RUN: %FileCheck %s < %t.txt
// note: remove the --stdlib-unittest-in-process once all the FileCheck tests
// have been converted to StdlibUnittest
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
var CollectionTests = TestSuite("CollectionTests")
/// An *iterator* that adapts a *collection* `C` and any *sequence* of
/// its `Index` type to present the collection's elements in a
/// permuted order.
public struct PermutationGenerator<
C: Collection, Indices: Sequence
> : IteratorProtocol, Sequence where Indices.Element == C.Index {
var seq : C
var indices : Indices.Iterator
/// The type of element returned by `next()`.
public typealias Element = C.Element
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Precondition: No preceding call to `self.next()` has returned `nil`.
public mutating func next() -> Element? {
let result = indices.next()
return result != nil ? seq[result!] : .none
}
/// Construct an *iterator* over a permutation of `elements` given
/// by `indices`.
///
/// - Precondition: `elements[i]` is valid for every `i` in `indices`.
public init(elements: C, indices: Indices) {
self.seq = elements
self.indices = indices.makeIterator()
}
}
var foobar = MinimalCollection(elements: "foobar")
// CHECK: foobar
for a in foobar {
print(a, terminator: "")
}
print("")
// FIXME: separate r from the expression below pending
// <rdar://problem/15772601> Type checking failure
// CHECK: raboof
let i = foobar.indices
let r = i.lazy.reversed()
for a in PermutationGenerator(elements: foobar, indices: r) {
print(a, terminator: "")
}
print("")
func isPalindrome0<S: BidirectionalCollection>(_ seq: S) -> Bool
where S.Element : Equatable {
typealias Index = S.Index
let a = seq.indices
let i = seq.indices
let ir = i.lazy.reversed()
var b = ir.makeIterator()
for i in a {
if seq[i] != seq[b.next()!] {
return false
}
}
return true
}
// CHECK: false
print(isPalindrome0(MinimalBidirectionalCollection(elements: "GoHangaSalamiImaLasagneHoG")))
// CHECK: true
print(isPalindrome0(MinimalBidirectionalCollection(elements: "GoHangaSalamiimalaSagnaHoG")))
func isPalindrome1<
S : BidirectionalCollection
>(_ seq: S) -> Bool
where S.Element : Equatable {
let a = PermutationGenerator(elements: seq, indices: seq.indices)
var b = seq.lazy.reversed().makeIterator()
for nextChar in a {
if nextChar != b.next()! {
return false
}
}
return true
}
func isPalindrome1_5<S: BidirectionalCollection>(_ seq: S) -> Bool
where S.Element: Equatable {
var b = seq.lazy.reversed().makeIterator()
for nextChar in seq {
if nextChar != b.next()! {
return false
}
}
return true
}
// CHECK: false
print(isPalindrome1(MinimalBidirectionalCollection(elements: "MADAMINEDENIMWILLIAM")))
// CHECK: true
print(isPalindrome1(MinimalBidirectionalCollection(elements: "MadamInEdEnImadaM")))
// CHECK: false
print(isPalindrome1_5(MinimalBidirectionalCollection(elements: "FleetoMeRemoteelF")))
// CHECK: true
print(isPalindrome1_5(MinimalBidirectionalCollection(elements: "FleetoMeReMoteelF")))
// Finally, one that actually uses indexing to do half as much work.
// BidirectionalCollection traversal finally pays off!
func isPalindrome2<
S: BidirectionalCollection
>(_ seq: S) -> Bool
where
S.Element: Equatable {
var b = seq.startIndex, e = seq.endIndex
while (b != e) {
e = seq.index(before: e)
if (b == e) {
break
}
if seq[b] != seq[e] {
return false
}
b = seq.index(after: b)
}
return true
}
// Test even length
// CHECK: false
print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimarRamireZ")))
// CHECK: true
print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimaRRamireZ")))
// Test odd length
// CHECK: false
print(isPalindrome2(MinimalBidirectionalCollection(elements: "ZerimarORamireZ")))
// CHECK: true
print(isPalindrome2(MinimalBidirectionalCollection(elements: "Zerimar-O-ramireZ")))
func isPalindrome4<
S: BidirectionalCollection
>(_ seq: S) -> Bool
where
S.Element : Equatable {
typealias Index = S.Index
let a = PermutationGenerator(elements: seq, indices: seq.indices)
// FIXME: separate ri from the expression below pending
// <rdar://problem/15772601> Type checking failure
let i = seq.indices
let ri = i.lazy.reversed()
var b = PermutationGenerator(elements: seq, indices: ri)
for nextChar in a {
if nextChar != b.next()! {
return false
}
}
return true
}
// Can't put these literals into string interpolations pending
// <rdar://problem/16401145> hella-slow compilation
let array = [1, 2, 3, 4]
let dict = [0:0, 1:1, 2:2, 3:3, 4:4]
func testCount() {
// CHECK: testing count
print("testing count")
// CHECK-NEXT: random access: 4
print("random access: \(array.count)")
// CHECK-NEXT: bidirectional: 5
print("bidirectional: \(dict.count)")
}
testCount()
struct SequenceOnly<T : Sequence> : Sequence {
var base: T
func makeIterator() -> T.Iterator { return base.makeIterator() }
}
func testUnderestimatedCount() {
// CHECK: testing underestimatedCount
print("testing underestimatedCount")
// CHECK-NEXT: random access: 4
print("random access: \(array.underestimatedCount)")
// CHECK-NEXT: bidirectional: 5
print("bidirectional: \(dict.underestimatedCount)")
// CHECK-NEXT: Sequence only: 0
let s = SequenceOnly(base: array)
print("Sequence only: \(s.underestimatedCount)")
}
testUnderestimatedCount()
CollectionTests.test("isEmptyFirstLast") {
expectTrue((10..<10).isEmpty)
expectFalse((10...10).isEmpty)
expectEqual(10, (10..<100).first)
expectEqual(10, (10...100).first)
expectEqual(99, (10..<100).last)
expectEqual(100, (10...100).last)
}
/// A `Collection` that vends just the default implementations for
/// `CollectionType` methods.
struct CollectionOnly<T: Collection> : Collection {
var base: T
var startIndex: T.Index {
return base.startIndex
}
var endIndex: T.Index {
return base.endIndex
}
func makeIterator() -> T.Iterator {
return base.makeIterator()
}
subscript(position: T.Index) -> T.Element {
return base[position]
}
func index(after i: T.Index) -> T.Index { return base.index(after: i) }
}
// CHECK: all done.
print("all done.")
CollectionTests.test("first/performance") {
// accessing `first` should not perform duplicate work on lazy collections
var log: [Int] = []
let col_ = (0..<10).lazy.filter({ log.append($0); return (2..<8).contains($0) })
let col = CollectionOnly(base: col_)
expectEqual(2, col.first)
expectEqual([0, 1, 2], log)
}
runAllTests()
| apache-2.0 | e13f5a58ebbca5dedc86d371241d9b19 | 25.936759 | 92 | 0.694351 | 3.717949 | false | true | false | false |
AndyHT/TravelTips | iOSTravelTips/TravelTips/PlanTableViewController.swift | 1 | 7452 | //
// PlanTableViewController.swift
// TravelTips
//
// Created by Teng on 1/14/16.
// Copyright © 2016 huoteng. All rights reserved.
//
import UIKit
import DGElasticPullToRefresh
class PlanTableViewController: UITableViewController, AddNewPlanDelegate {
@IBOutlet var planTableView: UITableView!
var planArr:[Plan] = []
var isNeedReload = false
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
planArr.append(Plan(id: 1, lat: 30, lon: 120, name: "Shanghai", startDate: NSDate(), endDate: NSDate()))
let loadingView = DGElasticPullToRefreshLoadingViewCircle()
loadingView.tintColor = UIColor(red: 255/255.0, green: 208/255.0, blue: 80/255.0, alpha: 1.0)
planTableView.dg_addPullToRefreshWithActionHandler ({ [weak self] () -> Void in
print("Refreshing")
self!.planArr = []
self!.freshData()
self?.tableView.dg_stopLoading()
}, loadingView: loadingView)
tableView.dg_setPullToRefreshFillColor(UIColor(red: 59/255.0, green: 130/255.0, blue: 176/255.0, alpha: 1.0))
tableView.dg_setPullToRefreshBackgroundColor(tableView.backgroundColor!)
}
func addNewPlan(newPlan: Plan) {
self.planArr.append(newPlan)
self.planTableView.reloadData()
}
deinit {
tableView.dg_removePullToRefresh()
}
func freshData() {
let sessionID = NSUserDefaults.standardUserDefaults().valueForKey("sessionID") as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
ServerModel.getData(sessionID, withType: DataType.Plan) { (plans) -> Void in
//将plan填入planArr
}
if let sessionID = NSUserDefaults.standardUserDefaults().valueForKey("sessionID") as? String {
ServerModel.getData(sessionID, withType: DataType.Plan) { (plans) -> Void in
print("get plans")
print(plans.count)
//将plan填入planArr,待测试
for index in 1..<plans.count {
let destLat = plans[index]["latitude"].double!
let destLon = plans[index]["longitude"].double!
let destName = plans[index]["destination"].string!
let startStr = plans[index]["start"].string!
let endStr = plans[index]["end"].string!
let planId = plans[index]["schedule_id"].int!
let startDate = dateFormatter.dateFromString(startStr)!
let endDate = dateFormatter.dateFromString(endStr)!
let newPlan = Plan(id: planId, lat: destLat, lon: destLon, name: destName, startDate: startDate, endDate: endDate)
self.planArr.append(newPlan)
}
self.planTableView.reloadData()
let dest = self.planArr[0].destinationName
NSUserDefaults.standardUserDefaults().setObject(dest, forKey: "destination")
}
} else {
print("没有获得session")
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if planArr.count == 0 {
freshData()
} else {
let dest = planArr[0].destinationName
NSUserDefaults.standardUserDefaults().setObject(dest, forKey: "destination")
}
if isNeedReload {
self.planTableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return planArr.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let titleLabel = cell.viewWithTag(100) as! UILabel
let startDateLabel = cell.viewWithTag(101) as! UILabel
titleLabel.text = planArr[indexPath.row].destinationName
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy.MM.dd"
let startDateText = formatter.stringFromDate(planArr[indexPath.row].startDate)
startDateLabel.text = startDateText
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "destinationSegue" {
let vc = segue.destinationViewController as! WeatherViewController
if let index = tableView.indexPathForSelectedRow {
vc.destination = self.planArr[index.row]
}
} else if segue.identifier == "newPlan" {
let vc = segue.destinationViewController as! NewDestinationTableViewController
vc.newPlanDelegate = self
}
}
}
| mit | e61124df56e4c37fca3566d2da2fcf5b | 35.930348 | 157 | 0.618214 | 5.430139 | false | false | false | false |
Pluto-Y/SwiftyEcharts | SwiftyEcharts/Tools/Type/Pair.swift | 1 | 1405 | //
// Pair.swift
// SwiftyEcharts
//
// Created by Pluto Y on 15/02/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 用来保存只有两个元素的类型,
///
/// 例如一个点, [x, y]
///
/// 例如一个访问, [min, max]
public final class Pair<T>: ExpressibleByArrayLiteral {
fileprivate var first: T?
fileprivate var second: T?
public init(arrayLiteral elements: T...) {
if elements.count != 2 {
printError("The count of the array should only be two.")
} else {
self.first = elements[0]
self.second = elements[1]
}
}
public init (_ elements: [T]) {
if elements.count != 2 {
printError("The count of the array should only be two.")
} else {
self.first = elements[0]
self.second = elements[1]
}
}
}
extension Pair: Jsonable {
public var jsonString: String {
if let first = self.first as? Jsonable, let second = self.second as? Jsonable {
return [first, second].jsonString
}
return "null"
}
}
/// 用于指定坐标点, eg: [x, y]
public typealias Point = Pair<LengthValue>
/// 用于指定范围, eg: [min, max]
public typealias Range = Pair<LengthValue>
/// 用来指定两端的文本 , eg: ContinuousVisualMap.text
public typealias PiecewiseText = Pair<String>
| mit | 616c16c94255666a389a65d2009df393 | 24.153846 | 87 | 0.583333 | 3.747851 | false | false | false | false |
tjw/swift | test/type/types.swift | 2 | 7515 | // RUN: %target-typecheck-verify-swift
var a : Int
func test() {
var y : a // expected-error {{use of undeclared type 'a'}}
var z : y // expected-error {{use of undeclared type 'y'}}
var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}}
}
var b : (Int) -> Int = { $0 }
var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}}
var d2 : () -> Int = { 4 }
var d3 : () -> Float = { 4 }
var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}}
var e0 : [Int]
e0[] // expected-error {{cannot subscript a value of type '[Int]' with an index of type '()'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>),}}
var f0 : [Float]
var f1 : [(Int,Int)]
var g : Swift // expected-error {{use of undeclared type 'Swift'}} expected-note {{cannot use module 'Swift' as a type}}
var h0 : Int?
_ = h0 == nil // no-warning
var h1 : Int??
_ = h1! == nil // no-warning
var h2 : [Int?]
var h3 : [Int]?
var h3a : [[Int?]]
var h3b : [Int?]?
var h4 : ([Int])?
var h5 : ([([[Int??]])?])?
var h7 : (Int,Int)?
var h8 : ((Int) -> Int)?
var h9 : (Int?) -> Int?
var h10 : Int?.Type?.Type
var i = Int?(42)
func testInvalidUseOfParameterAttr() {
var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' may only be used on parameters}}
func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' may only be used on parameters}}
var bad_is : (Int) -> (__shared Int, Int) // expected-error {{'__shared' may only be used on parameters}}
func bad_is2(_ a: (__shared Int, Int)) {} // expected-error {{'__shared' may only be used on parameters}}
var bad_iow : (Int) -> (__owned Int, Int) // expected-error {{'__owned' may only be used on parameters}}
func bad_iow2(_ a: (__owned Int, Int)) {} // expected-error {{'__owned' may only be used on parameters}}
}
// <rdar://problem/15588967> Array type sugar default construction syntax doesn't work
func test_array_construct<T>(_: T) {
_ = [T]() // 'T' is a local name
_ = [Int]() // 'Int is a global name'
_ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name.
_ = [UnsafeMutablePointer<Int?>]() // Nesting.
_ = [([UnsafeMutablePointer<Int>])]()
_ = [(String, Float)]()
}
extension Optional {
init() {
self = .none
}
}
// <rdar://problem/15295763> default constructing an optional fails to typecheck
func test_optional_construct<T>(_: T) {
_ = T?() // Local name.
_ = Int?() // Global name
_ = (Int?)() // Parenthesized name.
}
// Test disambiguation of generic parameter lists in expression context.
struct Gen<T> {}
var y0 : Gen<Int?>
var y1 : Gen<Int??>
var y2 : Gen<[Int?]>
var y3 : Gen<[Int]?>
var y3a : Gen<[[Int?]]>
var y3b : Gen<[Int?]?>
var y4 : Gen<([Int])?>
var y5 : Gen<([([[Int??]])?])?>
var y7 : Gen<(Int,Int)?>
var y8 : Gen<((Int) -> Int)?>
var y8a : Gen<[([Int]?) -> Int]>
var y9 : Gen<(Int?) -> Int?>
var y10 : Gen<Int?.Type?.Type>
var y11 : Gen<Gen<Int>?>
var y12 : Gen<Gen<Int>?>?
var y13 : Gen<Gen<Int?>?>?
var y14 : Gen<Gen<Int?>>?
var y15 : Gen<Gen<Gen<Int?>>?>
var y16 : Gen<Gen<Gen<Int?>?>>
var y17 : Gen<Gen<Gen<Int?>?>>?
var z0 = Gen<Int?>()
var z1 = Gen<Int??>()
var z2 = Gen<[Int?]>()
var z3 = Gen<[Int]?>()
var z3a = Gen<[[Int?]]>()
var z3b = Gen<[Int?]?>()
var z4 = Gen<([Int])?>()
var z5 = Gen<([([[Int??]])?])?>()
var z7 = Gen<(Int,Int)?>()
var z8 = Gen<((Int) -> Int)?>()
var z8a = Gen<[([Int]?) -> Int]>()
var z9 = Gen<(Int?) -> Int?>()
var z10 = Gen<Int?.Type?.Type>()
var z11 = Gen<Gen<Int>?>()
var z12 = Gen<Gen<Int>?>?()
var z13 = Gen<Gen<Int?>?>?()
var z14 = Gen<Gen<Int?>>?()
var z15 = Gen<Gen<Gen<Int?>>?>()
var z16 = Gen<Gen<Gen<Int?>?>>()
var z17 = Gen<Gen<Gen<Int?>?>>?()
y0 = z0
y1 = z1
y2 = z2
y3 = z3
y3a = z3a
y3b = z3b
y4 = z4
y5 = z5
y7 = z7
y8 = z8
y8a = z8a
y9 = z9
y10 = z10
y11 = z11
y12 = z12
y13 = z13
y14 = z14
y15 = z15
y16 = z16
y17 = z17
// Type repr formation.
// <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr)
let tupleTypeWithNames = (age:Int, count:Int)(4, 5)
let dictWithTuple = [String: (age:Int, count:Int)]()
// <rdar://problem/21684837> typeexpr not being formed for postfix !
let bb2 = [Int!](repeating: nil, count: 2) // expected-warning {{using '!' is not allowed here; treating this as '?' instead}}{{15-16=?}}
// <rdar://problem/21560309> inout allowed on function return type
func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' may only be used on parameters}}
r21560309 { x in x }
// <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties
class r21949448 {
var myArray: inout [Int] = [] // expected-error {{'inout' may only be used on parameters}}
}
// SE-0066 - Standardize function type argument syntax to require parentheses
let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}}
let _ : inout Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{18-18=)}}
func testNoParenFunction(x: Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{32-32=)}}
func testNoParenFunction(x: inout Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{38-38=)}}
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{15-34=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{15-39=UnsafeMutableRawPointer}}
class C {
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{17-36=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{17-41=UnsafeMutableRawPointer}}
func foo3() {
let _ : UnsafePointer<Void> // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{13-32=UnsafeRawPointer}}
let _ : UnsafeMutablePointer<Void> // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{13-39=UnsafeMutableRawPointer}}
}
}
let _ : inout @convention(c) Int -> Int // expected-error {{'inout' may only be used on parameters}}
func foo3(inout a: Int -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{11-16=}} {{20-20=inout }}
// expected-error @-1 {{single argument function types require parentheses}} {{20-20=(}} {{23-23=)}}
func sr5505(arg: Int) -> String {
return "hello"
}
var _: sr5505 = sr5505 // expected-error {{use of undeclared type 'sr5505'}}
typealias A = (inout Int ..., Int ... = [42, 12]) -> Void // expected-error {{'inout' must not be used on variadic parameters}}
// expected-error@-1 {{only a single element can be variadic}} {{35-39=}}
// expected-error@-2 {{default argument not permitted in a tuple type}} {{39-49=}}
| apache-2.0 | 32546eb284c25c45ccaf959d503e5f14 | 37.737113 | 175 | 0.61996 | 3.239224 | false | false | false | false |
lorentey/swift | stdlib/public/Platform/POSIXError.swift | 16 | 18093 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// Enumeration describing POSIX error codes.
@objc
public enum POSIXErrorCode : Int32 {
/// Operation not permitted.
case EPERM = 1
/// No such file or directory.
case ENOENT = 2
/// No such process.
case ESRCH = 3
/// Interrupted system call.
case EINTR = 4
/// Input/output error.
case EIO = 5
/// Device not configured.
case ENXIO = 6
/// Argument list too long.
case E2BIG = 7
/// Exec format error.
case ENOEXEC = 8
/// Bad file descriptor.
case EBADF = 9
/// No child processes.
case ECHILD = 10
/// Resource deadlock avoided.
case EDEADLK = 11
/// 11 was EAGAIN.
/// Cannot allocate memory.
case ENOMEM = 12
/// Permission denied.
case EACCES = 13
/// Bad address.
case EFAULT = 14
/// Block device required.
case ENOTBLK = 15
/// Device / Resource busy.
case EBUSY = 16
/// File exists.
case EEXIST = 17
/// Cross-device link.
case EXDEV = 18
/// Operation not supported by device.
case ENODEV = 19
/// Not a directory.
case ENOTDIR = 20
/// Is a directory.
case EISDIR = 21
/// Invalid argument.
case EINVAL = 22
/// Too many open files in system.
case ENFILE = 23
/// Too many open files.
case EMFILE = 24
/// Inappropriate ioctl for device.
case ENOTTY = 25
/// Text file busy.
case ETXTBSY = 26
/// File too large.
case EFBIG = 27
/// No space left on device.
case ENOSPC = 28
/// Illegal seek.
case ESPIPE = 29
/// Read-only file system.
case EROFS = 30
/// Too many links.
case EMLINK = 31
/// Broken pipe.
case EPIPE = 32
/// math software.
/// Numerical argument out of domain.
case EDOM = 33
/// Result too large.
case ERANGE = 34
/// non-blocking and interrupt i/o.
/// Resource temporarily unavailable.
case EAGAIN = 35
/// Operation would block.
public static var EWOULDBLOCK: POSIXErrorCode { return EAGAIN }
/// Operation now in progress.
case EINPROGRESS = 36
/// Operation already in progress.
case EALREADY = 37
/// ipc/network software -- argument errors.
/// Socket operation on non-socket.
case ENOTSOCK = 38
/// Destination address required.
case EDESTADDRREQ = 39
/// Message too long.
case EMSGSIZE = 40
/// Protocol wrong type for socket.
case EPROTOTYPE = 41
/// Protocol not available.
case ENOPROTOOPT = 42
/// Protocol not supported.
case EPROTONOSUPPORT = 43
/// Socket type not supported.
case ESOCKTNOSUPPORT = 44
/// Operation not supported.
case ENOTSUP = 45
/// Protocol family not supported.
case EPFNOSUPPORT = 46
/// Address family not supported by protocol family.
case EAFNOSUPPORT = 47
/// Address already in use.
case EADDRINUSE = 48
/// Can't assign requested address.
case EADDRNOTAVAIL = 49
/// ipc/network software -- operational errors
/// Network is down.
case ENETDOWN = 50
/// Network is unreachable.
case ENETUNREACH = 51
/// Network dropped connection on reset.
case ENETRESET = 52
/// Software caused connection abort.
case ECONNABORTED = 53
/// Connection reset by peer.
case ECONNRESET = 54
/// No buffer space available.
case ENOBUFS = 55
/// Socket is already connected.
case EISCONN = 56
/// Socket is not connected.
case ENOTCONN = 57
/// Can't send after socket shutdown.
case ESHUTDOWN = 58
/// Too many references: can't splice.
case ETOOMANYREFS = 59
/// Operation timed out.
case ETIMEDOUT = 60
/// Connection refused.
case ECONNREFUSED = 61
/// Too many levels of symbolic links.
case ELOOP = 62
/// File name too long.
case ENAMETOOLONG = 63
/// Host is down.
case EHOSTDOWN = 64
/// No route to host.
case EHOSTUNREACH = 65
/// Directory not empty.
case ENOTEMPTY = 66
/// quotas & mush.
/// Too many processes.
case EPROCLIM = 67
/// Too many users.
case EUSERS = 68
/// Disc quota exceeded.
case EDQUOT = 69
/// Network File System.
/// Stale NFS file handle.
case ESTALE = 70
/// Too many levels of remote in path.
case EREMOTE = 71
/// RPC struct is bad.
case EBADRPC = 72
/// RPC version wrong.
case ERPCMISMATCH = 73
/// RPC prog. not avail.
case EPROGUNAVAIL = 74
/// Program version wrong.
case EPROGMISMATCH = 75
/// Bad procedure for program.
case EPROCUNAVAIL = 76
/// No locks available.
case ENOLCK = 77
/// Function not implemented.
case ENOSYS = 78
/// Inappropriate file type or format.
case EFTYPE = 79
/// Authentication error.
case EAUTH = 80
/// Need authenticator.
case ENEEDAUTH = 81
/// Intelligent device errors.
/// Device power is off.
case EPWROFF = 82
/// Device error, e.g. paper out.
case EDEVERR = 83
/// Value too large to be stored in data type.
case EOVERFLOW = 84
// MARK: Program loading errors.
/// Bad executable.
case EBADEXEC = 85
/// Bad CPU type in executable.
case EBADARCH = 86
/// Shared library version mismatch.
case ESHLIBVERS = 87
/// Malformed Macho file.
case EBADMACHO = 88
/// Operation canceled.
case ECANCELED = 89
/// Identifier removed.
case EIDRM = 90
/// No message of desired type.
case ENOMSG = 91
/// Illegal byte sequence.
case EILSEQ = 92
/// Attribute not found.
case ENOATTR = 93
/// Bad message.
case EBADMSG = 94
/// Reserved.
case EMULTIHOP = 95
/// No message available on STREAM.
case ENODATA = 96
/// Reserved.
case ENOLINK = 97
/// No STREAM resources.
case ENOSR = 98
/// Not a STREAM.
case ENOSTR = 99
/// Protocol error.
case EPROTO = 100
/// STREAM ioctl timeout.
case ETIME = 101
/// No such policy registered.
case ENOPOLICY = 103
/// State not recoverable.
case ENOTRECOVERABLE = 104
/// Previous owner died.
case EOWNERDEAD = 105
/// Interface output queue is full.
case EQFULL = 106
/// Must be equal largest errno.
public static var ELAST: POSIXErrorCode { return EQFULL }
// FIXME: EOPNOTSUPP has different values depending on __DARWIN_UNIX03 and
// KERNEL.
}
#elseif os(Linux) || os(Android)
/// Enumeration describing POSIX error codes.
public enum POSIXErrorCode : Int32 {
/// Operation not permitted.
case EPERM = 1
/// No such file or directory.
case ENOENT = 2
/// No such process.
case ESRCH = 3
/// Interrupted system call.
case EINTR = 4
/// Input/output error.
case EIO = 5
/// Device not configured.
case ENXIO = 6
/// Argument list too long.
case E2BIG = 7
/// Exec format error.
case ENOEXEC = 8
/// Bad file descriptor.
case EBADF = 9
/// No child processes.
case ECHILD = 10
/// Try again.
case EAGAIN = 11
/// Cannot allocate memory.
case ENOMEM = 12
/// Permission denied.
case EACCES = 13
/// Bad address.
case EFAULT = 14
/// Block device required.
case ENOTBLK = 15
/// Device / Resource busy.
case EBUSY = 16
/// File exists.
case EEXIST = 17
/// Cross-device link.
case EXDEV = 18
/// Operation not supported by device.
case ENODEV = 19
/// Not a directory.
case ENOTDIR = 20
/// Is a directory.
case EISDIR = 21
/// Invalid argument.
case EINVAL = 22
/// Too many open files in system.
case ENFILE = 23
/// Too many open files.
case EMFILE = 24
/// Inappropriate ioctl for device.
case ENOTTY = 25
/// Text file busy.
case ETXTBSY = 26
/// File too large.
case EFBIG = 27
/// No space left on device.
case ENOSPC = 28
/// Illegal seek.
case ESPIPE = 29
/// Read-only file system.
case EROFS = 30
/// Too many links.
case EMLINK = 31
/// Broken pipe.
case EPIPE = 32
/// Numerical argument out of domain.
case EDOM = 33
/// Result too large.
case ERANGE = 34
/// Resource deadlock would occur.
case EDEADLK = 35
/// File name too long.
case ENAMETOOLONG = 36
/// No record locks available
case ENOLCK = 37
/// Function not implemented.
case ENOSYS = 38
/// Directory not empty.
case ENOTEMPTY = 39
/// Too many symbolic links encountered
case ELOOP = 40
/// Operation would block.
public static var EWOULDBLOCK: POSIXErrorCode { return .EAGAIN }
/// No message of desired type.
case ENOMSG = 42
/// Identifier removed.
case EIDRM = 43
/// Channel number out of range.
case ECHRNG = 44
/// Level 2 not synchronized.
case EL2NSYNC = 45
/// Level 3 halted
case EL3HLT = 46
/// Level 3 reset.
case EL3RST = 47
/// Link number out of range.
case ELNRNG = 48
/// Protocol driver not attached.
case EUNATCH = 49
/// No CSI structure available.
case ENOCSI = 50
/// Level 2 halted.
case EL2HLT = 51
/// Invalid exchange
case EBADE = 52
/// Invalid request descriptor
case EBADR = 53
/// Exchange full
case EXFULL = 54
/// No anode
case ENOANO = 55
/// Invalid request code
case EBADRQC = 56
/// Invalid slot
case EBADSLT = 57
public static var EDEADLOCK: POSIXErrorCode { return .EDEADLK }
/// Bad font file format
case EBFONT = 59
/// Device not a stream
case ENOSTR = 60
/// No data available
case ENODATA = 61
/// Timer expired
case ETIME = 62
/// Out of streams resources
case ENOSR = 63
/// Machine is not on the network
case ENONET = 64
/// Package not installed
case ENOPKG = 65
/// Object is remote
case EREMOTE = 66
/// Link has been severed
case ENOLINK = 67
/// Advertise error
case EADV = 68
/// Srmount error
case ESRMNT = 69
/// Communication error on send
case ECOMM = 70
/// Protocol error
case EPROTO = 71
/// Multihop attempted
case EMULTIHOP = 72
/// RFS specific error
case EDOTDOT = 73
/// Not a data message
case EBADMSG = 74
/// Value too large for defined data type
case EOVERFLOW = 75
/// Name not unique on network
case ENOTUNIQ = 76
/// File descriptor in bad state
case EBADFD = 77
/// Remote address changed
case EREMCHG = 78
/// Can not access a needed shared library
case ELIBACC = 79
/// Accessing a corrupted shared library
case ELIBBAD = 80
/// .lib section in a.out corrupted
case ELIBSCN = 81
/// Attempting to link in too many shared libraries
case ELIBMAX = 82
/// Cannot exec a shared library directly
case ELIBEXEC = 83
/// Illegal byte sequence
case EILSEQ = 84
/// Interrupted system call should be restarted
case ERESTART = 85
/// Streams pipe error
case ESTRPIPE = 86
/// Too many users
case EUSERS = 87
/// Socket operation on non-socket
case ENOTSOCK = 88
/// Destination address required
case EDESTADDRREQ = 89
/// Message too long
case EMSGSIZE = 90
/// Protocol wrong type for socket
case EPROTOTYPE = 91
/// Protocol not available
case ENOPROTOOPT = 92
/// Protocol not supported
case EPROTONOSUPPORT = 93
/// Socket type not supported
case ESOCKTNOSUPPORT = 94
/// Operation not supported on transport endpoint
case EOPNOTSUPP = 95
/// Protocol family not supported
case EPFNOSUPPORT = 96
/// Address family not supported by protocol
case EAFNOSUPPORT = 97
/// Address already in use
case EADDRINUSE = 98
/// Cannot assign requested address
case EADDRNOTAVAIL = 99
/// Network is down
case ENETDOWN = 100
/// Network is unreachable
case ENETUNREACH = 101
/// Network dropped connection because of reset
case ENETRESET = 102
/// Software caused connection abort
case ECONNABORTED = 103
/// Connection reset by peer
case ECONNRESET = 104
/// No buffer space available
case ENOBUFS = 105
/// Transport endpoint is already connected
case EISCONN = 106
/// Transport endpoint is not connected
case ENOTCONN = 107
/// Cannot send after transport endpoint shutdown
case ESHUTDOWN = 108
/// Too many references: cannot splice
case ETOOMANYREFS = 109
/// Connection timed out
case ETIMEDOUT = 110
/// Connection refused
case ECONNREFUSED = 111
/// Host is down
case EHOSTDOWN = 112
/// No route to host
case EHOSTUNREACH = 113
/// Operation already in progress
case EALREADY = 114
/// Operation now in progress
case EINPROGRESS = 115
/// Stale NFS file handle
case ESTALE = 116
/// Structure needs cleaning
case EUCLEAN = 117
/// Not a XENIX named type file
case ENOTNAM = 118
/// No XENIX semaphores available
case ENAVAIL = 119
/// Is a named type file
case EISNAM = 120
/// Remote I/O error
case EREMOTEIO = 121
/// Quota exceeded
case EDQUOT = 122
/// No medium found
case ENOMEDIUM = 123
/// Wrong medium type
case EMEDIUMTYPE = 124
/// Operation Canceled
case ECANCELED = 125
/// Required key not available
case ENOKEY = 126
/// Key has expired
case EKEYEXPIRED = 127
/// Key has been revoked
case EKEYREVOKED = 128
/// Key was rejected by service
case EKEYREJECTED = 129
/// Owner died
case EOWNERDEAD = 130
/// State not recoverable
case ENOTRECOVERABLE = 131
/// Operation not possible due to RF-kill
case ERFKILL = 132
/// Memory page has hardware error
case EHWPOISON = 133
}
#elseif os(Windows)
/// Enumeration describing POSIX error codes.
public enum POSIXErrorCode : Int32 {
/// Operation not permitted
case EPERM = 1
/// No such file or directory
case ENOENT = 2
/// No such process
case ESRCH = 3
/// Interrupted function
case EINTR = 4
/// I/O error
case EIO = 5
/// No such device or address
case ENXIO = 6
/// Argument list too long
case E2BIG = 7
/// Exec format error
case ENOEXEC = 8
/// Bad file number
case EBADF = 9
/// No spawned processes
case ECHILD = 10
/// No more processes or not enough memory or maximum nesting level reached
case EAGAIN = 11
/// Not enough memory
case ENOMEM = 12
/// Permission denied
case EACCES = 13
/// Bad address
case EFAULT = 14
/// Device or resource busy
case EBUSY = 16
/// File exists
case EEXIST = 17
/// Cross-device link
case EXDEV = 18
/// No such device
case ENODEV = 19
/// Not a directory
case ENOTDIR = 20
/// Is a directory
case EISDIR = 21
/// Invalid argument
case EINVAL = 22
/// Too many files open in system
case ENFILE = 23
/// Too many open files
case EMFILE = 24
/// Inappropriate I/O control operation
case ENOTTY = 25
/// File too large
case EFBIG = 27
/// No space left on device
case ENOSPC = 28
/// Invalid seek
case ESPIPE = 29
/// Read-only file system
case EROFS = 30
/// Too many links
case EMLINK = 31
/// Broken pipe
case EPIPE = 32
/// Math argument
case EDOM = 33
/// Result too large
case ERANGE = 34
/// Resource deadlock would occur
case EDEADLK = 36
/// Same as EDEADLK for compatibility with older Microsoft C versions
public static var EDEADLOCK: POSIXErrorCode { return .EDEADLK }
/// Filename too long
case ENAMETOOLONG = 38
/// No locks available
case ENOLCK = 39
/// Function not supported
case ENOSYS = 40
/// Directory not empty
case ENOTEMPTY = 41
/// Illegal byte sequence
case EILSEQ = 42
/// String was truncated
case STRUNCATE = 80
}
#endif
| apache-2.0 | 0b4a77781cf0d5cead7a40a492cb1d4f | 25.413139 | 80 | 0.560327 | 4.663144 | false | false | false | false |
Gruppio/Run-Forrest-Run | Examples/ListSwiftFiles/main.swift | 1 | 426 | //
// main.swift
// ListSwiftFiles
//
// Created by Michele Gruppioni on 16/01/16.
// Copyright © 2016 Michele Gruppioni. All rights reserved.
//
import Foundation
import Forrest
let forrest = Forrest()
let pwd = forrest.run("pwd").stdout
let swiftFiles = forrest.run("ls | grep swift").stdout
if let pwd = pwd, swiftFiles = swiftFiles {
print("Swift Files in \(pwd) \(swiftFiles)")
}
print("Done")
| mit | dbfb82d9dc5b866532c45a0e7fb7ef8e | 19.238095 | 60 | 0.665882 | 3.373016 | false | false | false | false |
jverdi/Gramophone | Source/Model/User.swift | 1 | 2708 | //
// User.swift
// Gramophone
//
// Copyright (c) 2017 Jared Verdi. 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
import protocol Decodable.Decodable
import Decodable
public struct User {
public let ID: String
public let username: String
public let fullName: String
public let profilePictureURL: URL
public let bio: String?
public let websiteURL: URL?
public let mediaCount: Int?
public let followingCount: Int?
public let followersCount: Int?
public init(ID: String, username: String, fullName: String, profilePictureURL: URL, bio: String?,
websiteURL: URL?, mediaCount: Int?, followingCount: Int?, followersCount: Int?) {
self.ID = ID
self.username = username
self.fullName = fullName
self.profilePictureURL = profilePictureURL
self.bio = bio
self.websiteURL = websiteURL
self.mediaCount = mediaCount
self.followingCount = followingCount
self.followersCount = followersCount
}
}
// MARK: Decodable
extension User: Decodable {
public static func decode(_ json: Any) throws -> User {
return try User(
ID: json => "id",
username: json => "username",
fullName: json => "full_name",
profilePictureURL: json => "profile_picture",
bio: try? json => "bio",
websiteURL: try? json => "website",
mediaCount: try? json => "counts" => "media",
followingCount: try? json => "counts" => "follows",
followersCount: try? json => "counts" => "followed_by"
)
}
}
| mit | 74a20566bc74cf5fed4be1bf2cfd154e | 37.140845 | 101 | 0.672083 | 4.528428 | false | false | false | false |
SandcastleApps/partyup | Pods/Instructions/Sources/Controllers/Public/CoachMark.swift | 1 | 4988 | // CoachMark.swift
//
// Copyright (c) 2015, 2016 Frédéric Maquin <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// This structure handle the parametrization of a given coach mark.
/// It doesn't provide any clue about the way it will look, however.
public struct CoachMark {
//mark: Public properties
/// Change this value to change the duration of the fade.
public var animationDuration = Constants.coachMarkFadeAnimationDuration
/// The path to cut in the overlay, so the point of interest will be visible.
public var cutoutPath: UIBezierPath?
/// The vertical offset for the arrow (in rare cases, the arrow might need to overlap with
/// the coach mark body).
public var gapBetweenBodyAndArrow: CGFloat = 2.0
/// The orientation of the arrow, around the body of the coach mark (top or bottom).
public var arrowOrientation: CoachMarkArrowOrientation?
/// The "point of interest" toward which the arrow will point.
///
/// At the moment, it's only used to shift the arrow horizontally and make it sits above/below
/// the point of interest.
public var pointOfInterest: CGPoint?
/// Offset between the coach mark and the cutout path.
public var gapBetweenCoachMarkAndCutoutPath: CGFloat = 2.0
/// Maximum width for a coach mark.
public var maxWidth: CGFloat = 350
/// Trailing and leading margin of the coach mark.
public var horizontalMargin: CGFloat = 20
/// Set this property to `true` to disable a tap on the overlay.
/// (only if the tap capture was enabled)
///
/// If you need to disable the tap for all the coachmarks, prefer setting
/// `CoachMarkController.allowOverlayTap`.
public var disableOverlayTap: Bool = false
/// Set this property to `true` to allow touch forwarding inside the cutoutPath.
public var allowTouchInsideCutoutPath: Bool = false
//mark: Initialization
/// Allocate and initialize a Coach mark with default values.
public init () {
}
//mark: Internal Methods
/// This method perform both `computeOrientationInFrame` and `computePointOfInterestInFrame`.
///
/// - Parameter frame: the frame in which compute the orientation
/// (likely to match the overlay's frame)
internal mutating func computeMetadataForFrame(frame: CGRect) {
self.computeOrientationInFrame(frame)
self.computePointOfInterestInFrame()
}
/// Compute the orientation of the arrow, given the frame in which the coach mark
/// will be displayed.
///
/// - Parameter frame: the frame in which compute the orientation
/// (likely to match the overlay's frame)
internal mutating func computeOrientationInFrame(frame: CGRect) {
// No cutout path means no arrow. That way, no orientation
// computation is needed.
guard let cutoutPath = self.cutoutPath else {
self.arrowOrientation = nil
return
}
if self.arrowOrientation != nil {
return
}
if cutoutPath.bounds.origin.y > frame.size.height / 2 {
self.arrowOrientation = .Bottom
} else {
self.arrowOrientation = .Top
}
}
/// Compute the orientation of the arrow, given the frame in which the coach mark
/// will be displayed.
internal mutating func computePointOfInterestInFrame() {
/// If the value is already set, don't do anything.
if self.pointOfInterest != nil { return }
/// No cutout path means no point of interest.
/// That way, no orientation computation is needed.
guard let cutoutPath = self.cutoutPath else { return }
let x = cutoutPath.bounds.origin.x + cutoutPath.bounds.width / 2
let y = cutoutPath.bounds.origin.y + cutoutPath.bounds.height / 2
self.pointOfInterest = CGPoint(x: x, y: y)
}
}
| mit | bee2419d5a202172a550d2a3a31c4d88 | 39.868852 | 98 | 0.689731 | 4.812741 | false | false | false | false |
noblakit01/PhotoCollectionView | PhotoCollectionViewDemo/ViewController.swift | 1 | 3508 | //
// ViewController.swift
// PhotoCollectionViewDemo
//
// Created by Minh Luan Tran on 7/6/17.
// Copyright © 2017 Minh Luan Tran. All rights reserved.
//
import UIKit
import PhotoCollectionView
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var images : [[UIImage]] = [
[#imageLiteral(resourceName: "image1")],
[#imageLiteral(resourceName: "image1"), #imageLiteral(resourceName: "image2")],
[#imageLiteral(resourceName: "image1"), #imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image3")],
[#imageLiteral(resourceName: "image1"), #imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image3"), #imageLiteral(resourceName: "image4")],
[#imageLiteral(resourceName: "image1"), #imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image3"), #imageLiteral(resourceName: "image4"), #imageLiteral(resourceName: "image5")],
[#imageLiteral(resourceName: "image1"), #imageLiteral(resourceName: "image2"), #imageLiteral(resourceName: "image3"), #imageLiteral(resourceName: "image4"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5"), #imageLiteral(resourceName: "image5")],
[#imageLiteral(resourceName: "dog-1")],
[#imageLiteral(resourceName: "dog-1"), #imageLiteral(resourceName: "dog-2")],
[#imageLiteral(resourceName: "dog-1"), #imageLiteral(resourceName: "dog-2"), #imageLiteral(resourceName: "dog-3")],
[#imageLiteral(resourceName: "dog-1"), #imageLiteral(resourceName: "dog-2"), #imageLiteral(resourceName: "dog-3"), #imageLiteral(resourceName: "dog-4")],
[#imageLiteral(resourceName: "dog-1"), #imageLiteral(resourceName: "dog-2"), #imageLiteral(resourceName: "dog-3"), #imageLiteral(resourceName: "dog-4"), #imageLiteral(resourceName: "dog-5")],
[#imageLiteral(resourceName: "dog-1"), #imageLiteral(resourceName: "dog-2"), #imageLiteral(resourceName: "dog-3"), #imageLiteral(resourceName: "dog-4"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5"), #imageLiteral(resourceName: "dog-5")],
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = nil
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? TableViewCell else {
return UITableViewCell()
}
cell.images = images[indexPath.row]
cell.indexLabel.text = "Cell \(indexPath.row)"
return cell
}
}
| mit | decd1dce010599b76b6026b8652d8dff | 60.526316 | 555 | 0.697462 | 4.439241 | false | false | false | false |
fabiomassimo/eidolon | Kiosk/App/Models/SaleArtwork.swift | 1 | 7823 | import UIKit
import SwiftyJSON
import Swift_RAC_Macros
import ReactiveCocoa
public enum ReserveStatus: String {
case ReserveNotMet = "reserve_not_met"
case NoReserve = "no_reserve"
case ReserveMet = "reserve_met"
public var reserveNotMet: Bool {
return self == .ReserveNotMet
}
public static func initOrDefault (rawValue: String?) -> ReserveStatus {
return ReserveStatus(rawValue: rawValue ?? "") ?? .NoReserve
}
}
public struct SaleNumberFormatter {
static let dollarFormatter = createDollarFormatter()
}
private let kNoBidsString = "0 bids placed"
public class SaleArtwork: JSONAble {
public let id: String
public let artwork: Artwork
public var auctionID: String?
public var saleHighestBid: Bid?
public dynamic var bidCount: NSNumber?
public var userBidderPosition: BidderPosition?
public var positions: [String]?
public dynamic var openingBidCents: NSNumber?
public dynamic var minimumNextBidCents: NSNumber?
public dynamic var highestBidCents: NSNumber?
public var lowEstimateCents: Int?
public var highEstimateCents: Int?
public dynamic var reserveStatus: String?
public dynamic var lotNumber: NSNumber?
public init(id: String, artwork: Artwork) {
self.id = id
self.artwork = artwork
}
override public class func fromJSON(json: [String: AnyObject]) -> JSONAble {
let json = JSON(json)
let id = json["id"].stringValue
let artworkDict = json["artwork"].object as! [String: AnyObject]
let artwork = Artwork.fromJSON(artworkDict) as! Artwork
let saleArtwork = SaleArtwork(id: id, artwork: artwork) as SaleArtwork
if let highestBidDict = json["highest_bid"].object as? [String: AnyObject] {
saleArtwork.saleHighestBid = Bid.fromJSON(highestBidDict) as? Bid
}
saleArtwork.auctionID = json["sale_id"].string
saleArtwork.openingBidCents = json["opening_bid_cents"].int
saleArtwork.minimumNextBidCents = json["minimum_next_bid_cents"].int
saleArtwork.highestBidCents = json["highest_bid_amount_cents"].int
saleArtwork.lowEstimateCents = json["low_estimate_cents"].int
saleArtwork.highEstimateCents = json["high_estimate_cents"].int
saleArtwork.bidCount = json["bidder_positions_count"].int
saleArtwork.reserveStatus = json["reserve_status"].string
saleArtwork.lotNumber = json["lot_number"].int
return saleArtwork
}
public func updateWithValues(newSaleArtwork: SaleArtwork) {
saleHighestBid = newSaleArtwork.saleHighestBid
auctionID = newSaleArtwork.auctionID
openingBidCents = newSaleArtwork.openingBidCents
minimumNextBidCents = newSaleArtwork.minimumNextBidCents
highestBidCents = newSaleArtwork.highestBidCents
lowEstimateCents = newSaleArtwork.lowEstimateCents
highEstimateCents = newSaleArtwork.highEstimateCents
bidCount = newSaleArtwork.bidCount
reserveStatus = newSaleArtwork.reserveStatus
lotNumber = newSaleArtwork.lotNumber ?? lotNumber
artwork.updateWithValues(newSaleArtwork.artwork)
}
public var estimateString: String {
switch (lowEstimateCents, highEstimateCents) {
case let (.Some(lowCents), .Some(highCents)):
let lowDollars = NSNumberFormatter.currencyStringForCents(lowCents)
let highDollars = NSNumberFormatter.currencyStringForCents(highCents)
return "Estimate: \(lowDollars)–\(highDollars)"
case let (.Some(lowCents), nil):
let lowDollars = NSNumberFormatter.currencyStringForCents(lowCents)
return "Estimate: \(lowDollars)"
case let (nil, .Some(highCents)):
let highDollars = NSNumberFormatter.currencyStringForCents(highCents)
return "Estimate: \(highDollars)"
default:
return "No Estimate"
}
}
public var numberOfBidsSignal: RACSignal {
return RACObserve(self, "bidCount").map { (optionalBidCount) -> AnyObject! in
// Technically, the bidCount is Int?, but the `as?` cast could fail (it never will, but the compiler doesn't know that)
// So we need to unwrap it as an optional optional. Yo dawg.
let bidCount = optionalBidCount as! Int?
if let bidCount = bidCount {
let suffix = bidCount == 1 ? "" : "s"
return "\(bidCount) bid\(suffix) placed"
} else {
return kNoBidsString
}
}
}
// The language used here is very specific – see https://github.com/artsy/eidolon/pull/325#issuecomment-64121996 for details
public var numberOfBidsWithReserveSignal: RACSignal {
return RACSignal.combineLatest([numberOfBidsSignal, RACObserve(self, "reserveStatus"), RACObserve(self, "highestBidCents")]).map { (object) -> AnyObject! in
let tuple = object as! RACTuple // Ignoring highestBidCents; only there to trigger on bid update.
let numberOfBidsString = tuple.first as! String
let reserveStatus = ReserveStatus.initOrDefault(tuple.second as? String)
// if there is no reserve, just return the number of bids string.
if reserveStatus == .NoReserve {
return numberOfBidsString
} else {
if numberOfBidsString == kNoBidsString {
// If there are no bids, then return only this string.
return "This lot has a reserve"
} else if reserveStatus == .ReserveNotMet {
return "(\(numberOfBidsString), Reserve not met)"
} else { // implicitly, reserveStatus is .ReserveMet
return "(\(numberOfBidsString), Reserve met)"
}
}
}
}
public var lotNumberSignal: RACSignal {
return RACObserve(self, "lotNumber").map({ (lotNumber) -> AnyObject! in
if let lotNumber = lotNumber as? Int {
return "Lot \(lotNumber)"
} else {
return nil
}
}).mapNilToEmptyString()
}
public var forSaleSignal: RACSignal {
return RACObserve(self, "artwork").map { (artwork) -> AnyObject! in
let artwork = artwork as! Artwork
return Artwork.SoldStatus.fromString(artwork.soldStatus) == .NotSold
}
}
public func currentBidSignal(prefix: String = "", missingPrefix: String = "") -> RACSignal {
return RACObserve(self, "highestBidCents").map({ [weak self] (highestBidCents) -> AnyObject! in
if let currentBidCents = highestBidCents as? Int {
return "\(prefix)\(NSNumberFormatter.currencyStringForCents(currentBidCents))"
} else {
return "\(missingPrefix)\(NSNumberFormatter.currencyStringForCents(self?.openingBidCents ?? 0))"
}
})
}
override public class func keyPathsForValuesAffectingValueForKey(key: String) -> Set<NSObject> {
if key == "estimateString" {
return ["lowEstimateCents", "highEstimateCents"] as Set
} else if key == "lotNumberSignal" {
return ["lotNumber"] as Set
} else {
return super.keyPathsForValuesAffectingValueForKey(key)
}
}
}
func createDollarFormatter() -> NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
// This is always dollars, so let's make sure that's how it shows up
// regardless of locale.
formatter.currencyGroupingSeparator = ","
formatter.currencySymbol = "$"
formatter.maximumFractionDigits = 0
return formatter
} | mit | 721f8fff460bb9609fed0bf693a052b1 | 37.905473 | 164 | 0.649827 | 5.157652 | false | false | false | false |
soapyigu/LeetCode_Swift | DFS/FactorCombinations.swift | 1 | 844 | /**
* Question Link: https://leetcode.com/problems/factor-combinations/
* Primary idea: Classic Depth-first Search
*
* Time Complexity: O(n^n), Space Complexity: O(2^n - 1)
*
*/
class FactorCombinations {
func getFactors(_ n: Int) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
dfs(&res, &path, n, 2)
return res
}
private func dfs(_ res: inout [[Int]], _ path: inout [Int], _ n: Int, _ start: Int) {
if n == 1 {
if path.count > 1 {
res.append(Array(path))
}
return
}
if start > n {
return
}
for i in start...n where n % i == 0 {
path.append(i)
dfs(&res, &path, n / i, i)
path.removeLast()
}
}
} | mit | 1d0d8479a2416fa043ed2e4d34b2ca79 | 21.837838 | 89 | 0.437204 | 3.819005 | false | false | false | false |
WangYang-iOS/YiDeXuePin_Swift | DiYa/DiYa/Class/Class/View/YYEditShopCartCell.swift | 1 | 2223 | //
// YYEditShopCartCell.swift
// DiYa
//
// Created by wangyang on 2017/12/18.
// Copyright © 2017年 wangyang. All rights reserved.
//
import UIKit
@objc protocol YYEditShopCartCellDelegate {
@objc optional
func didSelectedGoods(goodsModel : GoodsModel)
func didSelectedCategory(goodsModel : GoodsModel)
}
class YYEditShopCartCell: UITableViewCell {
@IBOutlet weak var selectedButton: UIButton!
@IBOutlet weak var goodsImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var numberLabel: UILabel!
weak var delegate : YYEditShopCartCellDelegate?
var number : Int = 0 {
didSet {
numberLabel.text = "\(number)"
}
}
var goodsModel : GoodsModel? {
didSet {
guard let goodsModel = goodsModel else {
return
}
selectedButton.isSelected = goodsModel.isSelected
goodsImageView.sd_setImage(with: URL(string: goodsModel.picture), placeholderImage: UIImage(named: "ic_home_logo"))
titleLabel.text = goodsModel.title
categoryLabel.text = goodsModel.skuValue
number = Int(goodsModel.number) ?? 0
}
}
@IBAction func clickSelectedButton(_ sender: UIButton) {
guard let goodsModel = goodsModel else {
return
}
delegate?.didSelectedGoods?(goodsModel: goodsModel)
}
@IBAction func clickCategoryButton(_ sender: UIButton) {
//选择分类
guard let goodsModel = goodsModel else {
return
}
delegate?.didSelectedCategory(goodsModel: goodsModel)
}
@IBAction func clickNumberButton(_ sender: UIButton) {
if sender.tag == 100 {
//-
if number == 0 {
return
}
number = number - 1;
}else {
//+
number = number + 1;
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| mit | 5b58a28bc22b303a7ff08ed8f5f572be | 26.308642 | 127 | 0.595389 | 4.840263 | false | false | false | false |
ps12138/dribbbleAPI | NetworkManager/NetworkManager+publicFormRequest.swift | 1 | 9367 | //
// NetworkManager+FormRequest.swift
// DribbbleModuleFrameworkShadow
//
// Created by PSL on 12/8/16.
// Copyright © 2016 PSL. All rights reserved.
//
import Foundation
extension NetworkManager {
// MARK: - public method
public func formRequest(_ from: DribbleAuthApi) -> URLRequest?{
var urlString: String? {
return formUrlString(from)
}
var httpMethod: String? {
return formHttpMethod(from)
}
var httpBody: Data? {
switch from {
case .createComment( _, let content):
return formBody(bodyString: content)
default:
return nil
}
}
var cachePolicy: URLRequest.CachePolicy {
return formCachePolicy(from)
}
guard
httpMethod != nil,
let absoluteString = urlString,
let url = URL(string: absoluteString)
else {
print("NetM.formReq: fail to form request")
return nil
}
// form request
var request = URLRequest(url: url)
request.httpMethod = httpMethod
request.cachePolicy = cachePolicy
// add body
request.httpBody = httpBody
print("NetM.formReq: form req \(request.url!)")
return request
}
// MARK: - Api constant
fileprivate struct DefaultCons {
static let perPageInt = 12
static let sortString = ""
}
fileprivate struct Api {
static let base = "\(Constants.apiBase)/v1/"
static let shots = "shots/"
static let like = "like"
static let listLikes = "likes"
static let listShots = "shots"
static let listFollowers = "followers"
static let listFollowing = "following"
static let activeUser = "user/"
static let users = "users/"
static let comments = "comments"
static let page = "?page="
static let perPage = "&per_page="
static let paraBegin = "?"
static let paraBetween = "&"
}
// MARK: - Private method
// custom CachePolicy
private func formCachePolicy(_ from: DribbleAuthApi) -> URLRequest.CachePolicy {
switch from {
case .activeUser:
return URLRequest.CachePolicy.reloadIgnoringCacheData
default:
return URLRequest.CachePolicy.useProtocolCachePolicy
}
}
private func formUrlString(_ from: DribbleAuthApi) -> String? {
switch from {
case .likeShot(let shotID):
return formString(like: shotID)
case .checkLikeShot(let shotID):
return formString(like: shotID)
case .unlikeShot(let shotID):
return formString(like: shotID)
case .activeUser:
return "\(Api.base)\(Api.activeUser)"
case .activeUserLikesByPage(let page):
return "\(Api.base)\(Api.activeUser)\(Api.listLikes)\(Api.page)\(page)"
case .activeUserShotsByPage(let page):
return "\(Api.base)\(Api.activeUser)\(Api.listShots)\(Api.page)\(page)"
case .activeUserFollowersByPage(let page):
return "\(Api.base)\(Api.activeUser)\(Api.listFollowers)\(Api.page)\(page)"
case .activeUserFollowingByPage(let page):
return "\(Api.base)\(Api.activeUser)\(Api.listFollowing)\(Api.page)\(page)"
case .listUserShotsByPage(let userID, let page):
return formString(userShots: userID, page: page)
case .listUserLikesByPage(let userID, let page):
return formString(userLikes: userID, page: page)
case .listUserFollowersByPage(let userID, let page):
return formString(userFollowers: userID, page: page)
case .listUserFollowingByPage(let userID, let page):
return formString(userFollowing: userID, page: page)
case .listShotsByPage(let page):
return formString(listShotsByPage: page, perPage: DefaultCons.perPageInt, sort: DefaultCons.sortString)
case .listShotsByPagePerpage(let page, let perPage):
return formString(listShotsByPage: page, perPage: perPage, sort: DefaultCons.sortString)
case .listShotsByPageCustomSearch(let page, let sort):
return formString(listShotsByPage: page, perPage: DefaultCons.perPageInt, sort: sort)
case .listShotsByPagePerpageCustomSearch(let page, let perPage, let sort):
return formString(listShotsByPage: page, perPage: perPage, sort: sort)
case .listShotComments(let shotID):
return formString(listComments: shotID)
case .listLikesForComment(let shotID, let commentID):
return formString(listLikesForComment: shotID, commentID)
case .listShotCommentsByPage(let shotID, let page):
return formString(listComments: shotID, page: page)
case .createComment(let shotID, _):
return "\(Api.base)\(Api.shots)\(shotID)/\(Api.comments)"
case .deleteComment(let shotID):
return "\(Api.base)\(Api.shots)\(shotID)/\(Api.comments)"
case .likeComment(let shotID, let commentID):
return formString(likeComment: shotID, commentID)
case .unlikeComment(let shotID, let commentID):
return formString(likeComment: shotID, commentID)
default:
return nil
}
}
private func formHttpMethod(_ from: DribbleAuthApi) -> String? {
switch from {
case .likeShot:
return "POST"
case .checkLikeShot:
return "GET"
case .unlikeShot:
return "DELETE"
case .activeUser:
return "GET"
case .activeUserLikesByPage,
.activeUserShotsByPage,
.activeUserFollowersByPage,
.activeUserFollowingByPage:
return "GET"
case .listShotsByPage,
.listShotsByPagePerpage,
.listShotsByPageCustomSearch,
.listShotsByPagePerpageCustomSearch:
return "GET"
case .listUserShotsByPage,
.listUserLikesByPage,
.listUserFollowersByPage,
.listUserFollowingByPage:
return "GET"
case .listShotComments,
.listLikesForComment,
.listShotCommentsByPage:
return "GET"
case .createComment:
return "POST"
case .deleteComment:
return "DELETE"
case .likeComment:
return "POST"
case .unlikeComment:
return "DELETE"
default:
return nil
}
}
// form String for url
private func formString(like shotID: Int) -> String {
let urlString = "\(Api.base)\(Api.shots)\(shotID)/\(Api.like)"
return urlString
}
private func formString(userLikes userID: Int, page: Int) -> String {
let urlString = "\(Api.base)\(Api.users)\(userID)/\(Api.listLikes)\(Api.page)\(page)"
return urlString
}
private func formString(userShots userID: Int, page: Int) -> String {
let urlString = "\(Api.base)\(Api.users)\(userID)/\(Api.listShots)\(Api.page)\(page)"
return urlString
}
private func formString(userFollowers userID: Int, page: Int) -> String {
let urlString = "\(Api.base)\(Api.users)\(userID)/\(Api.listFollowers)\(Api.page)\(page)"
return urlString
}
private func formString(userFollowing userID: Int, page: Int) -> String {
let urlString = "\(Api.base)\(Api.users)\(userID)/\(Api.listFollowing)\(Api.page)\(page)"
return urlString
}
private func formString(listShotsByPage page: Int, perPage: Int, sort: String) -> String {
let urlString = "\(Api.base)\(Api.listShots)\(Api.page)\(page)\(Api.perPage)\(perPage)\(sort)"
return urlString
}
private func formString(listComments shotID: Int) -> String {
let urlString = "\(Api.base)\(Api.shots)\(shotID)/\(Api.comments)"
return urlString
}
private func formString(listComments shotID: Int, page: Int) -> String {
let urlString = "\(Api.base)\(Api.shots)\(shotID)/\(Api.comments)\(Api.page)\(page)"
return urlString
}
private func formString(listLikesForComment shotID: Int, _ commentID: Int) -> String {
let urlString = "\(Api.base)\(Api.shots)\(shotID)/\(Api.comments)/\(commentID)/\(Api.listLikes)"
return urlString
}
private func formString(likeComment shotID: Int, _ commentID: Int) -> String {
let urlString = "\(Api.base)\(Api.shots)\(shotID)/\(Api.comments)/\(commentID)/\(Api.listLikes)"
return urlString
}
private func formBody(bodyString: String) -> Data? {
let dict = ["body": bodyString]
let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
return data
}
}
| mit | 9a272e5358d0942c4f99d280bb4274eb | 32.812274 | 115 | 0.576126 | 5.046336 | false | false | false | false |
RameshRM/just-now | JustNow/JustNow/ListViewController.swift | 1 | 4409 | //
// ListViewController.swift
// JustNow
//
// Created by Mahadevan, Ramesh on 8/3/15.
// Copyright (c) 2015 GoliaMania. All rights reserved.
//
import Foundation
//
// ListViewController.swift
// TASKY
//
// Created by Mahadevan, Ramesh on 1/2/15.
// Copyright (c) 2015 GoliaMania. All rights reserved.
//
import UIKit
class ListViewController: MainViewController,UITableViewDelegate, UITableViewDataSource, ListViewProtocol {
var isSearchOn:Bool = false;
var tableView: UITableView!
var itemCellIdentifier : NSString!;
var detailIdentifier: String!;
var detailView: UIViewController!;
var dataEntity: AnyObject!;
var dataContext: [AnyObject] = [] {
willSet(newData){
}
didSet{
}
};
var isDirty = false;
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataContext.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = UITableViewCell();
println(itemCellIdentifier);
println(self.tableView);
println(self.tableView.dequeueReusableCellWithIdentifier(itemCellIdentifier as String));
if(itemCellIdentifier != nil){
cell = self.tableView.dequeueReusableCellWithIdentifier(itemCellIdentifier as String) as! UITableViewCell;
self.onCellForRowIndexSet(cell, rowData: dataContext[indexPath.row], indexPath: indexPath, canUserInteract: isSearchOn);
return cell;
}
return cell;
}
override func viewDidLoad() {
addRefresh();
addEdit();
super.viewDidLoad();
}
func prepareTableViewItem(itemCellId: NSString) {
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.itemCellIdentifier = itemCellId;
}
func prepareTableView(tableView: UITableView)-> Void{
self.tableView = tableView;
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
func getNumberOfRows() -> Int{
return dataContext.count;
}
/** Empty Stub**/
/** Derived Class Should Implement **/
func onCellForRowIndexSet(tableCell: UITableViewCell, rowData: AnyObject, indexPath: NSIndexPath) -> Void{
}
func onCellForRowIndexSet(tableCell: UITableViewCell, rowData: AnyObject,
indexPath: NSIndexPath, canUserInteract: Bool) -> Void{
}
func disableUserInteractionForTable(){
self.tableView.scrollEnabled=false;
self.tableView.userInteractionEnabled = false;
}
func enableUserInteractionForTable(){
self.tableView.scrollEnabled=true;
self.tableView.userInteractionEnabled = true;
}
func refreshList() -> Void{
println("Refreshing...");
self.tableView.reloadData();
}
private func addRefresh()->Void{
var refreshButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: Selector("onRefresh"));
self.navigationItem.setLeftBarButtonItem(refreshButton, animated: true);
}
private func addEdit()->Void{
var refreshButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: Selector("onEdit"));
self.navigationItem.setRightBarButtonItem(refreshButton, animated: true);
}
private func addToolbar(barButtonStyle: UIBarButtonItemStyle, position: NSString){
}
func setupDetailSegue(identifier: String) {
self.detailIdentifier = identifier;
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == self.detailIdentifier){
var rowIdx = self.tableView.indexPathForSelectedRow()?.row;
var selectedItem:AnyObject = self.dataContext[rowIdx!];
var detailView:DetailListViewController = segue.destinationViewController as! DetailListViewController;
detailView.dataEntity = selectedItem;
}
}
@objc func onEdit(){
self.tableView.setEditing(!isDirty, animated: true);
isDirty = !isDirty;
}
} | apache-2.0 | 2921ab25f4f425813eb3c8362438df99 | 29.839161 | 158 | 0.656611 | 5.389976 | false | false | false | false |
Himnshu/LoginLib | LoginLib/Classes/GradientImageView.swift | 1 | 1795 | //
// GradientImageView.swift
// Pods
//
// Created by Himanshu Mahajan on 26/07/17.
//
//
import UIKit
class GradientImageView: UIImageView {
@IBInspectable public var gradientColor: UIColor = UIColor.black {
didSet {
self.drawBackground()
}
}
@IBInspectable public var fadeColor: UIColor = UIColor.black {
didSet {
self.drawBackground()
}
}
@IBInspectable public var fadeAlpha: Float = 0.3 {
didSet {
self.drawBackground()
}
}
private var alphaLayer: CALayer?
private var gradientLayer: CAGradientLayer?
private let clearColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
drawBackground()
}
override init(image: UIImage?) {
super.init(image: image)
drawBackground()
}
override init(frame: CGRect) {
super.init(frame: frame)
drawBackground()
}
override func layoutSubviews() {
super.layoutSubviews()
alphaLayer?.frame = self.bounds
gradientLayer?.frame = self.bounds
}
func drawBackground() {
gradientLayer?.removeFromSuperlayer()
alphaLayer?.removeFromSuperlayer()
gradientLayer = CAGradientLayer()
alphaLayer = CALayer()
gradientLayer!.frame = bounds
gradientLayer!.colors = [clearColor.cgColor, gradientColor.cgColor]
gradientLayer!.locations = [0, 0.8]
alphaLayer!.frame = bounds
alphaLayer!.backgroundColor = fadeColor.cgColor
alphaLayer!.opacity = fadeAlpha
layer.insertSublayer(gradientLayer!, at: 0)
layer.insertSublayer(alphaLayer!, above: gradientLayer)
}
}
| mit | 0800edc6eb3b55cf32b2d33f1d5099fc | 22.012821 | 75 | 0.617827 | 4.864499 | false | false | false | false |
vzool/ios-nanodegree-virtual-tourist | Virtual Tourist/DFM.swift | 1 | 2024 | //
// DFM.swift
// Virtual Tourist
//
// Created by Abdelaziz Elrashed on 8/15/15.
// Copyright (c) 2015 Abdelaziz Elrashed. All rights reserved.
//
/*=================================================================================================*/
/*===================================== Document File Managment ===================================*/
/*=================================================================================================*/
import Foundation
import UIKit
class DFM{
static internal func saveImageToDocument(image: UIImage, fileName: String) -> String{
let fileManager = NSFileManager.defaultManager()
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var filePathToWrite = "\(paths)/\(fileName)"
var imageData: NSData = UIImageJPEGRepresentation(image, 1.0)
fileManager.createFileAtPath(filePathToWrite, contents: imageData, attributes: nil)
var getImagePath = paths.stringByAppendingPathComponent(fileName)
return getImagePath
}
static internal func loadImageFromDocument(imagePath: String) -> UIImage? {
if file_exists(imagePath){
return UIImage(contentsOfFile: imagePath)!
}else{
return nil
}
}
static internal func deleteImageFromDocument(imagePath: String){
let fileManager = NSFileManager.defaultManager()
if (fileManager.fileExistsAtPath(imagePath)){
var error:NSError?
fileManager.removeItemAtPath(imagePath, error: &error)
if let error = error{
println("Delete Error: \(error)")
}
}
}
static internal func file_exists(imagePath: String) -> Bool{
let fileManager = NSFileManager.defaultManager()
return fileManager.fileExistsAtPath(imagePath)
}
}
| mit | 0bcbec7b77ce423c5edf1525bcec999e | 31.126984 | 112 | 0.533597 | 6.114804 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/struct-outmodule-run.swift | 2 | 3480 | // RUN: %empty-directory(%t)
// RUN: %clang -c -v %target-cc-options -g -O0 -isysroot %sdk %S/Inputs/isPrespecialized.cpp -o %t/isPrespecialized.o -I %clang-include-dir -I %swift_src_root/include/ -I %swift_src_root/../llvm-project/llvm/include -I %clang-include-dir/../../llvm-macosx-x86_64/include -L %clang-include-dir/../lib/swift/macosx
// RUN: %target-build-swift %S/Inputs/struct-public-nonfrozen-1argument.swift -emit-module -emit-library -module-name Module -Xfrontend -prespecialize-generic-metadata -target %module-target-future -emit-module-path %t/Module.swiftmodule -o %t/%target-library-name(Module)
// RUN: %target-build-swift -v %mcp_opt %s %S/Inputs/main.swift %S/Inputs/consume-logging-metadata-value.swift %t/isPrespecialized.o -import-objc-header %S/Inputs/isPrespecialized.h -Xfrontend -prespecialize-generic-metadata -target %module-target-future -lc++ -I %t -L %t -lModule -L %clang-include-dir/../lib/swift/macosx -sdk %sdk -o %t/main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: swift_test_mode_optimize
// UNSUPPORTED: swift_test_mode_optimize_size
// UNSUPPORTED: remote_run
import Module
func ptr<T>(to ty: T.Type) -> UnsafeMutableRawPointer {
UnsafeMutableRawPointer(mutating: unsafePointerToMetadata(of: ty))!
}
struct FirstUsageDynamic {}
struct FirstUsageStatic {}
@inline(never)
func consumeType<T>(oneArgument: Module.OneArgument<T>.Type, line: UInt = #line) {
consumeType(oneArgument, line: line)
}
@inline(never)
func consumeType_OneArgumentAtFirstUsageStatic_Static(line: UInt = #line) {
consumeType(OneArgument<FirstUsageStatic>.self, line: line)
}
@inline(never)
func consumeType_OneArgumentAtFirstUsageStatic_Dynamic(line: UInt = #line) {
consumeType(oneArgument: OneArgument<FirstUsageStatic>.self, line: line)
}
@inline(never)
func consumeType_OneArgumentAtFirstUsageDynamic_Static(line: UInt = #line) {
consumeType(OneArgument<FirstUsageDynamic>.self, line: line)
}
@inline(never)
func consumeType_OneArgumentAtFirstUsageDynamic_Dynamic(line: UInt = #line) {
consumeType(oneArgument: OneArgument<FirstUsageDynamic>.self, line: line)
}
@inline(never)
func doit() {
// CHECK: [[STATIC_METADATA_ADDRESS:[0-9a-f]+]] @ 55
consumeType_OneArgumentAtFirstUsageStatic_Static()
// CHECK: [[STATIC_METADATA_ADDRESS]] @ 57
consumeType_OneArgumentAtFirstUsageStatic_Dynamic()
// CHECK: [[STATIC_METADATA_ADDRESS]] @ 59
consumeType_OneArgumentAtFirstUsageStatic_Dynamic()
// CHECK: [[DYNAMIC_METADATA_ADDRESS:[0-9a-f]+]] @ 61
consumeType_OneArgumentAtFirstUsageDynamic_Dynamic()
// CHECK: [[DYNAMIC_METADATA_ADDRESS:[0-9a-f]+]] @ 63
consumeType_OneArgumentAtFirstUsageDynamic_Dynamic()
// CHECK: [[DYNAMIC_METADATA_ADDRESS]] @ 65
consumeType_OneArgumentAtFirstUsageDynamic_Static()
let staticMetadata = ptr(to: OneArgument<FirstUsageStatic>.self)
// CHECK: [[STATIC_METADATA_ADDRESS]] @ 69
print(staticMetadata, "@", #line)
assert(isStaticallySpecializedGenericMetadata(staticMetadata))
assert(!isCanonicalStaticallySpecializedGenericMetadata(staticMetadata))
let dynamicMetadata = ptr(to: OneArgument<FirstUsageDynamic>.self)
// CHECK: [[DYNAMIC_METADATA_ADDRESS]] @ 75
print(dynamicMetadata, "@", #line)
assert(!isStaticallySpecializedGenericMetadata(dynamicMetadata))
assert(!isCanonicalStaticallySpecializedGenericMetadata(dynamicMetadata))
}
| apache-2.0 | 8ee167b951486f42aa0dc2ccbb406124 | 43.615385 | 344 | 0.757471 | 3.70607 | false | false | false | false |
WangCrystal/actor-platform | actor-apps/app-ios/ActorSwift/Strings.swift | 4 | 3695 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
extension String {
var length: Int { return self.characters.count }
func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet());
}
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
func first(count: Int) -> String {
let realCount = min(count, length);
return substringToIndex(startIndex.advancedBy(realCount));
}
func strip(set: NSCharacterSet) -> String {
return componentsSeparatedByCharactersInSet(set).joinWithSeparator("")
}
func replace(src: String, dest:String) -> String {
return stringByReplacingOccurrencesOfString(src, withString: dest, options: NSStringCompareOptions(), range: nil)
}
func toLong() -> Int64? {
return NSNumberFormatter().numberFromString(self)?.longLongValue
}
func smallValue() -> String {
let trimmed = trim();
if (trimmed.isEmpty){
return "#";
}
let letters = NSCharacterSet.letterCharacterSet()
let res: String = self[0];
if (res.rangeOfCharacterFromSet(letters) != nil) {
return res.uppercaseString;
} else {
return "#";
}
}
func hasPrefixInWords(prefix: String) -> Bool {
var components = self.componentsSeparatedByString(" ")
for i in 0..<components.count {
if components[i].lowercaseString.hasPrefix(prefix.lowercaseString) {
return true
}
}
return false
}
func contains(text: String) -> Bool {
return self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil
}
func rangesOfString(text: String) -> [Range<String.Index>] {
var res = [Range<String.Index>]()
var searchRange = Range<String.Index>(start: self.startIndex, end: self.endIndex)
while true {
let found = self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
if found != nil {
res.append(found!)
searchRange = Range<String.Index>(start: found!.endIndex, end: self.endIndex)
} else {
break
}
}
return res
}
func repeatString(count: Int) -> String {
var res = ""
for _ in 0..<count {
res += self
}
return res
}
var asNS: NSString { return (self as NSString) }
}
extension NSAttributedString {
func append(text: NSAttributedString) -> NSAttributedString {
let res = NSMutableAttributedString()
res.appendAttributedString(self)
res.appendAttributedString(text)
return res
}
func append(text: String, font: UIFont) -> NSAttributedString {
return append(NSAttributedString(string: text, attributes: [NSFontAttributeName: font]))
}
convenience init(string: String, font: UIFont) {
self.init(string: string)
}
}
extension NSMutableAttributedString {
func appendFont(font: UIFont) {
self.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, self.length))
}
func appendColor(color: UIColor) {
self.addAttribute(NSForegroundColorAttributeName, value: color.CGColor, range: NSMakeRange(0, self.length))
}
}
| mit | eb1e2ca02b2a932ef3ddedc1b3bf2dfd | 28.56 | 136 | 0.602706 | 4.913564 | false | false | false | false |
mathewa6/QTR | QuadTree.playground/Sources/HelpersDebug.swift | 1 | 3990 | import Foundation
import CoreLocation
//Basic Conversion functions.From DSAlgorithm.
public func radianToDegrees(_ radians: Double) -> Double {
return (radians * (180/Double.pi))
}
public func degreesToRadians(_ degrees: Double) -> Double {
return (degrees * (Double.pi/180))
}
/// - Returns 1/-1 for non zero values.
/// - Returns 0 for error
///
public func sgn(_ value: Double) -> Int {
if value == 0 {
return 0
}
return Int(abs(value)/value)
}
public func haversineDistanceBetweenCoordinates(_ coordinate: CLLocationCoordinate2D, otherCoordinate: CLLocationCoordinate2D) -> Double
{
let R: Double = 6378137
let deltaLat = degreesToRadians((otherCoordinate.latitude - coordinate.latitude))
let deltaLong = degreesToRadians((otherCoordinate.longitude - coordinate.longitude))
let radianLatCoordinate = degreesToRadians(coordinate.latitude)
let radianLatOther = degreesToRadians(otherCoordinate.latitude)
let a = pow(sin(deltaLat/2.0), 2) + cos(radianLatCoordinate)*cos(radianLatOther)*pow(sin(deltaLong/2.0), 2)
let c = 2 * atan2(sqrt(a), sqrt(1-a))
return (R * c)
}
public func equiRectangularDistanceBetweenCoordinates(_ coordinate: CLLocationCoordinate2D, otherCoordinate: CLLocationCoordinate2D) -> Double {
let R: Double = 6378137
let deltaLat = degreesToRadians((otherCoordinate.latitude - coordinate.latitude))
let deltaLong = degreesToRadians((otherCoordinate.longitude - coordinate.longitude))
let radianLatCoordinate = degreesToRadians(coordinate.latitude)
let radianLatOther = degreesToRadians(otherCoordinate.latitude)
let x = deltaLong * cos((radianLatCoordinate + radianLatOther)/2.0)
let y = deltaLat
return R * sqrt(pow(x, 2) + pow(y, 2))
}
func closestPointInNode(_ node: QTRNode, toPoint point: QTRNodePoint) -> (QTRNodePoint?, Double?) {
var distance: Double?
var returnPoint: QTRNodePoint?
for p in node.points {
let temp = point.distanceFrom(p.coordinate2D)
if distance == nil || temp < distance! {
if temp > 80.0 {
distance = temp
returnPoint = p
}
}
}
if returnPoint == nil && distance == nil && node.parent != nil{
(returnPoint,distance) = closestPointInNode(node.parent!, toPoint: point)
}
return (returnPoint,distance ?? 80.0)
}
func scaledValue(_ x: Double, alpha: Double, beta: Double, max: Double) -> Double{
return max*(exp(-1.0 * alpha * pow(x, beta)))
}
public func nearestNeighbours(toPoint point: QTRNodePoint, startingAt node:QTRNode, andApply map: (QTRNodePoint) -> ()) {
let n = node.nodeContaining(point) ?? node
let (p, d) = closestPointInNode(n, toPoint: point)
let factor = scaledValue(d!, alpha: 0.03, beta: 0.65, max: 3.0)
// p?.name
//
// d!
// d!*factor
let userB = QTRBBox(aroundCoordinate: point.coordinate2D, withBreadth: factor * d!)
// node.getByTraversingUp(pointsIn: userB, andApply: { (nd: QTRNodePoint) -> () in
// print(nd.name)
// })
node.get(pointsIn: userB, andApply: map)
}
public func nearestNeighboursAlternate(toPoint point: QTRNodePoint, startingAt node:QTRNode, canUseParent parent: Bool, andApply map: (QTRNodePoint) -> ()) {
let nodeContainer = node.nodeContaining(point)
let nodeBoxSpan = parent ? nodeContainer!.parent!.bbox.span : nodeContainer!.bbox.span
let bbox = QTRBBox(aroundCoordinate: point.coordinate2D, withSpan: nodeBoxSpan)
node.get(pointsIn: bbox, andApply: map)
}
func generateRandomPoint(inRange bbox: QTRBBox) -> CLLocationCoordinate2D {
let p = Double(arc4random_uniform(250))*(bbox.highLatitude - bbox.lowLatitude)/100 + bbox.lowLatitude
let q = Double(arc4random_uniform(250))*(bbox.highLongitude - bbox.lowLongitude)/100 + bbox.lowLongitude
return CLLocationCoordinate2DMake(p, q)
}
func generateQTRPointArray(ofLength length: Int, inRange bbox: QTRBBox) -> [QTRNodePoint] {
var returnArray = [QTRNodePoint]()
for i in 0..<length {
returnArray.append(QTRNodePoint(generateRandomPoint(inRange: bbox), "RandomPoint_" + "\(i)"))
}
return returnArray
}
| mit | 5772bf526531fbadb3a1387bcc3dbd8d | 31.975207 | 157 | 0.726065 | 3.509235 | false | false | false | false |
yaslab/Harekaze-iOS | Harekaze/ViewControllers/Settings/SettingValueSelectionViewController.swift | 1 | 7368 | /**
*
* SettingValueSelectionViewController.swift
* Harekaze
* Created by Yuki MIZUNO on 2016/08/16.
*
* Copyright (c) 2016-2017, Yuki MIZUNO
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
import SpringIndicator
struct DataSourceItem {
var title: String!
var detail: String!
var stringValue: String!
var intValue: Int!
}
enum ValueSelectionMode {
case videoSize, videoQuality, audioQuality, oneFingerHorizontalSwipeMode
}
class SettingValueSelectionViewController: MaterialContentAlertViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Instance fields
var tableView: UITableView!
var dataSource: [DataSourceItem] = []
var mode: ValueSelectionMode = .videoSize
// MARK: - View initialization
override func viewDidLoad() {
super.viewDidLoad()
self.alertView.bottomBar?.dividerColor = UIColor.clear
// Table view
self.tableView.register(UINib(nibName: "ChinachuWUIListTableViewCell", bundle: nil), forCellReuseIdentifier: "ChinachuWUIListTableViewCell")
self.tableView.separatorInset = UIEdgeInsets.zero
self.tableView.rowHeight = 72
self.tableView.height = 72 * 3
self.tableView.isScrollEnabled = false
self.tableView.separatorStyle = .none
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.backgroundColor = Material.Color.clear
switch mode {
case .videoSize:
dataSource.append(DataSourceItem(title: "Full HD", detail: "1080p", stringValue: "1920x1080", intValue: 0))
dataSource.append(DataSourceItem(title: "HD", detail: "720p", stringValue: "1280x720", intValue: 0))
dataSource.append(DataSourceItem(title: "SD", detail: "480p", stringValue: "853x480", intValue: 0))
case .videoQuality:
dataSource.append(DataSourceItem(title: "High quality", detail: "H.264 3Mbps", stringValue: "", intValue: 3192))
dataSource.append(DataSourceItem(title: "Middle quality", detail: "H.264 1Mbps", stringValue: "", intValue: 1024))
dataSource.append(DataSourceItem(title: "Low quality", detail: "H.264 512kbps", stringValue: "", intValue: 512))
case .audioQuality:
dataSource.append(DataSourceItem(title: "High quality", detail: "AAC 192kbps", stringValue: "", intValue: 192))
dataSource.append(DataSourceItem(title: "Middle quality", detail: "AAC 128kbps", stringValue: "", intValue: 128))
dataSource.append(DataSourceItem(title: "Low quality", detail: "AAC 64kbps", stringValue: "", intValue: 64))
case .oneFingerHorizontalSwipeMode:
dataSource.append(DataSourceItem(title: "Change playback speed", detail: "Increase or decrease play rate", stringValue: "", intValue: 0))
dataSource.append(DataSourceItem(title: "Seek +/- 30 seconds", detail: "30 seconds backward/forward skip", stringValue: "", intValue: 1))
dataSource.append(DataSourceItem(title: "No action", detail: "No swipe gesture", stringValue: "", intValue: -1))
}
let constraint = NSLayoutConstraint(item: alertView, attribute: .height, relatedBy: .lessThanOrEqual,
toItem: nil, attribute: .height, multiplier: 1, constant: 340)
view.addConstraint(constraint)
}
// MARK: - Memory/resource management
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 72
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
cell.preservesSuperviewLayoutMargins = false
cell.backgroundColor = Material.Color.clear
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ChinachuWUIListTableViewCell", for: indexPath) as? ChinachuWUIListTableViewCell else {
return UITableViewCell()
}
let service = dataSource[(indexPath as NSIndexPath).row]
cell.titleLabel?.text = service.title
cell.detailLabel?.text = service.detail
cell.lockIcon = nil
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath as NSIndexPath).row == dataSource.count {
return
}
switch mode {
case .videoSize:
ChinachuAPI.videoResolution = dataSource[(indexPath as NSIndexPath).row].stringValue
case .videoQuality:
ChinachuAPI.videoBitrate = dataSource[(indexPath as NSIndexPath).row].intValue
case .audioQuality:
ChinachuAPI.audioBitrate = dataSource[(indexPath as NSIndexPath).row].intValue
case .oneFingerHorizontalSwipeMode:
let userDefaults = UserDefaults()
userDefaults.set(dataSource[(indexPath as NSIndexPath).row].intValue, forKey: "OneFingerHorizontalSwipeMode")
userDefaults.synchronize()
}
dismiss(animated: true, completion: nil)
guard let navigationController = presentingViewController as? NavigationController else {
return
}
guard let settingsTableViewController = navigationController.viewControllers.first as? SettingsTableViewController else {
return
}
settingsTableViewController.reloadSettingsValue()
}
// MARK: - Initialization
override init() {
super.init()
}
convenience init(title: String, mode: ValueSelectionMode) {
self.init()
_title = title
self.mode = mode
self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
self.contentView = self.tableView
self.modalPresentationStyle = .overCurrentContext
self.modalTransitionStyle = .crossDissolve
}
internal required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| bsd-3-clause | 1eead2ead7a13a1607b3a42e6c929dca | 38.191489 | 152 | 0.758686 | 4.256499 | false | false | false | false |
manavgabhawala/CocoaMultipeer | MultipeerCocoaiOS/MGBrowserTableViewController.swift | 1 | 8846 | //
// MGBrowserViewController.swift
// CocoaMultipeer
//
// Created by Manav Gabhawala on 05/07/15.
//
//
import UIKit
protocol MGBrowserTableViewControllerDelegate : NSObjectProtocol
{
var minimumPeers: Int { get }
var maximumPeers: Int { get }
}
@objc internal class MGBrowserTableViewController: UITableViewController
{
/// The browser passed to the initializer for which this class is presenting a UI for. (read-only)
internal let browser: MGNearbyServiceBrowser
/// The session passed to the initializer for which this class is presenting a UI for. (read-only)
internal let session: MGSession
internal weak var delegate: MGBrowserTableViewControllerDelegate!
private var availablePeers = [MGPeerID]()
/// Initializes a browser view controller with the provided browser and session.
/// - Parameter browser: An object that the browser view controller uses for browsing. This is usually an instance of MGNearbyServiceBrowser. However, if your app is using a custom discovery scheme, you can instead pass any custom subclass that calls the methods defined in the MCNearbyServiceBrowserDelegate protocol on its delegate when peers are found and lost.
/// - Parameter session: The multipeer session into which the invited peers are connected.
/// - Returns: An initialized browser.
/// - Warning: If you want the browser view controller to manage the browsing process, the browser object must not be actively browsing, and its delegate must be nil.
internal init(browser: MGNearbyServiceBrowser, session: MGSession, delegate: MGBrowserTableViewControllerDelegate)
{
self.browser = browser
self.session = session
self.delegate = delegate
super.init(style: .Grouped)
self.browser.delegate = self
}
required internal init?(coder aDecoder: NSCoder)
{
let peer = MGPeerID()
self.browser = MGNearbyServiceBrowser(peer: peer, serviceType: "custom-server")
self.session = MGSession(peer: peer)
super.init(coder: aDecoder)
self.browser.delegate = self
}
internal override func viewDidLoad()
{
navigationItem.title = ""
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "donePressed:")
navigationItem.rightBarButtonItem?.enabled = false
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancelPressed:")
}
internal override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
browser.startBrowsingForPeers()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionUpdated:", name: MGSession.sessionPeerStateUpdatedNotification, object: session)
tableView.reloadData()
}
internal override func viewDidDisappear(animated: Bool)
{
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: MGSession.sessionPeerStateUpdatedNotification, object: session)
browser.stopBrowsingForPeers()
}
internal func sessionUpdated(notification: NSNotification)
{
guard notification.name == MGSession.sessionPeerStateUpdatedNotification
else
{
return
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadSections(NSIndexSet(indexesInRange: NSRange(location: 0, length: 2)), withRowAnimation: .Automatic)
})
if self.session.connectedPeers.count >= self.delegate.minimumPeers
{
self.navigationItem.rightBarButtonItem?.enabled = true
}
else
{
self.navigationItem.rightBarButtonItem?.enabled = false
}
}
// MARK: - Actions
internal func donePressed(sender: UIBarButtonItem)
{
guard session.connectedPeers.count >= delegate.minimumPeers && session.connectedPeers.count <= delegate.maximumPeers
else
{
sender.enabled = false
return
}
dismissViewControllerAnimated(true, completion: nil)
}
internal func cancelPressed(sender: UIBarButtonItem)
{
session.disconnect()
dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: - TableViewStuff
extension MGBrowserTableViewController
{
internal override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 2
}
internal override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return section == 0 ? session.peers.count : availablePeers.count
}
internal override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : UITableViewCell
if indexPath.section == 0
{
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "connected")
cell.textLabel!.text = session.peers[indexPath.row].peer.displayName
cell.detailTextLabel!.text = session.peers[indexPath.row].state.description
cell.selectionStyle = .None
}
else
{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "available")
if availablePeers.count > indexPath.row
{
cell.textLabel!.text = availablePeers[indexPath.row].displayName
}
cell.selectionStyle = .Default
}
return cell
}
internal override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.cellForRowAtIndexPath(indexPath)!.setHighlighted(false, animated: true)
guard indexPath.section == 1 && delegate.maximumPeers > session.peers.count
else { return }
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
do
{
try self.browser.invitePeer(self.availablePeers[indexPath.row], toSession: self.session)
}
catch
{
MGLog("Couldn't find peer. Refreshing.")
MGDebugLog("Attemtpting to connect to an unknown service. Removing the listing and refreshing the view to recover. \(error)")
self.availablePeers.removeAtIndex(indexPath.row)
// Couldn't find the peer so let's reload the table.
dispatch_async(dispatch_get_main_queue(), self.tableView.reloadData)
}
})
}
internal override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return section == 0 ? "Connected Peers" : "Available Peers"
}
internal override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String?
{
return section == 0 ? nil : "This device will appear as \(browser.myPeerID.displayName). You must connect to at least \(delegate.minimumPeers.peerText) and no more than \(delegate.maximumPeers.peerText)."
}
}
// MARK: - Browser stuff
extension MGBrowserTableViewController : MGNearbyServiceBrowserDelegate
{
internal func browserDidStartSuccessfully(browser: MGNearbyServiceBrowser)
{
tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic)
}
internal func browser(browser: MGNearbyServiceBrowser, didNotStartBrowsingForPeers error: [String : NSNumber])
{
// TODO: Handle the error.
}
internal func browser(browser: MGNearbyServiceBrowser, foundPeer peerID: MGPeerID, withDiscoveryInfo info: [String : String]?)
{
assert(browser === self.browser)
guard peerID != session.myPeerID && peerID != browser.myPeerID
else { return } // This should never happen but its better to check
availablePeers.append(peerID)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic)
})
}
internal func browser(browser: MGNearbyServiceBrowser, lostPeer peerID: MGPeerID)
{
assert(browser === self.browser)
guard peerID != session.myPeerID && peerID != browser.myPeerID
else
{
// FIXME: Fail silently
fatalError("We lost the browser to our own peer. Something went wrong in the browser.")
}
availablePeers.removeElement(peerID)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic)
})
}
internal func browser(browser: MGNearbyServiceBrowser, didReceiveInvitationFromPeer peerID: MGPeerID, invitationHandler: (Bool, MGSession) -> Void)
{
guard session.connectedPeers.count == 0
else
{
// We are already connected to some peers so we can't accept any other connections.
invitationHandler(false, session)
return
}
let alertController = UIAlertController(title: "\(peerID.displayName) wants to connect?", message: nil, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Decline", style: .Destructive, handler: { action in
invitationHandler(false, self.session)
}))
alertController.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default, handler: {action in
invitationHandler(true, self.session)
// Remove self since we accepted the connection.
self.dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(alertController, animated: true, completion: nil)
}
internal func browserStoppedSearching(browser: MGNearbyServiceBrowser)
{
// availablePeers.removeAll()
}
} | apache-2.0 | 280e23f869ab787974ff06e839f67add | 37.465217 | 365 | 0.765544 | 4.28793 | false | false | false | false |
takeshineshiro/Eureka | Tests/HiddenRowsTests.swift | 3 | 8384 | // HiddenRowsTests.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Eureka
class HiddenRowsTests: BaseEurekaTests {
var form : Form!
let row10 = IntRow("int1_hrt"){
$0.hidden = "$IntRow_s1 > 23" // .Predicate(NSPredicate(format: "$IntRow_s1 > 23"))
}
let row11 = TextRow("txt1_hrt"){
$0.hidden = .Function(["NameRow_s1"], { form in
if let r1 : NameRow = form.rowByTag("NameRow_s1") {
return r1.value?.containsString(" is ") ?? false
}
return false
})
}
let sec2 = Section("Whatsoever"){
$0.tag = "s3_hrt"
$0.hidden = "$NameRow_s1 contains 'God'" //.Predicate(NSPredicate(format: "$NameRow_s1 contains 'God'"))
}
let row20 = TextRow("txt2_hrt"){
$0.hidden = .Function(["IntRow_s1", "NameRow_s1"], { form in
if let r1 : IntRow = form.rowByTag("IntRow_s1"), let r2 : NameRow = form.rowByTag("NameRow_s1") {
return r1.value == 88 || r2.value?.hasSuffix("real") ?? false
}
return false
})
}
override func setUp() {
super.setUp()
form = shortForm
+++ row10
<<< row11
+++ sec2
<<< row20
}
func testAddRowToObserver(){
let intDep = form.rowObservers["IntRow_s1"]?[.Hidden]
let nameDep = form.rowObservers["NameRow_s1"]?[.Hidden]
// make sure we can unwrap
XCTAssertNotNil(intDep)
XCTAssertNotNil(nameDep)
// test rowObservers
XCTAssertEqual(intDep!.count, 2)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains({ $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains({ $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains({ $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains({ $0.tag == "int1_hrt" }))
//This should not change when some rows hide ...
form[0][0].baseValue = "God is real"
form[0][1].baseValue = 88
//check everything is still the same
XCTAssertEqual(intDep!.count, 2)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains({ $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains({ $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains({ $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains({ $0.tag == "int1_hrt" }))
// ...nor if they reappear
form[0][0].baseValue = "blah blah blah"
form[0][1].baseValue = 1
//check everything is still the same
XCTAssertEqual(intDep!.count, 2)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains({ $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains({ $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains({ $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains({ $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains({ $0.tag == "int1_hrt" }))
}
func testItemsByTag(){
// test that all rows and sections with tag are there
XCTAssertEqual(form.rowByTag("NameRow_s1"), form[0][0])
XCTAssertEqual(form.rowByTag("IntRow_s1"), form[0][1])
XCTAssertEqual(form.rowByTag("int1_hrt"), row10)
XCTAssertEqual(form.rowByTag("txt1_hrt"), row11)
XCTAssertEqual(form.sectionByTag("s3_hrt"), sec2)
XCTAssertEqual(form.rowByTag("txt2_hrt"), row20)
// check that these are all in there
XCTAssertEqual(form.rowsByTag.count, 5)
// what happens after hiding the rows? Let's cause havoc
form[0][0].baseValue = "God is real"
form[0][1].baseValue = 88
// we still want the same results here
XCTAssertEqual(form.rowByTag("NameRow_s1"), form[0][0])
XCTAssertEqual(form.rowByTag("IntRow_s1"), form[0][1])
XCTAssertEqual(form.rowByTag("int1_hrt"), row10)
XCTAssertEqual(form.rowByTag("txt1_hrt"), row11)
XCTAssertEqual(form.sectionByTag("s3_hrt"), sec2)
XCTAssertEqual(form.rowByTag("txt2_hrt"), row20)
XCTAssertEqual(form.rowsByTag.count, 5)
// and let them come up again
form[0][0].baseValue = "blah blah"
form[0][1].baseValue = 1
// we still want the same results here
XCTAssertEqual(form.rowsByTag["NameRow_s1"], form[0][0])
XCTAssertEqual(form.rowsByTag["IntRow_s1"], form[0][1])
XCTAssertEqual(form.rowsByTag["int1_hrt"], row10)
XCTAssertEqual(form.rowsByTag["txt1_hrt"], row11)
XCTAssertEqual(form.sectionByTag("s3_hrt"), sec2)
XCTAssertEqual(form.rowsByTag["txt2_hrt"], row20)
XCTAssertEqual(form.rowsByTag.count, 5)
}
func testCorrectValues(){
//initial empty values (none is hidden)
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 1)
// false values
form[0][0].baseValue = "Hi there"
form[0][1].baseValue = 15
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 1)
// hide 'int1_hrt' row
form[0][1].baseValue = 24
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 1)
XCTAssertEqual(sec2.count, 1)
XCTAssertEqual(form[1][0].tag, "txt1_hrt")
// hide 'txt1_hrt' and 'txt2_hrt'
form[0][0].baseValue = " is real"
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
XCTAssertEqual(sec2.count, 0)
// let the last section disappear
form[0][0].baseValue = "God is real"
XCTAssertEqual(form.count, 2)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
// and see if they come back to live
form[0][0].baseValue = "blah"
form[0][1].baseValue = 2
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 1)
}
}
| mit | 055718b63f827e684d0a6719e4a5439a | 38.92381 | 124 | 0.579437 | 4.11182 | false | false | false | false |
BennyKJohnson/OpenCloudKit | Sources/Bridging.swift | 1 | 5107 | //
// Bridging.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 20/07/2016.
//
//
import Foundation
public protocol _OCKBridgable {
associatedtype ObjectType
func bridge() -> ObjectType
}
public protocol CKNumberValueType: CKRecordValue {}
extension CKNumberValueType where Self: _OCKBridgable, Self.ObjectType == NSNumber {
public var recordFieldDictionary: [String: Any] {
return ["value": self.bridge()]
}
}
extension String: _OCKBridgable {
public typealias ObjectType = NSString
public func bridge() -> NSString {
return NSString(string: self)
}
}
extension Int: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension UInt: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Float: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Double: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Dictionary {
func bridge() -> NSDictionary {
var newDictionary: [NSString: Any] = [:]
for (key,value) in self {
if let stringKey = key as? String {
newDictionary[stringKey.bridge()] = value
} else if let nsstringKey = key as? NSString {
newDictionary[nsstringKey] = value
}
}
return newDictionary._bridgeToObjectiveC()
}
}
#if !os(Linux)
typealias NSErrorUserInfoType = [AnyHashable: Any]
public extension NSString {
func bridge() -> String {
return self as String
}
}
extension NSArray {
func bridge() -> Array<Any> {
return self as! Array<Any>
}
}
extension NSDictionary {
public func bridge() -> [NSObject: Any] {
return self as [NSObject: AnyObject]
}
}
extension Array {
func bridge() -> NSArray {
return self as NSArray
}
}
extension Date {
func bridge() -> NSDate {
return self as NSDate
}
}
extension NSDate {
func bridge() -> Date {
return self as Date
}
}
extension NSData {
func bridge() -> Data {
return self as Data
}
}
#elseif os(Linux)
typealias NSErrorUserInfoType = [String: Any]
public extension NSString {
func bridge() -> String {
return self._bridgeToSwift()
}
}
extension NSArray {
public func bridge() -> Array<Any> {
return self._bridgeToSwift()
}
}
extension NSDictionary {
public func bridge() -> [AnyHashable: Any] {
return self._bridgeToSwift()
}
}
extension Array {
public func bridge() -> NSArray {
return self._bridgeToObjectiveC()
}
}
extension NSData {
public func bridge() -> Data {
return self._bridgeToSwift()
}
}
extension Date {
public func bridge() -> NSDate {
return self._bridgeToObjectiveC()
}
}
extension NSDate {
public func bridge() -> Date {
return self._bridgeToSwift()
}
}
#endif
extension NSError {
public convenience init(error: Error) {
var userInfo: [String : Any] = [:]
var code: Int = 0
// Retrieve custom userInfo information.
if let customUserInfoError = error as? CustomNSError {
userInfo = customUserInfoError.errorUserInfo
code = customUserInfoError.errorCode
}
if let localizedError = error as? LocalizedError {
if let description = localizedError.errorDescription {
userInfo[NSLocalizedDescriptionKey] = description
}
if let reason = localizedError.failureReason {
userInfo[NSLocalizedFailureReasonErrorKey] = reason
}
if let suggestion = localizedError.recoverySuggestion {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = suggestion
}
if let helpAnchor = localizedError.helpAnchor {
userInfo[NSHelpAnchorErrorKey] = helpAnchor
}
}
if let recoverableError = error as? RecoverableError {
userInfo[NSLocalizedRecoveryOptionsErrorKey] = recoverableError.recoveryOptions
// userInfo[NSRecoveryAttempterErrorKey] = recoverableError
}
self.init(domain: "OpenCloudKit", code: code, userInfo: userInfo)
}
}
| mit | 7e263570640b80341a4a18259dfd3be0 | 21.799107 | 91 | 0.558449 | 5.415695 | false | false | false | false |
Geor9eLau/WorkHelper | Carthage/Checkouts/SwiftCharts/Examples/Examples/TrendlineExample.swift | 1 | 2749 | //
// TrendlineExample.swift
// Examples
//
// Created by ischuetz on 03/08/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class TrendlineExample: UIViewController {
fileprivate var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let chartPoints: [ChartPoint] = [(1, 3), (2, 5), (3, 7.5), (4, 10), (5, 6), (6, 12)].map{ChartPoint(x: ChartAxisValueDouble($0.0, labelSettings: labelSettings), y: ChartAxisValueDouble($0.1))}
let xValues = chartPoints.map{$0.x}
let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.red, animDuration: 1, animDelay: 0)
let trendLineModel = ChartLineModel(chartPoints: TrendlineGenerator.trendline(chartPoints), lineColor: UIColor.blue, animDuration: 0.5, animDelay: 1)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel])
let trendLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [trendLineModel])
let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
chartPointsLineLayer,
trendLineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| mit | fa41f42f72880453b6076e01f379f779 | 47.22807 | 259 | 0.692252 | 5.337864 | false | false | false | false |
chizcake/ReplayKitExample | ReplayKitExampleStarter/Carthage/Checkouts/CleanroomLogger/Sources/FileLogRecorder.swift | 2 | 3323 | //
// FileLogRecorder.swift
// CleanroomLogger
//
// Created by Evan Maloney on 5/12/15.
// Copyright © 2015 Gilt Groupe. All rights reserved.
//
import Darwin.C.stdio
import Dispatch
/**
A `LogRecorder` implementation that appends log entries to a file.
- note: `FileLogRecorder` is a simple log appender that provides no mechanism
for file rotation or truncation. Unless you manually manage the log file when
a `FileLogRecorder` doesn't have it open, you will end up with an ever-growing
file. Use a `RotatingLogFileRecorder` instead if you'd rather not have to
concern yourself with such details.
*/
open class FileLogRecorder: LogRecorderBase
{
/** The path of the file to which log entries will be written. */
open let filePath: String
private let file: UnsafeMutablePointer<FILE>?
private let newlines: [Character] = ["\n", "\r"]
/**
Attempts to initialize a new `FileLogRecorder` instance to use the
given file path and log formatters. This will fail if `filePath` could
not be opened for writing.
- parameter filePath: The path of the file to be written. The containing
directory must exist and be writable by the process. If the file does not
yet exist, it will be created; if it does exist, new log messages will be
appended to the end of the file.
- parameter formatters: An array of `LogFormatter`s to use for formatting
log entries to be recorded by the receiver. Each formatter is consulted in
sequence, and the formatted string returned by the first formatter to
yield a non-`nil` value will be recorded. If every formatter returns `nil`,
the log entry is silently ignored and not recorded.
*/
public init?(filePath: String, formatters: [LogFormatter])
{
let f = fopen(filePath, "a")
guard f != nil else {
return nil
}
self.filePath = filePath
self.file = f
super.init(formatters: formatters)
}
deinit {
// we've implemented FileLogRecorder as a class so we
// can have a de-initializer to close the file
if file != nil {
fclose(file)
}
}
/**
Called by the `LogReceptacle` to record the specified log message.
- note: This function is only called if one of the `formatters` associated
with the receiver returned a non-`nil` string for the given `LogEntry`.
- parameter message: The message to record.
- parameter entry: The `LogEntry` for which `message` was created.
- parameter currentQueue: The GCD queue on which the function is being
executed.
- parameter synchronousMode: If `true`, the receiver should record the log
entry synchronously and flush any buffers before returning.
*/
open override func record(message: String, for entry: LogEntry, currentQueue: DispatchQueue, synchronousMode: Bool)
{
var addNewline = true
let chars = message.characters
if chars.count > 0 {
let lastChar = chars[chars.index(before: chars.endIndex)]
addNewline = !newlines.contains(lastChar)
}
fputs(message, file)
if addNewline {
fputc(0x0A, file)
}
if synchronousMode {
fflush(file)
}
}
}
| mit | de6b481b6c65c23226fd3e373a6c4848 | 31.568627 | 119 | 0.665864 | 4.53206 | false | false | false | false |
armendo/CP-W3-Yelp | Yelp/Business.swift | 2 | 3183 | //
// Business.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class Business: NSObject {
let name: String?
let address: String?
let imageURL: NSURL?
let categories: String?
let distance: String?
let ratingImageURL: NSURL?
let reviewCount: NSNumber?
init(dictionary: NSDictionary) {
name = dictionary["name"] as? String
let imageURLString = dictionary["image_url"] as? String
if imageURLString != nil {
imageURL = NSURL(string: imageURLString!)!
} else {
imageURL = nil
}
let location = dictionary["location"] as? NSDictionary
var address = ""
if location != nil {
let addressArray = location!["address"] as? NSArray
if addressArray != nil && addressArray!.count > 0 {
address = addressArray![0] as! String
}
let neighborhoods = location!["neighborhoods"] as? NSArray
if neighborhoods != nil && neighborhoods!.count > 0 {
if !address.isEmpty {
address += ", "
}
address += neighborhoods![0] as! String
}
}
self.address = address
let categoriesArray = dictionary["categories"] as? [[String]]
if categoriesArray != nil {
var categoryNames = [String]()
for category in categoriesArray! {
let categoryName = category[0]
categoryNames.append(categoryName)
}
categories = categoryNames.joinWithSeparator(", ")
} else {
categories = nil
}
let distanceMeters = dictionary["distance"] as? NSNumber
if distanceMeters != nil {
let milesPerMeter = 0.000621371
distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue)
} else {
distance = nil
}
let ratingImageURLString = dictionary["rating_img_url_large"] as? String
if ratingImageURLString != nil {
ratingImageURL = NSURL(string: ratingImageURLString!)
} else {
ratingImageURL = nil
}
reviewCount = dictionary["review_count"] as? NSNumber
}
class func businesses(array array: [NSDictionary]) -> [Business] {
var businesses = [Business]()
for dictionary in array {
let business = Business(dictionary: dictionary)
businesses.append(business)
}
return businesses
}
class func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) {
YelpClient.sharedInstance.searchWithTerm(term, completion: completion)
}
class func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> Void {
YelpClient.sharedInstance.searchWithTerm(term, sort: sort, categories: categories, deals: deals, completion: completion)
}
}
| apache-2.0 | 5d2ca5181868e3eb812960114d4ded1f | 32.861702 | 156 | 0.568646 | 5.020505 | false | false | false | false |
hanhailong/practice-swift | CoreMotion/MotionMonitor/MotionMonitor/ViewController.swift | 2 | 2369 | //
// ViewController.swift
// MotionMonitor
//
// Created by Domenico on 02/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import CoreMotion
class ViewController: UIViewController {
@IBOutlet var gyroscopeLabel:UILabel!
@IBOutlet var accelerometerLabel:UILabel!
@IBOutlet var attitudeLabel:UILabel!
private let motionManager = CMMotionManager()
private let queue = NSOperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
if motionManager.deviceMotionAvailable {
motionManager.deviceMotionUpdateInterval = 0.1
motionManager.startDeviceMotionUpdatesToQueue(queue,
withHandler: {
(motion:CMDeviceMotion!, error:NSError!) -> Void in
let rotationRate = motion.rotationRate
let gravity = motion.gravity
let userAcc = motion.userAcceleration
let attitude = motion.attitude
let gyroscopeText =
String(format:"Rotation Rate:\n-----------------\n" +
"x: %+.2f\ny: %+.2f\nz: %+.2f\n",
rotationRate.x, rotationRate.y, rotationRate.z)
let acceleratorText =
String(format:"Acceleration:\n---------------\n" +
"Gravity x: %+.2f\t\tUser x: %+.2f\n" +
"Gravity y: %+.2f\t\tUser y: %+.2f\n" +
"Gravity z: %+.2f\t\tUser z: %+.2f\n",
gravity.x, userAcc.x, gravity.y,
userAcc.y, gravity.z,userAcc.z)
let attitudeText =
String(format:"Attitude:\n----------\n" +
"Roll: %+.2f\nPitch: %+.2f\nYaw: %+.2f\n",
attitude.roll, attitude.pitch, attitude.yaw)
// You need to dispatch the results to the main queue
dispatch_async(dispatch_get_main_queue(), {
self.gyroscopeLabel.text = gyroscopeText
self.accelerometerLabel.text = acceleratorText
self.attitudeLabel.text = attitudeText
})
})
}
}
}
| mit | 26875a47f32fdb6b42aa4842cb82446b | 37.836066 | 73 | 0.49599 | 5.051173 | false | false | false | false |
cameronklein/SwiftPasscodeLock | PasscodeLockTests/Fakes/FakePasscodeState.swift | 5 | 689 | //
// FakePasscodeState.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
class FakePasscodeState: PasscodeLockStateType {
var title = "A"
var description = "B"
var isCancellableAction = true
var isTouchIDAllowed = true
var acceptPaccodeCalled = false
var acceptedPasscode = [String]()
var numberOfAcceptedPasscodes = 0
init() {}
func acceptPasscode(passcode: [String], fromLock lock: PasscodeLockType) {
acceptedPasscode = passcode
acceptPaccodeCalled = true
numberOfAcceptedPasscodes += 1
}
}
| mit | fbe1a85989a20e7f27f475f9c4b5e499 | 21.933333 | 78 | 0.662791 | 4.586667 | false | false | false | false |
woodcockjosh/FastContact | FastContact/MasterViewController.swift | 1 | 9517 | //
// MasterViewController.swift
// FastContact
//
// Created by Josh Woodcock on 8/22/15.
// Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! NSManagedObject
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
var error: NSError? = nil
if !context.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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
var error: NSError? = nil
if !context.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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
cell.textLabel!.text = object.valueForKey("timeStamp")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| mit | a7f44c3277b1dc69bca412d36dd63da1 | 45.881773 | 360 | 0.690554 | 6.22433 | false | false | false | false |
tsolomko/SWCompression | Sources/Common/CodingTree/DecodingTree.swift | 1 | 1401 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import BitByteData
final class DecodingTree {
private let bitReader: BitReader
private let tree: [Int]
private let leafCount: Int
init(codes: [Code], maxBits: Int, _ bitReader: BitReader) {
self.bitReader = bitReader
// Calculate maximum amount of leaves in a tree.
self.leafCount = 1 << (maxBits + 1)
var tree = Array(repeating: -1, count: leafCount)
for code in codes {
// Put code in its place in the tree.
var treeCode = code.code
var index = 0
for _ in 0..<code.bits {
let bit = treeCode & 1
index = bit == 0 ? 2 * index + 1 : 2 * index + 2
treeCode >>= 1
}
tree[index] = code.symbol
}
self.tree = tree
}
func findNextSymbol() -> Int {
var bitsLeft = bitReader.bitsLeft
var index = 0
while bitsLeft > 0 {
let bit = bitReader.bit()
index = bit == 0 ? 2 * index + 1 : 2 * index + 2
bitsLeft -= 1
guard index < self.leafCount
else { return -1 }
if self.tree[index] > -1 {
return self.tree[index]
}
}
return -1
}
}
| mit | 72c619e79307e9003cc03fe6dc674186 | 25.433962 | 64 | 0.513919 | 4.284404 | false | false | false | false |
AnneBlair/Aphrodite | Aphrodite/Regular.swift | 1 | 2332 | //
// Regular.swift
// Aphrodite
//
// Created by AnneBlair on 2017/9/9.
// Copyright © 2017年 blog.aiyinyu.com. All rights reserved.
//
import Foundation
public struct RegexHelper {
let regex: NSRegularExpression
init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern, options: .caseInsensitive)
}
func match(_ input: String) -> Bool {
let matches = regex.matches(in: input, options: [], range: NSMakeRange(0, input.utf16.count))
return matches.count > 0
}
}
precedencegroup MatchPrecedence {
associativity: none
higherThan: DefaultPrecedence
}
infix operator =~: MatchPrecedence
public func =~(object: String, template: String) -> Bool {
do {
return try RegexHelper(template).match(object)
} catch _ {
return false
}
}
/// 邮箱匹配
public let mail: String = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
/// 匹配用户名 字母或者数字组合 4到16位
public let Username: String = "^[a-z0-9_-]{4,16}$"
/// 匹配密码 字母加下划线,6到18位
public let Password: String = "^[a-z0-9_-]{6,18}$"
/// 匹配16进制
public let HexValue: String = "^#?([a-f0-9]{6}|[a-f0-9]{3})$"
///内容带分割符号 “Anne-Blair”
public let Slug: String = "^[a-z0-9-]+$"
/// 匹配 HTPPS URL
public let isURL: String = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
/// 匹配IP地址
public let IPAddress: String = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
/// 是HTML <center>内容<\center> 符合
public let HTMLTag: String = "^<([a-z]+)([^<]+)*(?:>(.*)<\\/\\1>|\\s+\\/>)$"
/// 日期(年-月-日)
public let isDate1: String = "(\\d{4}|\\d{2})-((1[0-2])|(0?[1-9]))-(([12][0-9])|(3[01])|(0?[1-9]))"
/// 日期(月/日/年)
public let isDate2: String = "((1[0-2])|(0?[1-9]))/(([12][0-9])|(3[01])|(0?[1-9]))/(\\d{4}|\\d{2})"
/// 是汉字
public let isChinese: String = "[\\u4e00-\\u9fa5]"
/// 中文及全角标点符号(字符)
public let ChineseParagraph: String = "[\\u3000-\\u301e\\ufe10-\\ufe19\\ufe30-\\ufe44\\ufe50-\\ufe6b\\uff01-\\uffee]"
/// 手机号 ps:因为大陆手机号分联通移动等等没法用一个表示出来
public let isPhoneNum: String = "^1[0-9]{10}$"
| mit | 5538e4bb44b7ebd1b878175058bfb3b7 | 25.135802 | 125 | 0.562589 | 2.652882 | false | false | false | false |
aliceatlas/daybreak | Classes/SBUpdater.swift | 1 | 5814 | /*
SBUpdater.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
class SBUpdater: NSObject {
static let sharedUpdater = SBUpdater()
var raiseResult = false
var checkSkipVersion = true
func check() {
NSThread.detachNewThreadSelector(#selector(checking), toTarget: self, withObject: nil)
}
func checking() {
let result = NSComparisonResult.OrderedSame;
let appVersionString = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String
let URL = NSURL(string: SBVersionFileURL)!
let request = NSURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: kSBTimeoutInterval)
var response: NSURLResponse?
let data = try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
let currentThread = NSThread.currentThread()
let threadDictionary = currentThread.threadDictionary
threadDictionary[kSBUpdaterResult] = result.rawValue
NSNotificationCenter.defaultCenter().addObserver(self, selector: "threadWillExit:", name: NSThreadWillExitNotification, object: currentThread)
if (data !! appVersionString) != nil {
// Success for networking
// Parse data
if let string = String(UTF8String: UnsafePointer<CChar>(data!.bytes))?.ifNotEmpty,
range0 = string.rangeOfString("version=\""),
range1 = string.rangeOfString("\";", range: range0.endIndex..<string.endIndex),
range2 = .Some(range0.endIndex..<range1.startIndex),
versionString = string[range2].ifNotEmpty {
let comparisonResult = appVersionString!.compareAsVersionString(versionString)
threadDictionary[kSBUpdaterResult] = comparisonResult.rawValue
threadDictionary[kSBUpdaterVersionString] = versionString
}
} else {
// Error
threadDictionary[kSBUpdaterErrorDescription] = NSLocalizedString("Could not check for updates.", comment: "")
}
}
func threadWillExit(notification: NSNotification) {
let currentThread = notification.object as! NSThread
let threadDictionary = currentThread.threadDictionary
let userInfo = threadDictionary.copy() as! [NSObject: AnyObject]
if let errorDescription = threadDictionary[kSBUpdaterErrorDescription] as? String {
if let result = NSComparisonResult(rawValue: userInfo[kSBUpdaterResult] as! Int) {
switch result {
case .OrderedAscending:
var shouldSkip = false
if checkSkipVersion {
let versionString = userInfo[kSBUpdaterVersionString] as! String
let skipVersion = NSUserDefaults.standardUserDefaults().stringForKey(kSBUpdaterSkipVersion)
shouldSkip = versionString == skipVersion
}
if !shouldSkip {
SBDispatch { self.postShouldUpdateNotification(userInfo) }
}
case .OrderedSame where raiseResult:
SBDispatch { self.postNotNeedUpdateNotification(userInfo) }
case .OrderedDescending where raiseResult:
// Error
threadDictionary[kSBUpdaterErrorDescription] = NSLocalizedString("Invalid version number.", comment: "")
SBDispatch { self.postDidFailCheckingNotification(userInfo) }
default:
break
}
}
} else if raiseResult {
SBDispatch { self.postDidFailCheckingNotification(userInfo) }
}
}
func postShouldUpdateNotification(userInfo: [NSObject: AnyObject]) {
NSNotificationCenter.defaultCenter().postNotificationName(SBUpdaterShouldUpdateNotification, object: self, userInfo: userInfo)
}
func postNotNeedUpdateNotification(userInfo: [NSObject: AnyObject]) {
NSNotificationCenter.defaultCenter().postNotificationName(SBUpdaterNotNeedUpdateNotification, object: self, userInfo: userInfo)
}
func postDidFailCheckingNotification(userInfo: [NSObject: AnyObject]) {
NSNotificationCenter.defaultCenter().postNotificationName(SBUpdaterDidFailCheckingNotification, object: self, userInfo: userInfo)
}
} | bsd-2-clause | daeedea704e66c8515315145341d563b | 49.565217 | 150 | 0.677159 | 5.866801 | false | false | false | false |
ChikabuZ/ViewControllerWithScrollViewAndKeyboard | ScrollableExample/ScrollableExample/ViewControllerWithScrollViewAndKeyboard.swift | 1 | 8475 | // Created by ChikabuZ on 09.06.16.
// Copyright © 2016 Buddy Healthcare Ltd Oy. All rights reserved.
import UIKit
class ViewControllerWithScrollViewAndKeyboard: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate
{
let BOTTOM_MARGIN: CGFloat = 10.0
var bottomMargin: CGFloat {
return BOTTOM_MARGIN
}
var bottomViewFrame: CGRect? {
return self.scrollView?.frame
}
var activeTextInputFrame: CGRect?
var scrollView: UIScrollView?
{
for subview in self.view.subviews
{
if let scrollView = subview as? UIScrollView {
return scrollView
}
}
return nil
}
var bottomBarHeight: CGFloat {
get {
if let rootViewControllerView = UIApplication.shared.windows.first?.rootViewController?.view, let scrollView = scrollView {
let newFrame = view.convert(scrollView.frame, to: rootViewControllerView)
let result = rootViewControllerView.frame.height - newFrame.height - newFrame.origin.y
return result
}
return 0
}
}
var originalContentOffsetY: CGFloat = 0
var originalContentInsetBottom: CGFloat = 0
var originalScrollIndicatorInsetsBottom: CGFloat = 0
var keyboardHeight: CGFloat = 0
var isKeyboardVisible: Bool = false
var textFields: [UITextField] = [UITextField]()
var textViews: [UITextView] = [UITextView]()
func bottomTextFieldReturnAction() {
}
//MARK: -
override func viewDidLoad()
{
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
tapGesture.cancelsTouchesInView = false
tapGesture.delegate = self
view.addGestureRecognizer(tapGesture)
originalContentInsetBottom = scrollView?.contentInset.bottom ?? 0
originalScrollIndicatorInsetsBottom = scrollView?.scrollIndicatorInsets.bottom ?? 0
textFields = findTextFields()
textViews = findTextViews()
setReturnKeys(inputs: textFields)
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
registerForKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated)
unregisterFromKeyboardNotifications()
}
//MARK: - Keyboard actions
fileprivate func registerForKeyboardNotifications()
{
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
fileprivate func unregisterFromKeyboardNotifications()
{
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc fileprivate func handleKeyboardNotification(_ notification: Notification) {
guard notification.name == NSNotification.Name.UIKeyboardWillShow || notification.name == NSNotification.Name.UIKeyboardWillHide else {
return
}
let userInfo = notification.userInfo
keyboardHeight = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height ?? 220
let animationOptionRawValue = userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? UInt ?? UIViewAnimationOptions().rawValue
let keyboardAnimationOption = UIViewAnimationOptions(rawValue: animationOptionRawValue)
let keyboardAnimationDuration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0.25
isKeyboardVisible = notification.name == NSNotification.Name.UIKeyboardWillShow
UIView.animate(withDuration: keyboardAnimationDuration, delay: 0, options: keyboardAnimationOption, animations: {
self.updateScrollViewContentSize()
self.scrollToActiveTextInput()
}) { (completed) in
self.updateScrollViewContentSize()
}
}
func scrollToActiveTextInput(animated: Bool = false) {
guard let scrollView = scrollView, let activeTextInputFrame = activeTextInputFrame else
{
print("activeTextInputFrame is nil"); return
}
if isKeyboardVisible {
// originalContentOffsetY = scrollView.contentOffset.y
let delta = activeTextInputFrame.origin.y + activeTextInputFrame.height + bottomMargin + keyboardHeight - bottomBarHeight - scrollView.frame.height
if delta > 0 {
scrollView.contentOffset.y = delta
}
} else {
// scrollView.contentOffset.y = originalContentOffsetY
}
}
func updateScrollViewContentSize() {
guard let scrollView = scrollView, let bottomViewFrame = bottomViewFrame else {
print("scrollView not found")
return
}
if isKeyboardVisible {
let delta = bottomViewFrame.origin.y + bottomViewFrame.height + keyboardHeight - bottomBarHeight + bottomMargin - scrollView.contentSize.height
scrollView.contentInset.bottom = delta
scrollView.scrollIndicatorInsets.bottom = keyboardHeight - bottomBarHeight
} else {
scrollView.contentInset.bottom = originalContentInsetBottom
scrollView.scrollIndicatorInsets.bottom = originalScrollIndicatorInsetsBottom
}
}
@objc func hideKeyboard() {
view.endEditing(true)
}
//MARK: - UITextFieldDelegate
func textFieldDidBeginEditing(_ textField: UITextField) {
activeTextInputFrame = textField.frame
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let currentIndex = textFields.index(of: textField) {
if currentIndex + 1 < textFields.count {
let newTextField = textFields[currentIndex + 1]
newTextField.becomeFirstResponder()
// textFieldDidBeginEditing(newTextField)
} else {
bottomTextFieldReturnAction()
}
}
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
// Workaround for the jumping text bug
textField.resignFirstResponder()
textField.layoutIfNeeded()
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view is UIButton {
return false
}
if touch.view is UIStackView {
return false
}
return true
}
}
private extension ViewControllerWithScrollViewAndKeyboard {
func findTextFields() -> [UITextField] {
if let scrollV = scrollView {
let container = scrollV.subviews[0]
var inputs = [UITextField]()
for view in container.subviews {
if view is UITextField {
inputs.append(view as! UITextField)
}
}
return inputs
}
return [UITextField]()
}
func findTextViews() -> [UITextView] {
if let scrollV = scrollView {
let container = scrollV.subviews[0]
var inputs = [UITextView]()
for view in container.subviews {
if view is UITextView {
inputs.append(view as! UITextView)
}
}
return inputs
}
return [UITextView]()
}
func setReturnKeys(inputs: [UITextField]) {
for (index, textField) in textFields.enumerated() {
if index == textFields.count - 1 {
textField.returnKeyType = .done
} else {
textField.returnKeyType = .next
}
}
}
}
| mit | ed785e8d7c4628e3f7c0ad37a0b7e040 | 33.169355 | 164 | 0.619424 | 6.226304 | false | false | false | false |
rockgarden/swift_language | privacy/privacy/Dog.swift | 1 | 546 | import UIKit
class Dog {
var name = ""
private var whatADogSays = "woof"
func bark() {
print(self.whatADogSays)
}
func nameCat(cat:Cat) {
cat.secretName = "Lazybones" // legal: same file
let k = Kangaroo()
_ = k
}
func nameCat2(cat:Cat2) {
// cat.secretName = "Lazybones" // illegal: different file
}
}
class Cat {
fileprivate var secretName : String?
private(set) var color : UIColor?
fileprivate(set) var length : Double?
}
private class Kangaroo {
}
| mit | 288ae39d4717d3b766cebbfaa907b43c | 18.5 | 66 | 0.584249 | 3.477707 | false | false | false | false |
joshc89/DeclarativeLayout | DeclarativeLayout/Collections/Collections/CollectionManager.swift | 1 | 3483 | //
// CollectionManager.swift
// DeclarativeLayout
//
// Created by Joshua Campion on 19/09/2016.
// Copyright © 2016 Josh Campion. All rights reserved.
//
import UIKit
/**
Common `UICollectionViewDataSource` that implements common methods using a generic `CollectionModel`. Typical use is to subclass this, providing explicit cell creation.
Methods implemented are:
- `numberOfSection(in:)`
- `collectionView(_:numberOfItemsInSection:)`
`collectionView(_:cellForItemAt:)` is implemented to return a new `UICollectionViewCell`. Subclasses should override this to return the configured cell for their object. Ensure this cell is registered programmatically in `init()` if the `collectionView` hasn't been created from a Storyboard.
*/
open class CollectionManager<CollectionType: CollectionModel>: NSObject, UICollectionViewDataSource {
/// The `UICollectionView` this object is managing. The intention is one table view per manager, hence `let`
public let collectionView: UICollectionView
/// It is recommended that only subclasses set this variable. Use `update(to:animated)` to provide new data instead.
open var collection: CollectionType
/**
Default initialiser, assigns `self` as the data source for this `UICollectionView`.
- note: Animation is supported only using a `DifferentiableCollectionManager`.
- parameter collectionView: The `UICollectionView` to manage.
- parameter collection: The initial data for this table. This can be updated subsequently using `update(to:animated:)`.
*/
public init(collectionView: UICollectionView, collection: CollectionType) {
self.collectionView = collectionView
self.collection = collection
super.init()
collectionView.dataSource = self
}
/**
Recommended method for updating the data in the table.
- note: This class does not perform the update with animation. Use `DifferentiableCollectionManager` instead.
- parameter to: A new version of the data to show.
- parameter animated: Flag unused in this class. See `DifferentiableCollectionManager` instead.
*/
open func update(to: CollectionType, animated: Bool) {
self.collection = to
collectionView.reloadData()
}
// MARK: Data Source
/**
`UICollectionViewDataSource` conformance.
- returns: The `numberOfSections()` of `collection`.
*/
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return collection.numberOfSections()
}
/**
`UICollectionViewDataSource` conformance.
- returns: The `numberOfItems(in:) collection`.
*/
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collection.numberOfItems(in: section)
}
/**
`UICollectionViewDataSource` conformance. Subclasses should override this method to provide a custom cell, typically populated using `collection.item(at:)`.
*/
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath)
return cell
}
}
| mit | c3a731a6bb447091609501b4b8a4bc0a | 32.161905 | 293 | 0.684951 | 5.708197 | false | false | false | false |
epiphany27/SwiftHN | SwiftHN/ViewControllers/DetailViewController.swift | 5 | 5095 | //
// DetailViewController.swift
// SwiftHN
//
// Created by Thomas Ricouard on 11/06/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import UIKit
import SwiftHNShared
import HackerSwifter
class DetailViewController: HNTableViewController, NewsCellDelegate {
var post: Post!
var cellHeightCache: [CGFloat] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "HN:Post"
self.setupBarButtonItems()
self.onPullToFresh()
}
func onPullToFresh() {
Comment.fetch(forPost: self.post, completion: {(comments: [Comment]!, error: Fetcher.ResponseError!, local: Bool) in
if let realDatasource = comments {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, UInt(0)), { ()->() in
self.cacheHeight(realDatasource)
dispatch_async(dispatch_get_main_queue(), { ()->() in
self.datasource = realDatasource
})
})
}
if (!local) {
self.refreshing = false
}
})
}
func cacheHeight(comments: NSArray) {
cellHeightCache = []
for comment : AnyObject in comments {
if let realComment = comment as? Comment {
var height = CommentsCell.heightForText(realComment.text!, bounds: self.tableView.bounds, level: realComment.depth)
cellHeightCache.append(height)
}
}
}
func setupBarButtonItems() {
var shareItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: "onShareButton")
self.navigationItem.rightBarButtonItem = shareItem
}
func onShareButton() {
Helper.showShareSheet(self.post, controller: self, barbutton: self.navigationItem.rightBarButtonItem)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
if (indexPath.section == 0) {
var title: NSString = self.post.title!
return NewsCell.heightForText(title, bounds: self.tableView.bounds)
}
return self.cellHeightCache[indexPath.row] as CGFloat
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1
}
if (self.datasource != nil) {
return self.datasource.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
var cell = tableView.dequeueReusableCellWithIdentifier(NewsCellsId) as? NewsCell
cell!.post = self.post
cell!.cellDelegate = self;
return cell!
}
var cell = tableView.dequeueReusableCellWithIdentifier(CommentsCellId) as! CommentsCell!
var comment = self.datasource[indexPath.row] as! Comment
cell.comment = comment
return cell
}
//MARK: NewsCellDelegate
func newsCellDidSelectButton(cell: NewsCell, actionType: Int, post: Post) {
if (actionType == NewsCellActionType.Username.rawValue) {
if let realUsername = post.username {
var detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("UserViewController") as! UserViewController
detailVC.user = realUsername
self.showDetailViewController(detailVC, sender: self)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "toWebview") {
var destination = segue.destinationViewController as! WebviewController
destination.post = self.post
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ (context: UIViewControllerTransitionCoordinatorContext!) -> Void in
//Nothing to do here, I just want to be noticed when the transition is done.
//It's actuallu quite nice to have the final size of size of the current layout,
//Event if it's useless in our case.
}, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, UInt(0)), { ()->() in
self.cacheHeight(self.datasource)
dispatch_async(dispatch_get_main_queue(), { ()->() in
self.tableView.reloadData()
})
})
})
}
}
| gpl-2.0 | f17146f3c6e708c428838157f8ea5926 | 35.92029 | 136 | 0.607066 | 5.351891 | false | false | false | false |
maicki/AsyncDisplayKit | examples_extra/ASLayoutSpecPlayground-Swift/Sample/Sample.playground/Pages/PhotoWithOutsetIconOverlay.xcplaygroundpage/Contents.swift | 15 | 852 | //: [Photo With Inset Text Overlay](PhotoWithInsetTextOverlay)
import AsyncDisplayKit
extension PhotoWithOutsetIconOverlay {
override public func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let iconWidth: CGFloat = 40
let iconHeight: CGFloat = 40
iconNode.style.preferredSize = CGSize(width: iconWidth, height: iconWidth)
photoNode.style.preferredSize = CGSize(width: 150, height: 150)
let x: CGFloat = 150
let y: CGFloat = 0
iconNode.style.layoutPosition = CGPoint(x: x, y: y)
photoNode.style.layoutPosition = CGPoint(x: iconWidth * 0.5, y: iconHeight * 0.5);
let absoluteLayoutSpec = ASAbsoluteLayoutSpec(children: [photoNode, iconNode])
return absoluteLayoutSpec;
}
}
PhotoWithOutsetIconOverlay().show()
//: [Horizontal Stack With Spacer](HorizontalStackWithSpacer)
| bsd-3-clause | db9baaf3b55aba02ae1b5c8aecae7124 | 29.428571 | 91 | 0.737089 | 4.281407 | false | false | false | false |
hilen/TSWeChat | TSWeChat/General/TSGlobalHelper.swift | 1 | 1432 | //
// TSGlobalHelper.swift
// TSWeChat
//
// Created by Hilen on 3/2/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
// stolen from Kingfisher: https://github.com/onevcat/Kingfisher/blob/master/Sources/ThreadHelper.swift
func dispatch_async_safely_to_main_queue(_ block: @escaping ()->()) {
dispatch_async_safely_to_queue(DispatchQueue.main, block)
}
// This methd will dispatch the `block` to a specified `queue`.
// If the `queue` is the main queue, and current thread is main thread, the block
// will be invoked immediately instead of being dispatched.
func dispatch_async_safely_to_queue(_ queue: DispatchQueue, _ block: @escaping ()->()) {
if queue === DispatchQueue.main && Thread.isMainThread {
block()
} else {
queue.async {
block()
}
}
}
func TSAlertView_show(_ title: String, message: String? = nil) {
var theMessage = ""
if message != nil {
theMessage = message!
}
let alertView = UIAlertView(title: title , message: theMessage, delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "好的")
alertView.show()
}
/// Print log
func printLog<T>(_ message: T,
file: String = #file,
method: String = #function,
line: Int = #line)
{
#if DEBUG
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
#endif
}
| mit | dacd0836adda87ef52a4d9d09eef5f6a | 25.849057 | 132 | 0.631061 | 3.92011 | false | false | false | false |
nifty-swift/Nifty | Sources/eq.swift | 2 | 2204 | /**************************************************************************************************
* eq.swift
*
* This file defines functionality for determining floating-point relative accuracy.
*
* Author: Nicolas Bertagnolli
* Creation Date: 21 Feb 2017
*
* 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.
*
* Copyright 2017 Nicolas Bertagnolli
**************************************************************************************************/
/// Compute elementwise equality of two matrices
///
/// - Parameters:
/// - A: first Matrix
/// - B: second Matrix
/// - Returns: A Matrix where the i, j element is 1 if A[i,j] = B[i, j] and 0 otherwise
func eq(_ A: Matrix<Double>, _ B: Matrix<Double>, within tol: Double=0.0000001) -> Matrix<Double> {
precondition(A.size == B.size, "Matrices must be the same shape")
var result = zeros(A.size[0], A.size[1])
for i in 0..<A.size[0] {
for j in 0..<A.size[1] {
if A[i, j] > B[i, j] - tol && A[i, j] < B[i, j] + tol {
result[i, j] = 1.0
}
}
}
return result
}
/// Compute elementwise equality of two vectors
///
/// - Parameters:
/// - a: first Vector
/// - b: second Vector
/// - Returns: A Vector where the ith element is 1 if a[i] = b[i] and 0 otherwise
func eq(_ a: Vector<Double>, _ b: Vector<Double>, within tol: Double=0.0000001) -> Vector<Double> {
precondition(a.count == b.count, "Vectors must be the same shape")
var result = Vector(a.count, value: 0.0)
for i in 0..<a.count {
if a[i] > b[i] - tol && a[i] < b[i] + tol {
result[i] = 1.0
}
}
return result
}
| apache-2.0 | 2d46b06ed7d653656f602c82e481c000 | 34.548387 | 100 | 0.557623 | 3.748299 | false | false | false | false |
taketo1024/SwiftyAlgebra | Sources/SwmCore/Numbers/F2.swift | 1 | 1758 | //
// F2.swift
// SwiftyMath
//
// Created by Taketo Sano on 2019/10/30.
//
public struct 𝐅₂: Field, FiniteSet, Hashable, ExpressibleByIntegerLiteral {
public let representative: UInt8
@inlinable
public init(_ a: UInt8) {
assert(a == 0 || a == 1)
representative = a
}
@inlinable
public init(_ a: 𝐙) {
self.init(a.isEven ? UInt8(0) : UInt8(1))
}
@inlinable
public init(from a: 𝐙) {
self.init(a)
}
@inlinable
public init(integerLiteral value: UInt8) {
self.init((value % 2 == 0) ? 0 : 1)
}
@inlinable
public var inverse: Self? {
isZero ? nil : self
}
@inlinable
public static func +(a: Self, b: Self) -> Self {
.init(a.representative ^ b.representative)
}
@inlinable
public prefix static func -(a: Self) -> Self {
a
}
@inlinable
public static func -(a: Self, b: Self) -> Self {
a + b
}
@inlinable
public static func *(a: Self, b: Self) -> Self {
.init(a.representative & b.representative)
}
@inlinable
public static func sum<S: Sequence>(_ elements: S) -> Self where S.Element == Self {
elements.count { $0.representative == 1 }.isEven ? .zero : .identity
}
public static var allElements: [𝐅₂] {
[.zero, .identity]
}
public static var countElements: Int {
2
}
public var description: String {
representative.description
}
public static var symbol: String {
"𝐅₂"
}
}
extension 𝐅₂: Randomable {
public static func random() -> 𝐅₂ {
.init(Bool.random() ? 0 : 1)
}
}
| cc0-1.0 | 783c30634cc156b154a41c359bde2c0d | 19.807229 | 88 | 0.53619 | 3.721983 | false | false | false | false |
nextcloud/ios | iOSClient/Main/Create cloud/NCCreateMenuAdd.swift | 1 | 9697 | //
// NCCreateMenuAdd.swift
// Nextcloud
//
// Created by Marino Faggiana on 14/11/2018.
// Copyright © 2018 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// 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 Sheeeeeeeeet
class NCCreateMenuAdd: NSObject {
weak var appDelegate = UIApplication.shared.delegate as! AppDelegate
var isNextcloudTextAvailable = false
@objc init(viewController: UIViewController, view: UIView) {
super.init()
if self.appDelegate.reachability.isReachable() && NCBrandBeta.shared.directEditing && NCManageDatabase.sharedInstance.getDirectEditingCreators(account: self.appDelegate.activeAccount) != nil {
isNextcloudTextAvailable = true
}
var items = [MenuItem]()
ActionSheetTableView.appearance().backgroundColor = NCBrandColor.sharedInstance.backgroundForm
ActionSheetTableView.appearance().separatorColor = NCBrandColor.sharedInstance.separator
ActionSheetItemCell.appearance().backgroundColor = NCBrandColor.sharedInstance.backgroundForm
ActionSheetItemCell.appearance().titleColor = NCBrandColor.sharedInstance.textView
items.append(MenuItem(title: NSLocalizedString("_upload_photos_videos_", comment: ""), value: 10, image: CCGraphics.changeThemingColorImage(UIImage(named: "file_photo"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
items.append(MenuItem(title: NSLocalizedString("_upload_file_", comment: ""), value: 20, image: CCGraphics.changeThemingColorImage(UIImage(named: "file"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
if NCBrandOptions.sharedInstance.use_imi_viewer {
items.append(MenuItem(title: NSLocalizedString("_im_create_new_file", tableName: "IMLocalizable", bundle: Bundle.main, value: "", comment: ""), value: 21, image: CCGraphics.scale(UIImage(named: "imagemeter"), to: CGSize(width: 25, height: 25), isAspectRation: true)))
}
if isNextcloudTextAvailable {
items.append(MenuItem(title: NSLocalizedString("_create_nextcloudtext_document_", comment: ""), value: 31, image: CCGraphics.changeThemingColorImage(UIImage(named: "file_txt"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
} else {
items.append(MenuItem(title: NSLocalizedString("_upload_file_text_", comment: ""), value: 30, image: CCGraphics.changeThemingColorImage(UIImage(named: "file_txt"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
}
#if !targetEnvironment(simulator)
if #available(iOS 11.0, *) {
items.append(MenuItem(title: NSLocalizedString("_scans_document_", comment: ""), value: 40, image: CCGraphics.changeThemingColorImage(UIImage(named: "scan"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
}
#endif
items.append(MenuItem(title: NSLocalizedString("_create_voice_memo_", comment: ""), value: 50, image: CCGraphics.changeThemingColorImage(UIImage(named: "microphone"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon)))
items.append(MenuItem(title: NSLocalizedString("_create_folder_", comment: ""), value: 60, image: CCGraphics.changeThemingColorImage(UIImage(named: "folder"), width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement)))
if let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getRichdocumentsMimetypes(account: appDelegate.activeAccount) {
if richdocumentsMimetypes.count > 0 {
items.append(MenuItem(title: NSLocalizedString("_create_new_document_", comment: ""), value: 70, image: UIImage(named: "create_file_document")))
items.append(MenuItem(title: NSLocalizedString("_create_new_spreadsheet_", comment: ""), value: 80, image: UIImage(named: "create_file_xls")))
items.append(MenuItem(title: NSLocalizedString("_create_new_presentation_", comment: ""), value: 90, image: UIImage(named: "create_file_ppt")))
}
}
items.append(CancelButton(title: NSLocalizedString("_cancel_", comment: "")))
let actionSheet = ActionSheet(menu: Menu(items: items), action: { _, item in
if item.value as? Int == 10 { self.appDelegate.activeMain.openAssetsPickerController() }
if item.value as? Int == 20 { self.appDelegate.activeMain.openImportDocumentPicker() }
if item.value as? Int == 21 {
_ = IMCreate(serverUrl: self.appDelegate.activeMain.serverUrl)
}
if item.value as? Int == 30 {
let storyboard = UIStoryboard(name: "NCText", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "NCText")
controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
self.appDelegate.activeMain.present(controller, animated: true, completion: nil)
}
if item.value as? Int == 31 {
guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
return
}
navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
viewController.typeTemplate = k_template_document
viewController.serverUrl = self.appDelegate.activeMain.serverUrl
viewController.titleForm = NSLocalizedString("_create_nextcloudtext_document_", comment: "")
self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
}
if item.value as? Int == 40 {
if #available(iOS 11.0, *) {
NCCreateScanDocument.sharedInstance.openScannerDocument(viewController: self.appDelegate.activeMain)
}
}
if item.value as? Int == 50 { NCMainCommon.sharedInstance.startAudioRecorder() }
if item.value as? Int == 60 { self.appDelegate.activeMain.createFolder() }
if item.value as? Int == 70 {
guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
return
}
navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
viewController.typeTemplate = k_template_document
viewController.serverUrl = self.appDelegate.activeMain.serverUrl
viewController.titleForm = NSLocalizedString("_create_new_document_", comment: "")
self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
}
if item.value as? Int == 80 {
guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
return
}
navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
viewController.typeTemplate = k_template_spreadsheet
viewController.serverUrl = self.appDelegate.activeMain.serverUrl
viewController.titleForm = NSLocalizedString("_create_new_spreadsheet_", comment: "")
self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
}
if item.value as? Int == 90 {
guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController() else {
return
}
navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
viewController.typeTemplate = k_template_presentation
viewController.serverUrl = self.appDelegate.activeMain.serverUrl
viewController.titleForm = NSLocalizedString("_create_new_presentation_", comment: "")
self.appDelegate.window.rootViewController?.present(navigationController, animated: true, completion: nil)
}
if item is CancelButton { print("Cancel buttons has the value `true`") }
})
actionSheet.present(in: viewController, from: view)
}
}
| gpl-3.0 | bcaf441f0e427f050a10c053a0d73384 | 58.851852 | 279 | 0.686159 | 5.272431 | false | false | false | false |
mentrena/SyncKit | SyncKit/Classes/QSSynchronizer/CloudKitSynchronizer.swift | 1 | 13768 | //
// CloudKitSynchronizer.swift
// Pods
//
// Created by Manuel Entrena on 05/04/2019.
//
import Foundation
import CloudKit
// For Swift
public extension Notification.Name {
/// Sent when the synchronizer is going to start a sync with CloudKit.
static let SynchronizerWillSynchronize = Notification.Name("QSCloudKitSynchronizerWillSynchronizeNotification")
/// Sent when the synchronizer is going to start the fetch stage, where it downloads any new changes from CloudKit.
static let SynchronizerWillFetchChanges = Notification.Name("QSCloudKitSynchronizerWillFetchChangesNotification")
/// Sent when the synchronizer is going to start the upload stage, where it sends changes to CloudKit.
static let SynchronizerWillUploadChanges = Notification.Name("QSCloudKitSynchronizerWillUploadChangesNotification")
/// Sent when the synchronizer finishes syncing.
static let SynchronizerDidSynchronize = Notification.Name("QSCloudKitSynchronizerDidSynchronizeNotification")
/// Sent when the synchronizer encounters an error while syncing.
static let SynchronizerDidFailToSynchronize = Notification.Name("QSCloudKitSynchronizerDidFailToSynchronizeNotification")
}
// For Obj-C
@objc public extension NSNotification {
/// Sent when the synchronizer is going to start a sync with CloudKit.
static let CloudKitSynchronizerWillSynchronizeNotification: NSString = "QSCloudKitSynchronizerWillSynchronizeNotification"
/// Sent when the synchronizer is going to start the fetch stage, where it downloads any new changes from CloudKit.
static let CloudKitSynchronizerWillFetchChangesNotification: NSString = "QSCloudKitSynchronizerWillFetchChangesNotification"
/// Sent when the synchronizer is going to start the upload stage, where it sends changes to CloudKit.
static let CloudKitSynchronizerWillUploadChangesNotification: NSString = "QSCloudKitSynchronizerWillUploadChangesNotification"
/// Sent when the synchronizer finishes syncing.
static let CloudKitSynchronizerDidSynchronizeNotification: NSString = "QSCloudKitSynchronizerDidSynchronizeNotification"
/// Sent when the synchronizer encounters an error while syncing.
static let CloudKitSynchronizerDidFailToSynchronizeNotification: NSString = "QSCloudKitSynchronizerDidFailToSynchronizeNotification"
}
/// An `AdapterProvider` gets requested for new model adapters when a `CloudKitSynchronizer` encounters a new `CKRecordZone` that does not already correspond to an existing model adapter.
@objc public protocol AdapterProvider {
/// The `CloudKitSynchronizer` requests a new model adapter for the given record zone.
/// - Parameters:
/// - synchronizer: `QSCloudKitSynchronizer` asking for the adapter.
/// - zoneID: `CKRecordZoneID` that the model adapter will be used for.
/// - Returns: `ModelAdapter` correctly configured to sync changes in the given record zone.
func cloudKitSynchronizer(_ synchronizer: CloudKitSynchronizer, modelAdapterForRecordZoneID zoneID: CKRecordZone.ID) -> ModelAdapter?
/// The `CloudKitSynchronizer` informs the provider that a record zone was deleted so it can clean up any associated data.
/// - Parameters:
/// - synchronizer: `QSCloudKitSynchronizer` that found the deleted record zone.
/// - zoneID: `CKRecordZoneID` of the record zone that was deleted.
func cloudKitSynchronizer(_ synchronizer: CloudKitSynchronizer, zoneWasDeletedWithZoneID zoneID: CKRecordZone.ID)
}
@objc public protocol CloudKitSynchronizerDelegate: AnyObject {
func synchronizerWillStartSyncing(_ synchronizer: CloudKitSynchronizer)
func synchronizerWillCheckForChanges(_ synchronizer: CloudKitSynchronizer)
func synchronizerWillFetchChanges(_ synchronizer: CloudKitSynchronizer, in recordZone: CKRecordZone.ID)
func synchronizerDidFetchChanges(_ synchronizer: CloudKitSynchronizer, in recordZone: CKRecordZone.ID)
func synchronizerWillUploadChanges(_ synchronizer: CloudKitSynchronizer, to recordZone: CKRecordZone.ID)
func synchronizerDidSync(_ synchronizer: CloudKitSynchronizer)
func synchronizerDidfailToSync(_ synchronizer: CloudKitSynchronizer, error: Error)
func synchronizer(_ synchronizer: CloudKitSynchronizer, didAddAdapter adapter: ModelAdapter, forRecordZoneID zoneID: CKRecordZone.ID)
func synchronizer(_ synchronizer: CloudKitSynchronizer, zoneIDWasDeleted zoneID: CKRecordZone.ID)
}
/**
A `CloudKitSynchronizer` object takes care of making all the required calls to CloudKit to keep your model synchronized, using the provided
`ModelAdapter` to interact with it.
`CloudKitSynchronizer` will post notifications at different steps of the synchronization process.
*/
public class CloudKitSynchronizer: NSObject {
/// SyncError
@objc public enum SyncError: Int, Error {
/**
* Received when synchronize is called while there was an ongoing synchronization.
*/
case alreadySyncing = 0
/**
* A synchronizer with a higer `compatibilityVersion` value uploaded changes to CloudKit, so those changes won't be imported here.
* This error can be detected to prompt the user to update the app to a newer version.
*/
case higherModelVersionFound = 1
/**
* A record fot the provided object was not found, so the object cannot be shared on CloudKit.
*/
case recordNotFound = 2
/**
* Synchronization was manually cancelled.
*/
case cancelled = 3
}
/// `CloudKitSynchronizer` can be configured to only download changes, never uploading local changes to CloudKit.
@objc public enum SynchronizeMode: Int {
/// Download and upload all changes
case sync
/// Only download changes
case downloadOnly
}
public static let errorDomain = "CloudKitSynchronizerErrorDomain"
public static let errorKey = "CloudKitSynchronizerErrorKey"
/**
More than one `CloudKitSynchronizer` may be created in an app.
The identifier is used to persist some state, so it should always be the same for a synchronizer –if you change your app to use a different identifier state might be lost.
*/
@objc public let identifier: String
/// iCloud container identifier.
@objc public let containerIdentifier: String
/// Adapter wrapping a `CKDatabase`. The synchronizer will run CloudKit operations on the given database.
public let database: CloudKitDatabaseAdapter
/// Provides the model adapter to the synchronizer.
@objc public let adapterProvider: AdapterProvider
/// Required by the synchronizer to persist some state. `UserDefaults` can be used via `UserDefaultsAdapter`.
public let keyValueStore: KeyValueStore
/// Indicates whether the instance is currently synchronizing data.
@objc public internal(set) var syncing: Bool = false
/// Number of records that are sent in an upload operation.
@objc public var batchSize: Int = CloudKitSynchronizer.defaultBatchSize
/**
* When set, if the synchronizer finds records uploaded by a different device using a higher compatibility version,
* it will end synchronization with a `higherModelVersionFound` error.
*/
@objc public var compatibilityVersion: Int = 0
/// Whether the synchronizer will only download data or also upload any local changes.
@objc public var syncMode: SynchronizeMode = .sync
@objc public var delegate: CloudKitSynchronizerDelegate?
internal let dispatchQueue = DispatchQueue(label: "QSCloudKitSynchronizer")
internal let operationQueue = OperationQueue()
internal var modelAdapterDictionary = [CKRecordZone.ID: ModelAdapter]()
internal var serverChangeToken: CKServerChangeToken?
internal var activeZoneTokens = [CKRecordZone.ID: CKServerChangeToken]()
internal var cancelSync = false
internal var completion: ((Error?) -> ())?
internal weak var currentOperation: Operation?
internal var uploadRetries = 0
internal var didNotifyUpload = Set<CKRecordZone.ID>()
/// Default number of records to send in an upload operation.
@objc public static var defaultBatchSize = 200
static let deviceUUIDKey = "QSCloudKitDeviceUUIDKey"
static let modelCompatibilityVersionKey = "QSCloudKitModelCompatibilityVersionKey"
/// Initializes a newly allocated synchronizer.
/// - Parameters:
/// - identifier: Identifier for the `QSCloudKitSynchronizer`.
/// - containerIdentifier: Identifier of the iCloud container to be used. The application must have the right entitlements to be able to access this container.
/// - database: Private or Shared CloudKit Database
/// - adapterProvider: `CloudKitSynchronizerAdapterProvider`
/// - keyValueStore: Object conforming to KeyValueStore (`UserDefaultsAdapter`, for example)
/// - Returns: Initialized synchronizer or `nil` if no iCloud container can be found with the provided identifier.
@objc public init(identifier: String, containerIdentifier: String, database: CloudKitDatabaseAdapter, adapterProvider: AdapterProvider, keyValueStore: KeyValueStore = UserDefaultsAdapter(userDefaults: UserDefaults.standard)) {
self.identifier = identifier
self.containerIdentifier = containerIdentifier
self.adapterProvider = adapterProvider
self.database = database
self.keyValueStore = keyValueStore
super.init()
BackupDetection.runBackupDetection { (result, error) in
if result == .restoredFromBackup {
self.clearDeviceIdentifier()
}
}
}
fileprivate var _deviceIdentifier: String!
var deviceIdentifier: String {
if _deviceIdentifier == nil {
_deviceIdentifier = deviceUUID
if _deviceIdentifier == nil {
_deviceIdentifier = UUID().uuidString
deviceUUID = _deviceIdentifier
}
}
return _deviceIdentifier
}
func clearDeviceIdentifier() {
deviceUUID = nil
}
// MARK: - Public
/// These keys will be added to CKRecords uploaded to CloudKit and are used by SyncKit internally.
public static let metadataKeys: [String] = [CloudKitSynchronizer.deviceUUIDKey, CloudKitSynchronizer.modelCompatibilityVersionKey]
/// Synchronize data with CloudKit.
/// - Parameter completion: Completion block that receives an optional error. Could be a `SyncError`, `CKError`, or any other error found during synchronization.
@objc public func synchronize(completion: ((Error?) -> ())?) {
guard !syncing else {
completion?(SyncError.alreadySyncing)
return
}
debugPrint("CloudKitSynchronizer >> Initiating synchronization")
cancelSync = false
syncing = true
self.completion = completion
performSynchronization()
}
/// Cancel synchronization. It will cause a current synchronization to end with a `cancelled` error.
@objc public func cancelSynchronization() {
guard syncing, !cancelSync else { return }
cancelSync = true
currentOperation?.cancel()
}
/**
* Deletes saved database token, so next synchronization will include changes in all record zones in the database.
* This does not reset tokens stored by model adapters.
*/
@objc public func resetDatabaseToken() {
storedDatabaseToken = nil
}
/**
* Deletes saved database token and all local metadata used to track changes in models.
* The synchronizer should not be used after calling this function, create a new synchronizer instead if you need it.
*/
@objc public func eraseLocalMetadata() {
cancelSynchronization()
dispatchQueue.async {
self.storedDatabaseToken = nil
self.clearAllStoredSubscriptionIDs()
self.deviceUUID = nil
self.modelAdapters.forEach {
$0.deleteChangeTracking()
self.removeModelAdapter($0)
}
}
}
/// Deletes the corresponding record zone on CloudKit, along with any data in it.
/// - Parameters:
/// - adapter: Model adapter whose corresponding record zone should be deleted
/// - completion: Completion block.
@objc public func deleteRecordZone(for adapter: ModelAdapter, completion: ((Error?)->())?) {
database.delete(withRecordZoneID: adapter.recordZoneID) { (zoneID, error) in
if let error = error {
debugPrint("CloudKitSynchronizer >> Error: \(error)")
} else {
debugPrint("CloudKitSynchronizer >> Deleted zone: \(zoneID?.debugDescription ?? "")")
}
completion?(error)
}
}
/// Model adapters in use by this synchronizer
@objc public var modelAdapters: [ModelAdapter] {
return Array(modelAdapterDictionary.values)
}
/// Adds a new model adapter to be synchronized with CloudKit.
/// - Parameter adapter: The adapter to be managed by this synchronizer.
@objc public func addModelAdapter(_ adapter: ModelAdapter) {
modelAdapterDictionary[adapter.recordZoneID] = adapter
}
/// Removes the model adapter so data managed by it won't be synced with CloudKit any more.
/// - Parameter adapter: Adapter to be removed from the synchronizer
@objc public func removeModelAdapter(_ adapter: ModelAdapter) {
modelAdapterDictionary.removeValue(forKey: adapter.recordZoneID)
}
}
| mit | e189496be939cd8ab9fd72b277beaf94 | 46.798611 | 230 | 0.715023 | 5.651067 | false | false | false | false |
davbeck/ImageIOSwift | Sources/ImageIOSwift/CGSize+Helpers.swift | 1 | 977 | import CoreGraphics
extension CGSize {
func scaled(toFit innerRect: CGSize) -> CGSize {
let outerRect = self
// the width and height ratios of the rects
let wRatio = outerRect.width / innerRect.width
let hRatio = outerRect.height / innerRect.height
// calculate scaling ratio based on the smallest ratio.
let ratio = (wRatio > hRatio) ? wRatio : hRatio
// aspect fitted origin and size
return CGSize(
width: outerRect.width / ratio,
height: outerRect.height / ratio
)
}
func scaled(toFill innerRect: CGSize) -> CGSize {
let outerRect = self
// the width and height ratios of the rects
let wRatio = outerRect.width / innerRect.width
let hRatio = outerRect.height / innerRect.height
// calculate scaling ratio based on the smallest ratio.
let ratio = (wRatio < hRatio) ? wRatio : hRatio
// aspect fitted origin and size
return CGSize(
width: outerRect.width / ratio,
height: outerRect.height / ratio
)
}
}
| mit | ed093043f76ca8e145eaf9e170e1ebff | 25.405405 | 57 | 0.698055 | 3.876984 | false | false | false | false |
CombineCommunity/CombineExt | Sources/Operators/Materialize.swift | 1 | 4601 | //
// Materialize.swift
// CombineExt
//
// Created by Shai Mishali on 14/03/2020.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if canImport(Combine)
import Combine
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publisher {
/// Converts any publisher to a publisher of its events
///
/// - note: The returned publisher is guaranteed to never fail,
/// but it will complete given any upstream completion event
///
/// - returns: A publisher that wraps events in an `Event<Output, Failure>`.
func materialize() -> Publishers.Materialize<Self> {
return Publishers.Materialize(upstream: self)
}
}
// MARK: - Materialized Operators
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publisher where Output: EventConvertible, Failure == Never {
/// Given a materialized publisher, publish only the emitted
/// upstream values, omitting failures
///
/// - returns: A publisher emitting the `Output` of the wrapped event
func values() -> AnyPublisher<Output.Output, Never> {
compactMap {
guard case .value(let value) = $0.event else { return nil }
return value
}
.eraseToAnyPublisher()
}
/// Given a materialize publisher, publish only the emitted
/// upstream failure, if exists, omitting values
///
/// - returns: A publisher emitting the `Failure` of the wrapped event
func failures() -> AnyPublisher<Output.Failure, Never> {
compactMap {
guard case .failure(let error) = $0.event else { return nil }
return error
}
.eraseToAnyPublisher()
}
}
// MARK: - Publisher
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publishers {
/// A publisher which takes an upstream publisher and emits its events,
/// wrapped in `Event<Output, Failure>`
///
/// - note: This publisher is guaranteed to never fail, but it
/// will complete given any upstream completion event
struct Materialize<Upstream: Publisher>: Publisher {
public typealias Output = Event<Upstream.Output, Upstream.Failure>
public typealias Failure = Never
private let upstream: Upstream
public init(upstream: Upstream) {
self.upstream = upstream
}
public func receive<S: Subscriber>(subscriber: S) where Failure == S.Failure, Output == S.Input {
subscriber.receive(subscription: Subscription(upstream: upstream, downstream: subscriber))
}
}
}
// MARK: - Subscription
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
private extension Publishers.Materialize {
class Subscription<Downstream: Subscriber>: Combine.Subscription where Downstream.Input == Event<Upstream.Output, Upstream.Failure>, Downstream.Failure == Never {
private var sink: Sink<Downstream>?
init(upstream: Upstream,
downstream: Downstream) {
self.sink = Sink(upstream: upstream,
downstream: downstream,
transformOutput: { .value($0) })
}
func request(_ demand: Subscribers.Demand) {
sink?.demand(demand)
}
func cancel() {
sink?.cancelUpstream()
sink = nil
}
}
}
// MARK: - Sink
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
private extension Publishers.Materialize {
class Sink<Downstream: Subscriber>: CombineExt.Sink<Upstream, Downstream>
where Downstream.Input == Event<Upstream.Output, Upstream.Failure>, Downstream.Failure == Never {
override func receive(completion: Subscribers.Completion<Upstream.Failure>) {
// We're overriding the standard completion buffering mechanism
// to buffer these events as regular materialized values, and send
// a regular finished event in either case
switch completion {
case .finished:
_ = buffer.buffer(value: .finished)
case .failure(let error):
_ = buffer.buffer(value: .failure(error))
}
buffer.complete(completion: .finished)
cancelUpstream()
}
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publishers.Materialize.Subscription: CustomStringConvertible {
var description: String {
return "Materialize.Subscription<\(Downstream.Input.Output.self), \(Downstream.Input.Failure.self)>"
}
}
#endif
| mit | 08d72ab1c4131d386822cc2605e2c302 | 34.658915 | 166 | 0.634348 | 4.554455 | false | false | false | false |
jgorset/Recorder | Sources/Recording.swift | 1 | 2808 | import AVFoundation
import QuartzCore
@objc public protocol RecorderDelegate: AVAudioRecorderDelegate {
optional func audioMeterDidUpdate(dB: Float)
}
public class Recording : NSObject {
@objc public enum State: Int {
case None, Record, Play
}
static var directory: String {
return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
}
public weak var delegate: RecorderDelegate?
public private(set) var url: NSURL
public private(set) var state: State = .None
public var bitRate = 192000
public var sampleRate = 44100.0
public var channels = 1
private let session = AVAudioSession.sharedInstance()
private var recorder: AVAudioRecorder?
private var player: AVAudioPlayer?
private var link: CADisplayLink?
var metering: Bool {
return delegate?.respondsToSelector("audioMeterDidUpdate:") == true
}
// MARK: - Initializers
public init(to: String) {
url = NSURL(fileURLWithPath: Recording.directory).URLByAppendingPathComponent(to)
super.init()
}
// MARK: - Record
public func prepare() throws {
let settings: [String: AnyObject] = [
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless)),
AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue,
AVEncoderBitRateKey: bitRate,
AVNumberOfChannelsKey: channels,
AVSampleRateKey: sampleRate
]
recorder = try AVAudioRecorder(URL: url, settings: settings)
recorder?.prepareToRecord()
recorder?.delegate = delegate
recorder?.meteringEnabled = metering
}
public func record() throws {
if recorder == nil {
try prepare()
}
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
recorder?.record()
state = .Record
if metering {
startMetering()
}
}
// MARK: - Playback
public func play() throws {
try session.setCategory(AVAudioSessionCategoryPlayback)
player = try AVAudioPlayer(contentsOfURL: url)
player?.play()
state = .Play
}
public func stop() {
switch state {
case .Play:
player?.stop()
player = nil
case .Record:
recorder?.stop()
recorder = nil
stopMetering()
default:
break
}
state = .None
}
// MARK: - Metering
func updateMeter() {
guard let recorder = recorder else { return }
recorder.updateMeters()
let dB = recorder.averagePowerForChannel(0)
delegate?.audioMeterDidUpdate?(dB)
}
private func startMetering() {
link = CADisplayLink(target: self, selector: "updateMeter")
link?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
private func stopMetering() {
link?.invalidate()
link = nil
}
}
| mit | 17dbb08694316fab667bb6e5318d37ef | 22.016393 | 92 | 0.692308 | 4.8 | false | false | false | false |
Beaver/BeaverCodeGen | Pods/SourceKittenFramework/Source/SourceKittenFramework/SourceDeclaration.swift | 1 | 7465 | //
// SourceDeclaration.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
import Foundation
public func insertMarks(declarations: [SourceDeclaration], limit: NSRange? = nil) -> [SourceDeclaration] {
guard !declarations.isEmpty else { return [] }
guard let path = declarations.first?.location.file, let file = File(path: path) else {
fatalError("can't extract marks without a file.")
}
let currentMarks = file.contents.pragmaMarks(filename: path, excludeRanges: declarations.map({
file.contents.byteRangeToNSRange(start: $0.range.location, length: $0.range.length) ?? NSRange()
}), limit: limit)
let newDeclarations: [SourceDeclaration] = declarations.map { declaration in
var varDeclaration = declaration
let range = file.contents.byteRangeToNSRange(start: declaration.range.location, length: declaration.range.length)
varDeclaration.children = insertMarks(declarations: declaration.children, limit: range)
return varDeclaration
}
return (newDeclarations + currentMarks).sorted()
}
/// Represents a source code declaration.
public struct SourceDeclaration {
public let type: ObjCDeclarationKind
public let location: SourceLocation
public let extent: (start: SourceLocation, end: SourceLocation)
public let name: String?
public let usr: String?
public let declaration: String?
public let documentation: Documentation?
public let commentBody: String?
public var children: [SourceDeclaration]
public let swiftDeclaration: String?
public let availability: ClangAvailability?
/// Range
public var range: NSRange {
return extent.start.range(toEnd: extent.end)
}
/// Returns the USR for the auto-generated getter for this property.
///
/// - warning: can only be invoked if `type == .Property`.
public var getterUSR: String {
return accessorUSR(getter: true)
}
/// Returns the USR for the auto-generated setter for this property.
///
/// - warning: can only be invoked if `type == .Property`.
public var setterUSR: String {
return accessorUSR(getter: false)
}
private enum AccessorType {
case `class`, instance
var propertyTypeString: String {
switch self {
case .class: return "(cpy)"
case .instance: return "(py)"
}
}
var methodTypeString: String {
switch self {
case .class: return "(cm)"
case .instance: return "(im)"
}
}
}
private func propertyTypeStringStartAndAcessorType(usr: String) -> (String.Index, AccessorType) {
if let accessorTypeStringStartIndex = usr.range(of: AccessorType.class.propertyTypeString)?.lowerBound {
return (accessorTypeStringStartIndex, .class)
} else if let accessorTypeStringStartIndex = usr.range(of: AccessorType.instance.propertyTypeString)?.lowerBound {
return (accessorTypeStringStartIndex, .instance)
} else {
fatalError("expected an instance or class property by got \(usr)")
}
}
private func accessorUSR(getter: Bool) -> String {
assert(type == .property)
guard let usr = usr else {
fatalError("Couldn't extract USR")
}
guard let declaration = declaration else {
fatalError("Couldn't extract declaration")
}
let (propertyTypeStringStart, accessorType) = propertyTypeStringStartAndAcessorType(usr: usr)
let nsDeclaration = declaration as NSString
#if swift(>=3.2)
let usrPrefix = usr[..<propertyTypeStringStart]
#else
let usrPrefix = usr.substring(to: propertyTypeStringStart)
#endif
let pattern = getter ? "getter\\s*=\\s*(\\w+)" : "setter\\s*=\\s*(\\w+:)"
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: declaration, options: [], range: NSRange(location: 0, length: nsDeclaration.length))
if !matches.isEmpty {
let accessorName = nsDeclaration.substring(with: matches[0].range(at: 1))
return usrPrefix + accessorType.methodTypeString + accessorName
} else if getter {
return usr.replacingOccurrences(of: accessorType.propertyTypeString, with: accessorType.methodTypeString)
}
// Setter
#if swift(>=3.2)
let setterOffset = accessorType.propertyTypeString.count
#else
let setterOffset = accessorType.propertyTypeString.characters.count
#endif
let from = usr.index(propertyTypeStringStart, offsetBy: setterOffset)
#if swift(>=3.2)
let capitalizedSetterName = String(usr[from...]).capitalizingFirstLetter()
#else
let capitalizedSetterName = usr.substring(from: from).capitalizingFirstLetter()
#endif
return "\(usrPrefix)\(accessorType.methodTypeString)set\(capitalizedSetterName):"
}
}
extension SourceDeclaration {
init?(cursor: CXCursor, compilerArguments: [String]) {
guard cursor.shouldDocument() else {
return nil
}
type = cursor.objCKind()
location = cursor.location()
extent = cursor.extent()
name = cursor.name()
usr = cursor.usr()
declaration = cursor.declaration()
documentation = Documentation(comment: cursor.parsedComment())
commentBody = cursor.commentBody()
children = cursor.flatMap({
SourceDeclaration(cursor: $0, compilerArguments: compilerArguments)
}).rejectPropertyMethods()
swiftDeclaration = cursor.swiftDeclaration(compilerArguments: compilerArguments)
availability = cursor.platformAvailability()
}
}
extension Sequence where Iterator.Element == SourceDeclaration {
/// Removes implicitly generated property getters & setters
func rejectPropertyMethods() -> [SourceDeclaration] {
let propertyGetterSetterUSRs = filter {
$0.type == .property
}.flatMap {
[$0.getterUSR, $0.setterUSR]
}
return filter { !propertyGetterSetterUSRs.contains($0.usr!) }
}
/// Reject one of an enum duplicate pair that's empty if the other isn't.
func rejectEmptyDuplicateEnums() -> [SourceDeclaration] {
let enums = filter { $0.type == .enum }
let enumUSRs = enums.map { $0.usr! }
let dupedEmptyUSRs = enumUSRs.filter { usr in
let enumsForUSR = enums.filter { $0.usr == usr }
let childCounts = Set(enumsForUSR.map({ $0.children.count }))
return childCounts.count > 1 && childCounts.contains(0)
}
return filter {
$0.type != .enum || !dupedEmptyUSRs.contains($0.usr!) || !$0.children.isEmpty
}
}
}
extension SourceDeclaration: Hashable {
public var hashValue: Int {
return usr?.hashValue ?? 0
}
}
public func == (lhs: SourceDeclaration, rhs: SourceDeclaration) -> Bool {
return lhs.usr == rhs.usr &&
lhs.location == rhs.location
}
// MARK: Comparable
extension SourceDeclaration: Comparable {}
/// A [strict total order](http://en.wikipedia.org/wiki/Total_order#Strict_total_order)
/// over instances of `Self`.
public func < (lhs: SourceDeclaration, rhs: SourceDeclaration) -> Bool {
return lhs.location < rhs.location
}
#endif
| mit | 534d75194f5ef3d4b3f145bde6b5f27e | 35.950495 | 124 | 0.657824 | 4.573529 | false | false | false | false |
danielgindi/Charts | Tests/ChartsTests/ChartDataTests.swift | 1 | 3571 | //
// ChartDataTests.swift
// ChartsTests
//
// Created by Peter Kaminski on 1/23/20.
//
@testable import Charts
import XCTest
class ChartDataTests: XCTestCase {
var data: ScatterChartData!
private enum SetLabels {
static let one = "label1"
static let two = "label2"
static let three = "label3"
static let badLabel = "Bad label"
}
override func setUp() {
super.setUp()
let setCount = 5
let range: UInt32 = 32
let values1 = (0 ..< setCount).map { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i), y: val)
}
let values2 = (0 ..< setCount).map { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i), y: val)
}
let values3 = (0 ..< setCount).map { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i), y: val)
}
let set1 = ScatterChartDataSet(entries: values1, label: SetLabels.one)
let set2 = ScatterChartDataSet(entries: values2, label: SetLabels.two)
let set3 = ScatterChartDataSet(entries: values3, label: SetLabels.three)
data = ScatterChartData(dataSets: [set1, set2, set3])
}
func testGetDataSetByLabelCaseSensitive() {
XCTAssertTrue(data.dataSet(forLabel: SetLabels.one, ignorecase: false)?.label == SetLabels.one)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.two, ignorecase: false)?.label == SetLabels.two)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.three, ignorecase: false)?.label == SetLabels.three)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.one.uppercased(), ignorecase: false) == nil)
}
func testGetDataSetByLabelIgnoreCase() {
XCTAssertTrue(data.dataSet(forLabel: SetLabels.one, ignorecase: true)?.label == SetLabels.one)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.two, ignorecase: true)?.label == SetLabels.two)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.three, ignorecase: true)?.label == SetLabels.three)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.one.uppercased(), ignorecase: true)?.label == SetLabels.one)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.two.uppercased(), ignorecase: true)?.label == SetLabels.two)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.three.uppercased(), ignorecase: true)?.label == SetLabels.three)
}
func testGetDataSetByLabelNilWithBadLabel() {
XCTAssertTrue(data.dataSet(forLabel: SetLabels.badLabel, ignorecase: true) == nil)
XCTAssertTrue(data.dataSet(forLabel: SetLabels.badLabel, ignorecase: false) == nil)
}
func testMaxEntryCountSet() throws {
let dataSet1 = BarChartDataSet(entries: (0 ..< 4).map { BarChartDataEntry(x: Double($0), y: Double($0)) },
label: "data-set-1")
let dataSet2 = BarChartDataSet(entries: (0 ..< 3).map { BarChartDataEntry(x: Double($0), y: Double($0)) },
label: "data-set-2")
let dataSet3 = BarChartDataSet(entries: [BarChartDataEntry(x: 0, y: 0)],
label: "data-set-3")
let data = BarChartData(dataSets: [dataSet1, dataSet2, dataSet3])
let maxEntryCountSet = try XCTUnwrap(data.maxEntryCountSet as? BarChartDataSet)
XCTAssertEqual(maxEntryCountSet, dataSet1)
}
}
| apache-2.0 | e2f285b32f24f039c99ce136274624db | 43.08642 | 119 | 0.641277 | 4.339004 | false | true | false | false |
joerocca/GitHawk | Classes/Issues/IssueResult.swift | 1 | 4763 | //
// IssueResult.swift
// Freetime
//
// Created by Ryan Nystrom on 7/27/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
import FlatCache
struct IssueResult: Cachable {
let id: String
let pullRequest: Bool
let status: IssueStatusModel
let title: NSAttributedStringSizing
let labels: IssueLabelsModel
let assignee: IssueAssigneesModel
// optional models
let rootComment: IssueCommentModel?
let reviewers: IssueAssigneesModel?
let milestone: Milestone?
// end optionals
let timelinePages: [IssueTimelinePage]
let viewerCanUpdate: Bool
let hasIssuesEnabled: Bool
let viewerCanAdminister: Bool
let defaultBranch: String
let fileChanges: FileChanges?
var timelineViewModels: [ListDiffable] {
return timelinePages.reduce([], { $0 + $1.viewModels })
}
var minStartCursor: String? {
return timelinePages.first?.startCursor
}
var hasPreviousPage: Bool {
return minStartCursor != nil
}
func timelinePages(appending: [ListDiffable]) -> [IssueTimelinePage] {
let newPage: IssueTimelinePage
if let lastPage = timelinePages.last {
newPage = IssueTimelinePage(
startCursor: lastPage.startCursor,
viewModels: lastPage.viewModels + appending
)
} else {
newPage = IssueTimelinePage(
startCursor: nil,
viewModels: appending
)
}
let count = timelinePages.count
if count > 0 {
return timelinePages[0..<count - 1] + [newPage]
} else {
return [newPage]
}
}
func updated(
id: String? = nil,
pullRequest: Bool? = nil,
status: IssueStatusModel? = nil,
title: NSAttributedStringSizing? = nil,
labels: IssueLabelsModel? = nil,
assignee: IssueAssigneesModel? = nil,
timelinePages: [IssueTimelinePage]? = nil,
viewerCanUpdate: Bool? = nil,
hasIssuesEnabled: Bool? = nil,
viewerCanAdminister: Bool? = nil,
defaultBranch: String? = nil
) -> IssueResult {
return IssueResult(
id: id ?? self.id,
pullRequest: pullRequest ?? self.pullRequest,
status: status ?? self.status,
title: title ?? self.title,
labels: labels ?? self.labels,
assignee: assignee ?? self.assignee,
rootComment: self.rootComment,
reviewers: self.reviewers,
milestone: self.milestone,
timelinePages: timelinePages ?? self.timelinePages,
viewerCanUpdate: viewerCanUpdate ?? self.viewerCanUpdate,
hasIssuesEnabled: hasIssuesEnabled ?? self.hasIssuesEnabled,
viewerCanAdminister: viewerCanAdminister ?? self.viewerCanAdminister,
defaultBranch: defaultBranch ?? self.defaultBranch,
fileChanges: fileChanges
)
}
func withMilestone(
_ milestone: Milestone?,
timelinePages: [IssueTimelinePage]? = nil
) -> IssueResult {
return IssueResult(
id: self.id,
pullRequest: self.pullRequest,
status: self.status,
title: self.title,
labels: self.labels,
assignee: self.assignee,
rootComment: self.rootComment,
reviewers: self.reviewers,
milestone: milestone,
timelinePages: timelinePages ?? self.timelinePages,
viewerCanUpdate: self.viewerCanUpdate,
hasIssuesEnabled: self.hasIssuesEnabled,
viewerCanAdminister: self.viewerCanAdminister,
defaultBranch: self.defaultBranch,
fileChanges: self.fileChanges
)
}
func withReviewers(
_ reviewers: IssueAssigneesModel?,
timelinePages: [IssueTimelinePage]? = nil
) -> IssueResult {
return IssueResult(
id: self.id,
pullRequest: self.pullRequest,
status: self.status,
title: self.title,
labels: self.labels,
assignee: self.assignee,
rootComment: self.rootComment,
reviewers: reviewers,
milestone: self.milestone,
timelinePages: timelinePages ?? self.timelinePages,
viewerCanUpdate: self.viewerCanUpdate,
hasIssuesEnabled: self.hasIssuesEnabled,
viewerCanAdminister: self.viewerCanAdminister,
defaultBranch: self.defaultBranch,
fileChanges: self.fileChanges
)
}
}
struct IssueTimelinePage {
let startCursor: String?
let viewModels: [ListDiffable]
}
| mit | 056f4ff9391a09f8ced5b4bcdfbf373d | 30.746667 | 81 | 0.607518 | 5.386878 | false | false | false | false |
aschwaighofer/swift | stdlib/public/core/Codable.swift | 2 | 232304 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Codable
//===----------------------------------------------------------------------===//
/// A type that can encode itself to an external representation.
public protocol Encodable {
/// Encodes this value into the given encoder.
///
/// If the value fails to encode anything, `encoder` will encode an empty
/// keyed container in its place.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
func encode(to encoder: Encoder) throws
}
/// A type that can decode itself from an external representation.
public protocol Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
init(from decoder: Decoder) throws
}
/// A type that can convert itself into and out of an external representation.
///
/// `Codable` is a type alias for the `Encodable` and `Decodable` protocols.
/// When you use `Codable` as a type or a generic constraint, it matches
/// any type that conforms to both protocols.
public typealias Codable = Encodable & Decodable
//===----------------------------------------------------------------------===//
// CodingKey
//===----------------------------------------------------------------------===//
/// A type that can be used as a key for encoding and decoding.
public protocol CodingKey: CustomStringConvertible,
CustomDebugStringConvertible {
/// The string to use in a named collection (e.g. a string-keyed dictionary).
var stringValue: String { get }
/// Creates a new instance from the given string.
///
/// If the string passed as `stringValue` does not correspond to any instance
/// of this type, the result is `nil`.
///
/// - parameter stringValue: The string value of the desired key.
init?(stringValue: String)
/// The value to use in an integer-indexed collection (e.g. an int-keyed
/// dictionary).
var intValue: Int? { get }
/// Creates a new instance from the specified integer.
///
/// If the value passed as `intValue` does not correspond to any instance of
/// this type, the result is `nil`.
///
/// - parameter intValue: The integer value of the desired key.
init?(intValue: Int)
}
extension CodingKey {
/// A textual representation of this key.
public var description: String {
let intValue = self.intValue?.description ?? "nil"
return "\(type(of: self))(stringValue: \"\(stringValue)\", intValue: \(intValue))"
}
/// A textual representation of this key, suitable for debugging.
public var debugDescription: String {
return description
}
}
//===----------------------------------------------------------------------===//
// Encoder & Decoder
//===----------------------------------------------------------------------===//
/// A type that can encode values into a native format for external
/// representation.
public protocol Encoder {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey: Any] { get }
/// Returns an encoding container appropriate for holding multiple values
/// keyed by the given key type.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `unkeyedContainer()` or after
/// encoding a value through a call to `singleValueContainer()`
///
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key>
/// Returns an encoding container appropriate for holding multiple unkeyed
/// values.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `container(keyedBy:)` or after
/// encoding a value through a call to `singleValueContainer()`
///
/// - returns: A new empty unkeyed container.
func unkeyedContainer() -> UnkeyedEncodingContainer
/// Returns an encoding container appropriate for holding a single primitive
/// value.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `unkeyedContainer()` or
/// `container(keyedBy:)`, or after encoding a value through a call to
/// `singleValueContainer()`
///
/// - returns: A new empty single value container.
func singleValueContainer() -> SingleValueEncodingContainer
}
/// A type that can decode values from a native format into in-memory
/// representations.
public protocol Decoder {
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// Any contextual information set by the user for decoding.
var userInfo: [CodingUserInfoKey: Any] { get }
/// Returns the data stored in this decoder as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
func container<Key>(
keyedBy type: Key.Type
) throws -> KeyedDecodingContainer<Key>
/// Returns the data stored in this decoder as represented in a container
/// appropriate for holding values with no keys.
///
/// - returns: An unkeyed container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
func unkeyedContainer() throws -> UnkeyedDecodingContainer
/// Returns the data stored in this decoder as represented in a container
/// appropriate for holding a single primitive value.
///
/// - returns: A single value container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a single value container.
func singleValueContainer() throws -> SingleValueDecodingContainer
}
//===----------------------------------------------------------------------===//
// Keyed Encoding Containers
//===----------------------------------------------------------------------===//
/// A type that provides a view into an encoder's storage and is used to hold
/// the encoded properties of an encodable type in a keyed manner.
///
/// Encoders should provide types conforming to
/// `KeyedEncodingContainerProtocol` for their format.
public protocol KeyedEncodingContainerProtocol {
associatedtype Key: CodingKey
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Encodes a null value for the given key.
///
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
mutating func encodeNil(forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Bool, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: String, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Double, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Float, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int8, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int16, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int32, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int64, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt8, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt16, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt32, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt64, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode<T: Encodable>(_ value: T, forKey key: Key) throws
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey>
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer
/// Stores a new nested container for the default `super` key and returns A
/// new encoder instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
/// Stores a new nested container for the given key and returns A new encoder
/// instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder
}
// An implementation of _KeyedEncodingContainerBase and
// _KeyedEncodingContainerBox are given at the bottom of this file.
/// A concrete container that provides a view into an encoder's storage, making
/// the encoded properties of an encodable type accessible by keys.
public struct KeyedEncodingContainer<K: CodingKey> :
KeyedEncodingContainerProtocol
{
public typealias Key = K
/// The container for the concrete encoder.
internal var _box: _KeyedEncodingContainerBase
/// Creates a new instance with the given container.
///
/// - parameter container: The container to hold.
public init<Container: KeyedEncodingContainerProtocol>(
_ container: Container
) where Container.Key == Key {
_box = _KeyedEncodingContainerBox(container)
}
/// The path of coding keys taken to get to this point in encoding.
public var codingPath: [CodingKey] {
return _box.codingPath
}
/// Encodes a null value for the given key.
///
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
public mutating func encodeNil(forKey key: Key) throws {
try _box.encodeNil(forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Bool, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: String, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Double, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Float, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int8, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int16, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int32, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int64, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt8, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt16, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt32, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt64, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode<T: Encodable>(
_ value: T,
forKey key: Key
) throws {
try _box.encode(value, forKey: key)
}
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try _box.encodeConditional(object, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
public mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
return _box.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
public mutating func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer {
return _box.nestedUnkeyedContainer(forKey: key)
}
/// Stores a new nested container for the default `super` key and returns A
/// new encoder instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
public mutating func superEncoder() -> Encoder {
return _box.superEncoder()
}
/// Stores a new nested container for the given key and returns A new encoder
/// instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new encoder to pass to `super.encode(to:)`.
public mutating func superEncoder(forKey key: Key) -> Encoder {
return _box.superEncoder(forKey: key)
}
}
/// A type that provides a view into a decoder's storage and is used to hold
/// the encoded properties of a decodable type in a keyed manner.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for
/// their format.
public protocol KeyedDecodingContainerProtocol {
associatedtype Key: CodingKey
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different
/// keys here; it is possible to encode with multiple key types which are
/// not convertible to one another. This should report all keys present
/// which are convertible to the requested type.
var allKeys: [Key] { get }
/// Returns a Boolean value indicating whether the decoder contains a value
/// associated with the given key.
///
/// The value associated with `key` may be a null value as appropriate for
/// the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
func decodeNil(forKey key: Key) throws -> Bool
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: String.Type, forKey key: Key) throws -> String
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Double.Type, forKey key: Key) throws -> Double
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Float.Type, forKey key: Key) throws -> Float
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int.Type, forKey key: Key) throws -> Int
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T?
/// Returns the data stored for the given key as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey>
/// Returns the data stored for the given key as represented in an unkeyed
/// container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the default `super` key.
func superDecoder() throws -> Decoder
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func superDecoder(forKey key: Key) throws -> Decoder
}
// An implementation of _KeyedDecodingContainerBase and
// _KeyedDecodingContainerBox are given at the bottom of this file.
/// A concrete container that provides a view into a decoder's storage, making
/// the encoded properties of a decodable type accessible by keys.
public struct KeyedDecodingContainer<K: CodingKey> :
KeyedDecodingContainerProtocol
{
public typealias Key = K
/// The container for the concrete decoder.
internal var _box: _KeyedDecodingContainerBase
/// Creates a new instance with the given container.
///
/// - parameter container: The container to hold.
public init<Container: KeyedDecodingContainerProtocol>(
_ container: Container
) where Container.Key == Key {
_box = _KeyedDecodingContainerBox(container)
}
/// The path of coding keys taken to get to this point in decoding.
public var codingPath: [CodingKey] {
return _box.codingPath
}
/// All the keys the decoder has for this container.
///
/// Different keyed containers from the same decoder may return different
/// keys here, because it is possible to encode with multiple key types
/// which are not convertible to one another. This should report all keys
/// present which are convertible to the requested type.
public var allKeys: [Key] {
return _box.allKeys as! [Key]
}
/// Returns a Boolean value indicating whether the decoder contains a value
/// associated with the given key.
///
/// The value associated with the given key may be a null value as
/// appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
public func contains(_ key: Key) -> Bool {
return _box.contains(key)
}
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
public func decodeNil(forKey key: Key) throws -> Bool {
return try _box.decodeNil(forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
return try _box.decode(Bool.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
return try _box.decode(String.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
return try _box.decode(Double.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
return try _box.decode(Float.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
return try _box.decode(Int.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
return try _box.decode(Int8.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
return try _box.decode(Int16.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
return try _box.decode(Int32.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
return try _box.decode(Int64.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
return try _box.decode(UInt.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
return try _box.decode(UInt8.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
return try _box.decode(UInt16.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
return try _box.decode(UInt32.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
return try _box.decode(UInt64.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T {
return try _box.decode(T.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
return try _box.decodeIfPresent(Bool.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
return try _box.decodeIfPresent(String.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
return try _box.decodeIfPresent(Double.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
return try _box.decodeIfPresent(Float.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
return try _box.decodeIfPresent(Int.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
return try _box.decodeIfPresent(Int8.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
return try _box.decodeIfPresent(Int16.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
return try _box.decodeIfPresent(Int32.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
return try _box.decodeIfPresent(Int64.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
return try _box.decodeIfPresent(UInt.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
return try _box.decodeIfPresent(UInt8.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
return try _box.decodeIfPresent(UInt16.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
return try _box.decodeIfPresent(UInt32.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
return try _box.decodeIfPresent(UInt64.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
return try _box.decodeIfPresent(T.self, forKey: key)
}
/// Returns the data stored for the given key as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
public func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
return try _box.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
/// Returns the data stored for the given key as represented in an unkeyed
/// container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
public func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer {
return try _box.nestedUnkeyedContainer(forKey: key)
}
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the default `super` key.
public func superDecoder() throws -> Decoder {
return try _box.superDecoder()
}
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _box.superDecoder(forKey: key)
}
}
//===----------------------------------------------------------------------===//
// Unkeyed Encoding Containers
//===----------------------------------------------------------------------===//
/// A type that provides a view into an encoder's storage and is used to hold
/// the encoded properties of an encodable type sequentially, without keys.
///
/// Encoders should provide types conforming to `UnkeyedEncodingContainer` for
/// their format.
public protocol UnkeyedEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// The number of elements encoded into the container.
var count: Int { get }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
mutating func encodeNil() throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Bool) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: String) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Double) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Float) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int8) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int16) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int32) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int64) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt8) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt16) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt32) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt64) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode<T: Encodable>(_ value: T) throws
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// For formats which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeConditional<T: AnyObject & Encodable>(_ object: T) throws
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Bool
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == String
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Double
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Float
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int8
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int16
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int32
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int64
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt8
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt16
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt32
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt64
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element: Encodable
/// Encodes a nested container keyed by the given type and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type
) -> KeyedEncodingContainer<NestedKey>
/// Encodes an unkeyed encoding container and returns it.
///
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer
/// Encodes a nested container and returns an `Encoder` instance for encoding
/// `super` into that container.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
}
/// A type that provides a view into a decoder's storage and is used to hold
/// the encoded properties of a decodable type sequentially, without keys.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for
/// their format.
public protocol UnkeyedDecodingContainer {
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// The number of elements contained within this container.
///
/// If the number of elements is unknown, the value is `nil`.
var count: Int? { get }
/// A Boolean value indicating whether there are no more elements left to be
/// decoded in the container.
var isAtEnd: Bool { get }
/// The current decoding index of the container (i.e. the index of the next
/// element to be decoded.) Incremented after every successful decode call.
var currentIndex: Int { get }
/// Decodes a null value.
///
/// If the value is not null, does not increment currentIndex.
///
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.valueNotFound` if there are no more values to
/// decode.
mutating func decodeNil() throws -> Bool
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Bool.Type) throws -> Bool
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: String.Type) throws -> String
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Double.Type) throws -> Double
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Float.Type) throws -> Float
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int.Type) throws -> Int
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int8.Type) throws -> Int8
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int16.Type) throws -> Int16
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int32.Type) throws -> Int32
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int64.Type) throws -> Int64
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt.Type) throws -> UInt
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt8.Type) throws -> UInt8
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt16.Type) throws -> UInt16
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt32.Type) throws -> UInt32
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt64.Type) throws -> UInt64
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode<T: Decodable>(_ type: T.Type) throws -> T
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: String.Type) throws -> String?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Double.Type) throws -> Double?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Float.Type) throws -> Float?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int.Type) throws -> Int?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent<T: Decodable>(_ type: T.Type) throws -> T?
/// Decodes a nested container keyed by the given type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
mutating func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type
) throws -> KeyedDecodingContainer<NestedKey>
/// Decodes an unkeyed nested container.
///
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer
/// Decodes a nested container and returns a `Decoder` instance for decoding
/// `super` from that container.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func superDecoder() throws -> Decoder
}
//===----------------------------------------------------------------------===//
// Single Value Encoding Containers
//===----------------------------------------------------------------------===//
/// A container that can support the storage and direct encoding of a single
/// non-keyed value.
public protocol SingleValueEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encodeNil() throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Bool) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: String) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Double) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Float) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int8) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int16) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int32) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int64) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt8) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt16) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt32) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt64) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode<T: Encodable>(_ value: T) throws
}
/// A container that can support the storage and direct decoding of a single
/// nonkeyed value.
public protocol SingleValueDecodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Bool.Type) throws -> Bool
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: String.Type) throws -> String
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Double.Type) throws -> Double
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Float.Type) throws -> Float
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int.Type) throws -> Int
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int8.Type) throws -> Int8
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int16.Type) throws -> Int16
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int32.Type) throws -> Int32
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int64.Type) throws -> Int64
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt.Type) throws -> UInt
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt8.Type) throws -> UInt8
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt16.Type) throws -> UInt16
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt32.Type) throws -> UInt32
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt64.Type) throws -> UInt64
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode<T: Decodable>(_ type: T.Type) throws -> T
}
//===----------------------------------------------------------------------===//
// User Info
//===----------------------------------------------------------------------===//
/// A user-defined key for providing context during encoding and decoding.
public struct CodingUserInfoKey: RawRepresentable, Equatable, Hashable {
public typealias RawValue = String
/// The key's string value.
public let rawValue: String
/// Creates a new instance with the given raw value.
///
/// - parameter rawValue: The value of the key.
public init?(rawValue: String) {
self.rawValue = rawValue
}
/// Returns a Boolean value indicating whether the given keys are equal.
///
/// - parameter lhs: The key to compare against.
/// - parameter rhs: The key to compare with.
public static func ==(
lhs: CodingUserInfoKey,
rhs: CodingUserInfoKey
) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// The key's hash value.
public var hashValue: Int {
return self.rawValue.hashValue
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher) {
hasher.combine(self.rawValue)
}
}
//===----------------------------------------------------------------------===//
// Errors
//===----------------------------------------------------------------------===//
/// An error that occurs during the encoding of a value.
public enum EncodingError: Error {
/// The context in which the error occurred.
public struct Context {
/// The path of coding keys taken to get to the point of the failing encode
/// call.
public let codingPath: [CodingKey]
/// A description of what went wrong, for debugging purposes.
public let debugDescription: String
/// The underlying error which caused this error, if any.
public let underlyingError: Error?
/// Creates a new context with the given path of coding keys and a
/// description of what went wrong.
///
/// - parameter codingPath: The path of coding keys taken to get to the
/// point of the failing encode call.
/// - parameter debugDescription: A description of what went wrong, for
/// debugging purposes.
/// - parameter underlyingError: The underlying error which caused this
/// error, if any.
public init(
codingPath: [CodingKey],
debugDescription: String,
underlyingError: Error? = nil
) {
self.codingPath = codingPath
self.debugDescription = debugDescription
self.underlyingError = underlyingError
}
}
/// An indication that an encoder or its containers could not encode the
/// given value.
///
/// As associated values, this case contains the attempted value and context
/// for debugging.
case invalidValue(Any, Context)
// MARK: - NSError Bridging
// CustomNSError bridging applies only when the CustomNSError conformance is
// applied in the same module as the declared error type. Since we cannot
// access CustomNSError (which is defined in Foundation) from here, we can
// use the "hidden" entry points.
public var _domain: String {
return "NSCocoaErrorDomain"
}
public var _code: Int {
switch self {
case .invalidValue: return 4866
}
}
public var _userInfo: AnyObject? {
// The error dictionary must be returned as an AnyObject. We can do this
// only on platforms with bridging, unfortunately.
#if _runtime(_ObjC)
let context: Context
switch self {
case .invalidValue(_, let c): context = c
}
var userInfo: [String: Any] = [
"NSCodingPath": context.codingPath,
"NSDebugDescription": context.debugDescription
]
if let underlyingError = context.underlyingError {
userInfo["NSUnderlyingError"] = underlyingError
}
return userInfo as AnyObject
#else
return nil
#endif
}
}
/// An error that occurs during the decoding of a value.
public enum DecodingError: Error {
/// The context in which the error occurred.
public struct Context {
/// The path of coding keys taken to get to the point of the failing decode
/// call.
public let codingPath: [CodingKey]
/// A description of what went wrong, for debugging purposes.
public let debugDescription: String
/// The underlying error which caused this error, if any.
public let underlyingError: Error?
/// Creates a new context with the given path of coding keys and a
/// description of what went wrong.
///
/// - parameter codingPath: The path of coding keys taken to get to the
/// point of the failing decode call.
/// - parameter debugDescription: A description of what went wrong, for
/// debugging purposes.
/// - parameter underlyingError: The underlying error which caused this
/// error, if any.
public init(
codingPath: [CodingKey],
debugDescription: String,
underlyingError: Error? = nil
) {
self.codingPath = codingPath
self.debugDescription = debugDescription
self.underlyingError = underlyingError
}
}
/// An indication that a value of the given type could not be decoded because
/// it did not match the type of what was found in the encoded payload.
///
/// As associated values, this case contains the attempted type and context
/// for debugging.
case typeMismatch(Any.Type, Context)
/// An indication that a non-optional value of the given type was expected,
/// but a null value was found.
///
/// As associated values, this case contains the attempted type and context
/// for debugging.
case valueNotFound(Any.Type, Context)
/// An indication that a keyed decoding container was asked for an entry for
/// the given key, but did not contain one.
///
/// As associated values, this case contains the attempted key and context
/// for debugging.
case keyNotFound(CodingKey, Context)
/// An indication that the data is corrupted or otherwise invalid.
///
/// As an associated value, this case contains the context for debugging.
case dataCorrupted(Context)
// MARK: - NSError Bridging
// CustomNSError bridging applies only when the CustomNSError conformance is
// applied in the same module as the declared error type. Since we cannot
// access CustomNSError (which is defined in Foundation) from here, we can
// use the "hidden" entry points.
public var _domain: String {
return "NSCocoaErrorDomain"
}
public var _code: Int {
switch self {
case .keyNotFound, .valueNotFound: return 4865
case .typeMismatch, .dataCorrupted: return 4864
}
}
public var _userInfo: AnyObject? {
// The error dictionary must be returned as an AnyObject. We can do this
// only on platforms with bridging, unfortunately.
#if _runtime(_ObjC)
let context: Context
switch self {
case .keyNotFound(_, let c): context = c
case .valueNotFound(_, let c): context = c
case .typeMismatch(_, let c): context = c
case .dataCorrupted( let c): context = c
}
var userInfo: [String: Any] = [
"NSCodingPath": context.codingPath,
"NSDebugDescription": context.debugDescription
]
if let underlyingError = context.underlyingError {
userInfo["NSUnderlyingError"] = underlyingError
}
return userInfo as AnyObject
#else
return nil
#endif
}
}
// The following extensions allow for easier error construction.
internal struct _GenericIndexKey: CodingKey {
internal var stringValue: String
internal var intValue: Int?
internal init?(stringValue: String) {
return nil
}
internal init?(intValue: Int) {
self.stringValue = "Index \(intValue)"
self.intValue = intValue
}
}
extension DecodingError {
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is constructed by appending the
/// given key to the given container's coding path.
///
/// - param key: The key which caused the failure.
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError<C: KeyedDecodingContainerProtocol>(
forKey key: C.Key,
in container: C,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(
codingPath: container.codingPath + [key],
debugDescription: debugDescription)
return .dataCorrupted(context)
}
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is constructed by appending the
/// given container's current index to its coding path.
///
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError(
in container: UnkeyedDecodingContainer,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(
codingPath: container.codingPath +
[_GenericIndexKey(intValue: container.currentIndex)!],
debugDescription: debugDescription)
return .dataCorrupted(context)
}
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is the given container's coding
/// path.
///
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError(
in container: SingleValueDecodingContainer,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(codingPath: container.codingPath,
debugDescription: debugDescription)
return .dataCorrupted(context)
}
}
//===----------------------------------------------------------------------===//
// Keyed Encoding Container Implementations
//===----------------------------------------------------------------------===//
internal class _KeyedEncodingContainerBase {
internal init(){}
deinit {}
// These must all be given a concrete implementation in _*Box.
internal var codingPath: [CodingKey] {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeNil<K: CodingKey>(forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Bool, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: String, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Double, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Float, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int8, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int16, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int32, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int64, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt8, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt16, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt32, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt64, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<T: Encodable, K: CodingKey>(_ value: T, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeConditional<T: AnyObject & Encodable, K: CodingKey>(
_ object: T,
forKey key: K
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Bool?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: String?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Double?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Float?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int8?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int16?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int32?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int64?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt8?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt16?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt32?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt64?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<T: Encodable, K: CodingKey>(
_ value: T?,
forKey key: K
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy keyType: NestedKey.Type,
forKey key: K
) -> KeyedEncodingContainer<NestedKey> {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) -> UnkeyedEncodingContainer {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder() -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder<K: CodingKey>(forKey key: K) -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedEncodingContainerBox<
Concrete: KeyedEncodingContainerProtocol
>: _KeyedEncodingContainerBase {
typealias Key = Concrete.Key
internal var concrete: Concrete
internal init(_ container: Concrete) {
concrete = container
}
override internal var codingPath: [CodingKey] {
return concrete.codingPath
}
override internal func encodeNil<K: CodingKey>(forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeNil(forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Bool, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: String, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Double, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Float, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int8, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int16, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int32, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int64, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt8, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt16, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt32, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt64, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<T: Encodable, K: CodingKey>(
_ value: T,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encodeConditional<T: AnyObject & Encodable, K: CodingKey>(
_ object: T,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeConditional(object, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Bool?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: String?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Double?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Float?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int8?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int16?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int32?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int64?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt8?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt16?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt32?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt64?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<T: Encodable, K: CodingKey>(
_ value: T?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy keyType: NestedKey.Type,
forKey key: K
) -> KeyedEncodingContainer<NestedKey> {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) -> UnkeyedEncodingContainer {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superEncoder() -> Encoder {
return concrete.superEncoder()
}
override internal func superEncoder<K: CodingKey>(forKey key: K) -> Encoder {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.superEncoder(forKey: key)
}
}
internal class _KeyedDecodingContainerBase {
internal init(){}
deinit {}
internal var codingPath: [CodingKey] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal var allKeys: [CodingKey] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func contains<K: CodingKey>(_ key: K) -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeNil<K: CodingKey>(forKey key: K) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy type: NestedKey.Type,
forKey key: K
) throws -> KeyedDecodingContainer<NestedKey> {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) throws -> UnkeyedDecodingContainer {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder() throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder<K: CodingKey>(forKey key: K) throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedDecodingContainerBox<
Concrete: KeyedDecodingContainerProtocol
>: _KeyedDecodingContainerBase {
typealias Key = Concrete.Key
internal var concrete: Concrete
internal init(_ container: Concrete) {
concrete = container
}
override var codingPath: [CodingKey] {
return concrete.codingPath
}
override var allKeys: [CodingKey] {
return concrete.allKeys
}
override internal func contains<K: CodingKey>(_ key: K) -> Bool {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.contains(key)
}
override internal func decodeNil<K: CodingKey>(forKey key: K) throws -> Bool {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeNil(forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Bool.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(String.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Double.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Float.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int8.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int16.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int32.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int64.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt8.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt16.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt32.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt64.self, forKey: key)
}
override internal func decode<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(T.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Bool.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(String.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Double.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Float.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int8.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int16.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int32.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int64.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt8.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt16.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt32.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt64.self, forKey: key)
}
override internal func decodeIfPresent<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(T.self, forKey: key)
}
override internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy type: NestedKey.Type,
forKey key: K
) throws -> KeyedDecodingContainer<NestedKey> {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) throws -> UnkeyedDecodingContainer {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superDecoder() throws -> Decoder {
return try concrete.superDecoder()
}
override internal func superDecoder<K: CodingKey>(forKey key: K) throws -> Decoder {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.superDecoder(forKey: key)
}
}
//===----------------------------------------------------------------------===//
// Primitive and RawRepresentable Extensions
//===----------------------------------------------------------------------===//
extension Bool: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Bool.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Bool, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Bool`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Bool, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Bool`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension String: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(String.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == String, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `String`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == String, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `String`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Double: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Double.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Double, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Double`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Double, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Double`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Float: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Float.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Float, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Float`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Float, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Float`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Float16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let floatValue = try Float(from: decoder)
self = Float16(floatValue)
if isInfinite && floatValue.isFinite {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Parsed JSON number \(floatValue) does not fit in Float16."
)
)
}
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
try Float(self).encode(to: encoder)
}
}
extension Int: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int8: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int8.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int8, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int8`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int8, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int8`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int16.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int16, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int16`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int16, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int16`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int32: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int32.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int32, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int32`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int32, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int32`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int64: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int64.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int64, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int64`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int64, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int64`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt8: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt8.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt8, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt8`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt8, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt8`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt16.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt16, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt16`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt16, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt16`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt32: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt32.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt32, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt32`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt32, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt32`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt64: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt64.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt64, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt64`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt64, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt64`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
//===----------------------------------------------------------------------===//
// Optional/Collection Type Conformances
//===----------------------------------------------------------------------===//
extension Optional: Encodable where Wrapped: Encodable {
/// Encodes this optional value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .none: try container.encodeNil()
case .some(let wrapped): try container.encode(wrapped)
}
}
}
extension Optional: Decodable where Wrapped: Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .none
} else {
let element = try container.decode(Wrapped.self)
self = .some(element)
}
}
}
extension Array: Encodable where Element: Encodable {
/// Encodes the elements of this array into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Array: Decodable where Element: Decodable {
/// Creates a new array by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
extension ContiguousArray: Encodable where Element: Encodable {
/// Encodes the elements of this contiguous array into the given encoder
/// in an unkeyed container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension ContiguousArray: Decodable where Element: Decodable {
/// Creates a new contiguous array by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
extension Set: Encodable where Element: Encodable {
/// Encodes the elements of this set into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Set: Decodable where Element: Decodable {
/// Creates a new set by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.insert(element)
}
}
}
/// A wrapper for dictionary keys which are Strings or Ints.
internal struct _DictionaryCodingKey: CodingKey {
internal let stringValue: String
internal let intValue: Int?
internal init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = Int(stringValue)
}
internal init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
}
extension Dictionary: Encodable where Key: Encodable, Value: Encodable {
/// Encodes the contents of this dictionary into the given encoder.
///
/// If the dictionary uses `String` or `Int` keys, the contents are encoded
/// in a keyed container. Otherwise, the contents are encoded as alternating
/// key-value pairs in an unkeyed container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
if Key.self == String.self {
// Since the keys are already Strings, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(stringValue: key as! String)!
try container.encode(value, forKey: codingKey)
}
} else if Key.self == Int.self {
// Since the keys are already Ints, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(intValue: key as! Int)!
try container.encode(value, forKey: codingKey)
}
} else {
// Keys are Encodable but not Strings or Ints, so we cannot arbitrarily
// convert to keys. We can encode as an array of alternating key-value
// pairs, though.
var container = encoder.unkeyedContainer()
for (key, value) in self {
try container.encode(key)
try container.encode(value)
}
}
}
}
extension Dictionary: Decodable where Key: Decodable, Value: Decodable {
/// Creates a new dictionary by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
if Key.self == String.self {
// The keys are Strings, so we should be able to expect a keyed container.
let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
for key in container.allKeys {
let value = try container.decode(Value.self, forKey: key)
self[key.stringValue as! Key] = value
}
} else if Key.self == Int.self {
// The keys are Ints, so we should be able to expect a keyed container.
let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
for key in container.allKeys {
guard key.intValue != nil else {
// We provide stringValues for Int keys; if an encoder chooses not to
// use the actual intValues, we've encoded string keys.
// So on init, _DictionaryCodingKey tries to parse string keys as
// Ints. If that succeeds, then we would have had an intValue here.
// We don't, so this isn't a valid Int key.
var codingPath = decoder.codingPath
codingPath.append(key)
throw DecodingError.typeMismatch(
Int.self,
DecodingError.Context(
codingPath: codingPath,
debugDescription: "Expected Int key but found String key instead."
)
)
}
let value = try container.decode(Value.self, forKey: key)
self[key.intValue! as! Key] = value
}
} else {
// We should have encoded as an array of alternating key-value pairs.
var container = try decoder.unkeyedContainer()
// We're expecting to get pairs. If the container has a known count, it
// had better be even; no point in doing work if not.
if let count = container.count {
guard count % 2 == 0 else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Expected collection of key-value pairs; encountered odd-length array instead."
)
)
}
}
while !container.isAtEnd {
let key = try container.decode(Key.self)
guard !container.isAtEnd else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Unkeyed container reached end before value in key-value pair."
)
)
}
let value = try container.decode(Value.self)
self[key] = value
}
}
}
}
//===----------------------------------------------------------------------===//
// Convenience Default Implementations
//===----------------------------------------------------------------------===//
// Default implementation of encodeConditional(_:forKey:) in terms of
// encode(_:forKey:)
extension KeyedEncodingContainerProtocol {
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try encode(object, forKey: key)
}
}
// Default implementation of encodeIfPresent(_:forKey:) in terms of
// encode(_:forKey:)
extension KeyedEncodingContainerProtocol {
public mutating func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
}
// Default implementation of decodeIfPresent(_:forKey:) in terms of
// decode(_:forKey:) and decodeNil(forKey:)
extension KeyedDecodingContainerProtocol {
public func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Bool.self, forKey: key)
}
public func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(String.self, forKey: key)
}
public func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Double.self, forKey: key)
}
public func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Float.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int8.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int16.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int32.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int64.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt8.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt16.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt32.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt64.self, forKey: key)
}
public func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(T.self, forKey: key)
}
}
// Default implementation of encodeConditional(_:) in terms of encode(_:),
// and encode(contentsOf:) in terms of encode(_:) loop.
extension UnkeyedEncodingContainer {
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T
) throws {
try self.encode(object)
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Bool {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == String {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Double {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Float {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int8 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int16 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int32 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int64 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt8 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt16 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt32 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt64 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element: Encodable {
for element in sequence {
try self.encode(element)
}
}
}
// Default implementation of decodeIfPresent(_:) in terms of decode(_:) and
// decodeNil()
extension UnkeyedDecodingContainer {
public mutating func decodeIfPresent(
_ type: Bool.Type
) throws -> Bool? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Bool.self)
}
public mutating func decodeIfPresent(
_ type: String.Type
) throws -> String? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(String.self)
}
public mutating func decodeIfPresent(
_ type: Double.Type
) throws -> Double? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Double.self)
}
public mutating func decodeIfPresent(
_ type: Float.Type
) throws -> Float? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Float.self)
}
public mutating func decodeIfPresent(
_ type: Int.Type
) throws -> Int? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int.self)
}
public mutating func decodeIfPresent(
_ type: Int8.Type
) throws -> Int8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int8.self)
}
public mutating func decodeIfPresent(
_ type: Int16.Type
) throws -> Int16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int16.self)
}
public mutating func decodeIfPresent(
_ type: Int32.Type
) throws -> Int32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int32.self)
}
public mutating func decodeIfPresent(
_ type: Int64.Type
) throws -> Int64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int64.self)
}
public mutating func decodeIfPresent(
_ type: UInt.Type
) throws -> UInt? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt.self)
}
public mutating func decodeIfPresent(
_ type: UInt8.Type
) throws -> UInt8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt8.self)
}
public mutating func decodeIfPresent(
_ type: UInt16.Type
) throws -> UInt16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt16.self)
}
public mutating func decodeIfPresent(
_ type: UInt32.Type
) throws -> UInt32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt32.self)
}
public mutating func decodeIfPresent(
_ type: UInt64.Type
) throws -> UInt64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt64.self)
}
public mutating func decodeIfPresent<T: Decodable>(
_ type: T.Type
) throws -> T? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(T.self)
}
}
| apache-2.0 | ec948a768576b6ba0ac7e347c6ecd36a | 36.760728 | 111 | 0.67496 | 4.355074 | false | false | false | false |
konovalov-aleks/snake-game | client/platform/ios/Game/Game/GameCanvasView.swift | 1 | 8873 | //
// GameCanvasView.swift
// Game
//
// Created by Солодовников П.А. on 16.11.16.
// Copyright © 2016 Tensor. All rights reserved.
//
import UIKit
class GameCanvasView: UIView {
// MARK: Константы
let backgroundCGImage: CGImage = UIImage(named: "Background")!.cgImage!
let mySnakeCGColor: CGColor = UIColor.blue.cgColor
let otherSnakesCGColor: CGColor = UIColor.red.cgColor
let whiteCGColor: CGColor = UIColor.white.cgColor
let blackCGColor: CGColor = UIColor.black.cgColor
let wallCGColor: CGColor = UIColor.yellow.cgColor
var convertedBackgroundImage: CGImage?
static let ppi = UIScreen.main.scale * ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) ? 132 : 163)
static let screenDimsInMM = screenDimensionsInMM()
public var delegate: GameCanvasViewDelegate?
var cameraPos = SDVectorModel(x: 0, y: 0)
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()!
ctx.interpolationQuality = .none
ctx.setLineJoin(.round)
ctx.setLineCap(.round)
ctx.setAllowsAntialiasing(true)
ctx.setShouldAntialias(true)
if convertedBackgroundImage == nil {
let colorSpace: CGColorSpace = ctx.colorSpace!
let bitmapInfo = ctx.bitmapInfo
let bitmapContext = CGContext(data: nil, width: Int(backgroundCGImage.width), height: Int(backgroundCGImage.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
bitmapContext?.draw(backgroundCGImage, in: CGRect(x: 0, y: 0, width: backgroundCGImage.width, height: backgroundCGImage.height))
convertedBackgroundImage = bitmapContext?.makeImage()
}
let gameInstance = SDGame.instance()!
gameInstance.run(Float(GameCanvasView.screenDimsInMM.width), dispHeight: Float(GameCanvasView.screenDimsInMM.height))
let fld = gameInstance.getField()
// настраиваем камеру
let mySnake = fld.mySnake
if mySnake != nil {
cameraPos = mySnake!.points[0]
}
// отображаем задний фон
drawBackground(ctx: ctx, startPoint: cameraPos)
ctx.translateBy(x: self.frame.width / 2 - mmToPoints(CGFloat(cameraPos.x)), y: self.frame.height / 2 - mmToPoints(CGFloat(cameraPos.y)))
// рисуем стены
drawWalls(ctx: ctx, walls: fld.walls)
// отрисовка бонусов
let bonuses = fld.bonuses
for bonus in bonuses {
drawBonus(ctx: ctx, bonus: bonus)
}
// Рисуем свою змейку
if mySnake != nil {
drawSnake(ctx: ctx, snake: mySnake!)
}
// Рисуем змейки других игроков
let snakes = fld.snakes
for snake in snakes {
drawSnake(ctx: ctx, snake: snake)
}
// после отрисовки делегируем контроллеру определение того, закончилась игра или нет
delegate?.handleGameOver()
}
func drawWalls(ctx: CGContext, walls: SDWalls) {
let scaledLeftX = mmToPoints(CGFloat(walls.leftX))
let scaledRightX = mmToPoints(CGFloat(walls.rightX))
let scaledTopY = mmToPoints(CGFloat(walls.topY))
let scaledBottomY = mmToPoints(CGFloat(walls.bottomY))
let wallsRectPath: UIBezierPath = UIBezierPath()
wallsRectPath.move(to: CGPoint(x: scaledLeftX, y: scaledTopY))
wallsRectPath.addLine(to: CGPoint(x: scaledRightX, y: scaledTopY))
wallsRectPath.addLine(to: CGPoint(x: scaledRightX, y: scaledBottomY))
wallsRectPath.addLine(to: CGPoint(x: scaledLeftX, y: scaledBottomY))
wallsRectPath.close()
ctx.saveGState()
ctx.setLineWidth(CGFloat(mmToPoints(1.5)))
ctx.setLineCap(.round)
ctx.setLineJoin(.round)
ctx.setStrokeColor(wallCGColor)
ctx.setAlpha(0.5)
ctx.addPath(wallsRectPath.cgPath)
ctx.strokePath()
ctx.restoreGState()
}
func drawBackground(ctx: CGContext, startPoint: SDVectorModel) {
let w = Float(backgroundCGImage.width)
let h = Float(backgroundCGImage.height)
let x = -Float(mmToPoints(CGFloat(startPoint.x))).truncatingRemainder(dividingBy: w) - w
let y = -Float(mmToPoints(CGFloat(startPoint.y))).truncatingRemainder(dividingBy: h) - h
let targetRect = CGRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(w), height: CGFloat(h))
ctx.draw(convertedBackgroundImage!, in: targetRect, byTiling: true)
}
func drawEye(ctx: CGContext, position: SDVectorModel) {
let whiteRegionSize = mmToPoints(1.4)
let blackRegionSize = mmToPoints(0.6)
ctx.saveGState()
ctx.setFillColor(whiteCGColor)
ctx.fillEllipse(in: CGRect(x: mmToPoints(CGFloat(position.x)) - whiteRegionSize / 2,
y: mmToPoints(CGFloat(position.y)) - whiteRegionSize / 2, width: whiteRegionSize, height: whiteRegionSize))
ctx.setFillColor(blackCGColor)
ctx.fillEllipse(in: CGRect(x: mmToPoints(CGFloat(position.x)) - blackRegionSize / 2,
y: mmToPoints(CGFloat(position.y)) - blackRegionSize / 2, width: blackRegionSize, height: blackRegionSize))
ctx.restoreGState()
}
func drawBonus(ctx: CGContext, bonus: SDBonusModel) {
var bonusRegionSize: CGFloat = mmToPoints(2)
ctx.saveGState()
for i in 1...3 {
// эмулируем LightingColorFilter из android
var adjustedCol: UIColor = UIColor()
adjustedCol = UIColor(red: CGFloat(bonus.color.red) / 255.0 * CGFloat(128 + i * 40) / 255,
green: CGFloat(bonus.color.green) / 255.0 * CGFloat(128 + i * 30) / 255,
blue: CGFloat(bonus.color.blue) / 255.0 * CGFloat(128 + i * 30) / 255, alpha: 0.6)
bonusRegionSize = mmToPoints(2.0) - mmToPoints(CGFloat(0.2 * Double(i)))
ctx.setFillColor(adjustedCol.cgColor)
ctx.fillEllipse(in: CGRect(x: mmToPoints(CGFloat(bonus.position.x)) - bonusRegionSize / 2,
y: mmToPoints(CGFloat(bonus.position.y)) - bonusRegionSize / 2, width: bonusRegionSize, height: bonusRegionSize))
}
ctx.restoreGState()
}
func drawSnake(ctx: CGContext, snake: SDSnakeModel) {
let points = snake.points
if points.isEmpty {
return
}
// тело змеи
let bodyPath: UIBezierPath = UIBezierPath()
bodyPath.lineJoinStyle = .round
bodyPath.lineCapStyle = .round
bodyPath.move(to: CGPoint(x: mmToPoints(CGFloat(points[0].x)), y: mmToPoints(CGFloat(points[0].y))))
for p in points {
bodyPath.addLine(to: CGPoint(x: mmToPoints(CGFloat(p.x)), y: mmToPoints(CGFloat(p.y))))
}
ctx.saveGState()
ctx.setShadow(offset: CGSize(width: 0, height: 0), blur: 2.5, color: blackCGColor)
let cgBodyPath = bodyPath.cgPath
for i in 1...3 {
ctx.setLineWidth(mmToPoints(CGFloat(3.0 - 0.4 * Double(i))))
// эмулируем LightingColorFilter из android
let adjustedCol = UIColor(red: CGFloat(snake.color.red) / 255.0 * CGFloat(128 + i * 40) / 255,
green: CGFloat(snake.color.green) / 255.0 * CGFloat(128 + i * 30) / 255,
blue: CGFloat(snake.color.blue) / 255.0 * CGFloat(128 + i * 30) / 255, alpha: 1.0)
ctx.setStrokeColor(adjustedCol.cgColor)
ctx.addPath(cgBodyPath)
ctx.strokePath()
}
ctx.restoreGState()
// глаза змеи
drawEye(ctx: ctx, position: snake.leftEye)
drawEye(ctx: ctx, position: snake.rightEye)
}
func updateView() {
setNeedsDisplay()
}
// конвертация миллиметров в user points
func mmToPoints(_ mm: CGFloat) -> CGFloat {
let ppmm = GameCanvasView.ppi / 25.4
let pixels = mm * ppmm
return pixels / UIScreen.main.scale
}
static func screenDimensionsInMM() -> CGSize {
let nativeBoundsRect = UIScreen.main.nativeBounds
let ppmm = ppi / 25.4
let mmWidth = nativeBoundsRect.maxX / ppmm
let mmHeight = nativeBoundsRect.maxY / ppmm
return CGSize(width: mmWidth, height: mmHeight)
}
}
| gpl-3.0 | cc80f7c8b515a9f7439e64b7a6c99622 | 40.603865 | 217 | 0.609266 | 4.263366 | false | false | false | false |
edison9888/D3View | D3View/D3View/D3ScrollView.swift | 1 | 8154 | //
// D3ScrollView.swift
// Neighborhood
//
// Created by mozhenhau on 15-6-08.
// Copyright (c) 2014 mozhenhau. All rights reserved.
// 滚动图
// 使用方法:initScrollView, 修改样式用initStyle
import UIKit
enum ScrollViewStyle{
case all
case noLabel
case noBar
}
class D3ScrollView: UIView ,UIScrollViewDelegate{
var d3ImgView : UIImageView! //显示的第一张图
private var d3ScrollView : UIScrollView! //scroll
private var d3PageControl : UIPageControl! //下方的圆点
private var d3Label : UILabel! //下方的标题
private var d3MaskView : UIView! //下方的蒙版
private var myTimer:NSTimer?
var imgArr:Array<String> = [] //图片数组
var labelArr:Array<String> = [] //标题数组
var currentPage:Int = 0 //滚到哪一页,当前页
private var style:ScrollViewStyle = ScrollViewStyle.all
var local:Bool = false //是不是用本地图
override func layoutSubviews() {
//调整各部件位置大小
d3ImgView.frame = CGRectMake(0,0,self.frame.width,self.frame.height)
d3ScrollView.frame = CGRectMake(0,0,self.frame.width,self.frame.height)
d3Label.frame = CGRectMake(10,self.frame.height-30,self.frame.width-100,30)
d3PageControl.frame = CGRectMake(0,self.frame.height-30,100,30)
d3PageControl.center.x = self.frame.width/2
d3MaskView.frame = CGRectMake(0,self.frame.height-30,self.frame.width,30)
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
//默认样式
d3ImgView = UIImageView(image: UIImage(named:""))
self.contentMode = UIViewContentMode.ScaleAspectFit
self.clipsToBounds = true
d3ScrollView = UIScrollView()
d3ScrollView.pagingEnabled = true
d3ScrollView!.delegate = self
d3ScrollView.scrollEnabled = true
d3Label = UILabel()
d3Label.font = UIFont.systemFontOfSize(14)
d3Label.textColor = UIColor.whiteColor()
d3PageControl = UIPageControl()
d3MaskView = UIView()
d3MaskView.backgroundColor = UIColor(red: 0.0 , green: 0.0, blue: 0.0, alpha: 0.6)
addSubview(d3ImgView)
addSubview(d3ScrollView)
addSubview(d3MaskView)
addSubview(d3Label)
addSubview(d3PageControl)
}
func initScrollView(imgs:Array<String>?,labels:Array<String>?,style:ScrollViewStyle)
{
self.imgArr = imgs!
self.labelArr = labels!
initStyle(style)
if myTimer != nil
{
myTimer?.invalidate()
myTimer = nil
}
//imgView 首先显示第一张图
if imgArr.count > 0{
getImg(d3ImgView, img: imgArr[0])
}
if labelArr.count > 0{
d3Label.text = labelArr[0]
}
//只有一张图就可以结束了,不用划动
if imgArr.count <= 1
{
d3PageControl!.numberOfPages = 0
}
else{
//scrollView 可移动范围3个宽度
d3ScrollView!.contentSize = CGSizeMake(self.frame.size.width * 3,self.frame.size.height)
//scrollView 第二个宽度居中
d3ScrollView!.contentOffset = CGPointMake(self.frame.size.width, 0)
//pagecontrol 有多少张图就多少个点
d3PageControl!.numberOfPages = imgArr.count
d3PageControl!.pageIndicatorTintColor = UIColor.lightGrayColor()
d3PageControl!.currentPageIndicatorTintColor = UIColor(red: 153/255, green: 201/255, blue: 47/255, alpha: 1)
myTimer = NSTimer.scheduledTimerWithTimeInterval(5, target:self, selector:"autoSlide", userInfo:nil, repeats:true)
}
}
func initStyle(style:ScrollViewStyle){
self.style = style
switch(style){
case .noLabel:
d3Label.hidden = true
case .noBar:
d3MaskView.hidden = true
d3Label.hidden = true
default:
break
}
}
func start()
{
if myTimer != nil
{
myTimer!.fireDate = NSDate().dateByAddingTimeInterval(5)
}
}
func stop()
{
if myTimer != nil
{
myTimer!.fireDate = NSDate.distantFuture() as! NSDate
}
}
//scrollView 开始手动滚动调用的方法
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.stop()
d3ImgView.image = nil
//总页数
let totalPage:Int = imgArr.count
//当前图片如果是第一张,则左边图片为最后一张,否则为上一张
let imgView1:String = imgArr[(currentPage == 0 ? (totalPage - 1) : (currentPage - 1))]
//当前图片
let imgView2:String = imgArr[currentPage]
//当前图片如果是最后一张,则右边图片为第一张,否则为下一张
let imgView3:String = imgArr[(currentPage == (totalPage - 1) ? 0 : (currentPage + 1))]
var scrollImgArr:Array<String> = [imgView1,imgView2,imgView3]
for i:Int in 0..<3
{
let imgView:UIImageView = UIImageView()
imgView.frame = CGRectMake(CGFloat(i)*self.frame.size.width,0,self.frame.size.width,self.frame.size.height)
getImg(imgView, img: scrollImgArr[i])
d3ScrollView!.addSubview(imgView)
}
}
//scrollView 手动滚动停止调用的方法
func scrollViewDidEndDecelerating(scrollView: UIScrollView)
{
turnPage()
self.start()
}
//scrollView 开始自动滚动调用的方法
func autoSlide()
{
scrollViewWillBeginDragging(d3ScrollView)
//代码模拟 用手向右拉了一个 scrollView 的宽度
d3ScrollView!.setContentOffset(CGPointMake(d3ScrollView!.frame.size.width*2,0),animated: true)
}
//scrollView 自动滚动停止调用的方法
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView)
{
turnPage()
self.start()
}
//换页时候调用的方法
func turnPage()
{
let totalPage:Int = imgArr.count
//如果 scrollView 的 x 坐标大于320,即已经向右换一页
//并且判断当前页是否最后一页,如果是则下一页为第一张图
if d3ScrollView!.contentOffset.x > d3ScrollView!.frame.size.width
{
currentPage = (currentPage < (totalPage - 1) ? (currentPage + 1) : 0)
}
else if d3ScrollView!.contentOffset.x < d3ScrollView!.frame.size.width
{
currentPage = (currentPage > 0 ? (currentPage - 1) : (totalPage - 1))
}
//换页后mainImgView 显示改图片,并且显示该页标题
var img:String = imgArr[currentPage]
getImg(d3ImgView, img: img)
if !d3Label.hidden{
d3Label.text = labelArr[currentPage]
}
d3PageControl!.currentPage = currentPage
//把临时加进去的 imgView 从 scrollView 删除,释放内存
for imgView:AnyObject in d3ScrollView!.subviews
{
if imgView is UIImageView
{
(imgView as! UIImageView).removeFromSuperview()
}
}
//scrollView重新摆回第二个页面在中间状态
d3ScrollView!.contentOffset = CGPointMake(d3ScrollView!.frame.size.width,0)
}
private func getImg(imgView:UIImageView,img:String){
if !local{
//TODO: 自行替换加载图的方式
imgView.image = UIImage(data: NSData(contentsOfURL: NSURL(string:img)!)!)
// imgView.loadImage(img)
imgView.contentMode = UIViewContentMode.ScaleAspectFit
imgView.clipsToBounds = true
}
else{
imgView.image = UIImage(named:img)
}
}
} | mit | a3bcc3aec4cc40af2e57330bf7e99ca6 | 29.561475 | 126 | 0.585703 | 4.191119 | false | false | false | false |
gyro-n/PaymentsIos | GyronPayments/Classes/Resources/CancelResource.swift | 1 | 6889 | //
// CancelResource.swift
// GyronPayments
//
// Created by David Ye on 2017/08/31.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
import PromiseKit
/**
CancelListRequestData is a class that defines the request pararmeters that is used to get a list of cancel objects.
*/
open class CancelListRequestData: ExtendedAnyObject, RequestDataDelegate, SortRequestDelegate, PaginationRequestDelegate {
/**
The sort order for the list (ASC or DESC)
*/
public var sortOrder: String?
/**
The property name to sort by
*/
public var sortBy: String?
/**
The desired page no
*/
public var page: Int?
/**
The desired page size of the returning data set
*/
public var pageSize: Int?
public init(sortOrder: String? = nil,
sortBy: String? = "created_on",
page: Int? = nil,
pageSize: Int? = nil) {
self.sortOrder = sortOrder
self.sortBy = sortBy
self.page = page
self.pageSize = pageSize
}
public func convertToMap() -> RequestData {
return convertToRequestData()
}
}
/**
CancelCreateRequestData is a class that defines the request pararmeters that is used to create a cancel object.
*/
open class CancelCreateRequestData: ExtendedAnyObject, RequestDataDelegate {
public var metadata: Metadata?
public init(metadata: Metadata? = nil) {
self.metadata = metadata
}
public func convertToMap() -> RequestData {
return convertToRequestData()
}
}
/**
CancelUpdateRequestData is a class that defines the request pararmeters that is used to update a cancel object.
*/
open class CancelUpdateRequestData: ExtendedAnyObject, RequestDataDelegate {
public var status: String?
public var metadata: Metadata?
public init(status: CancelStatus? = nil,
metadata: Metadata? = nil) {
self.status = status?.rawValue
self.metadata = metadata
}
public func convertToMap() -> RequestData {
return convertToRequestData()
}
}
/**
The CancelResource class is used to perform operations related to the management of charge cancelations.
*/
open class CancelResource: BaseResource {
/**
The base root path for the request url
*/
let basePath: String = ""
/**
Gets the parameters to be appended to the end of the base url
*/
public func getPathParams(storeId: String?, chargeId: String?, cancelId: String?) -> PathParamsData? {
var pathParams: PathParamsData? = nil
if let sId = storeId {
let cId = chargeId ?? ""
let id = cancelId ?? ""
pathParams = PathParamsData([("stores", sId), ("charges", cId), ("cancels",id)])
}
return pathParams
}
///---------------------------
/// @name Routes
///---------------------------
/**
Lists the cancels available based on the store and charge ids.
@param storeId the store id
@param storeId the charge id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the Cancels list
*/
public func list(storeId: String, chargeId: String, data: CancelListRequestData?, callback: ResponseCallback<Cancels>?) -> Promise<Cancels> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, chargeId: chargeId, cancelId: nil)
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: basePath, pathParams: pathParams, data: data, callback: callback)
}
/**
Get a cancel based on the store, charge and cancel ids.
@param storeId the store id
@param storeId the charge id
@param id the cancel id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the Cancel object
*/
public func get(storeId: String, chargeId: String, id: String, callback: ResponseCallback<Cancel>?) -> Promise<Cancel> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, chargeId: chargeId, cancelId: id)
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: basePath, pathParams: pathParams, data: nil, callback: callback)
}
/**
Create a cancel based on the store and charge ids.
@param storeId the store id
@param chargeId the charge id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the Cancel object
*/
public func create(storeId: String, chargeId: String, data: CancelCreateRequestData?, callback: ResponseCallback<Cancel>?) -> Promise<Cancel> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, chargeId: chargeId, cancelId: nil)
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.POST, path: basePath, pathParams: pathParams, data: data, callback: callback)
}
/**
Update a cancel based on the store, charge and cancel ids.
@param storeId the store id
@param chargeId the charge id
@param id the cancel id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the Cancel object
*/
public func update(storeId: String?, chargeId: String, id: String, data: CancelUpdateRequestData?, callback: ResponseCallback<Cancel>?) -> Promise<Cancel> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, chargeId: chargeId, cancelId: id)
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.PATCH, path: basePath, pathParams: pathParams, data: data, callback: callback)
}
public func poll(storeId: String, chargeId: String, id: String, callback: ResponseCallback<Cancel>?) -> Promise<Cancel> {
let pathParams: PathParamsData? = self.getPathParams(storeId: storeId, chargeId: chargeId, cancelId: id)
let condition: LongPollCondition<Cancel> = { d in
d.status != CancelStatus.pending
}
return self.performPoll(requiredParams: [],
method: HttpProtocol.HTTPMethod.GET,
path: basePath,
pathParams: pathParams,
data: nil,
condition: condition,
callback: callback)
}
}
| mit | 0cbd66768be998ea5b0ffe5597ff4be5 | 36.639344 | 160 | 0.646922 | 4.937634 | false | false | false | false |
dasdom/BreakOutToRefresh | Example/PullToRefreshDemo/DemoTableViewController.swift | 1 | 2474 | //
// DemoTableViewController.swift
// PullToRefreshDemo
//
// Created by dasdom on 17.01.15.
// Copyright (c) 2015 Dominik Hauser. All rights reserved.
//
import UIKit
import BreakOutToRefresh
class DemoTableViewController: UITableViewController {
var refreshView: BreakOutToRefreshView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DemoCell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshView = BreakOutToRefreshView(scrollView: tableView)
refreshView.refreshDelegate = self
// configure the refresh view
refreshView.scenebackgroundColor = .white
refreshView.textColor = .black
refreshView.paddleColor = .brown
refreshView.ballColor = .darkGray
refreshView.blockColors = [.blue, .green, .red]
tableView.addSubview(refreshView)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
refreshView.removeFromSuperview()
refreshView = nil
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DemoCell", for: indexPath)
cell.textLabel?.text = "Row \((indexPath as NSIndexPath).row)"
return cell
}
}
extension DemoTableViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
refreshView.scrollViewDidScroll(scrollView)
}
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
refreshView.scrollViewWillEndDragging(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
refreshView.scrollViewWillBeginDragging(scrollView)
}
}
extension DemoTableViewController: BreakOutToRefreshDelegate {
func refreshViewDidRefresh(_ refreshView: BreakOutToRefreshView) {
// this code is to simulage the loading from the internet
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(NSEC_PER_SEC * 10)) / Double(NSEC_PER_SEC), execute: { () -> Void in
refreshView.endRefreshing()
})
}
}
| mit | be2c74944a50d656f7c3237db69e4f09 | 28.105882 | 154 | 0.755861 | 4.803883 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/Pods/SkeletonView/Sources/Collections/TableViews/UITableView+CollectionSkeleton.swift | 1 | 2226 | //
// UITableView+CollectionSkeleton.swift
// SkeletonView-iOS
//
// Created by Juanpe Catalán on 02/02/2018.
// Copyright © 2018 SkeletonView. All rights reserved.
//
import UIKit
extension UITableView: CollectionSkeleton {
var estimatedNumberOfRows: Int {
return Int(ceil(frame.height/rowHeight))
}
var skeletonDataSource: SkeletonCollectionDataSource? {
get { return ao_get(pkey: &CollectionAssociatedKeys.dummyDataSource) as? SkeletonCollectionDataSource }
set {
ao_setOptional(newValue, pkey: &CollectionAssociatedKeys.dummyDataSource)
self.dataSource = newValue
}
}
var skeletonDelegate: SkeletonCollectionDelegate? {
get { return ao_get(pkey: &CollectionAssociatedKeys.dummyDelegate) as? SkeletonCollectionDelegate }
set {
ao_setOptional(newValue, pkey: &CollectionAssociatedKeys.dummyDelegate)
self.delegate = newValue
}
}
func addDummyDataSource() {
guard let originalDataSource = self.dataSource as? SkeletonTableViewDataSource,
!(originalDataSource is SkeletonCollectionDataSource)
else { return }
let rowHeight = calculateRowHeight()
let dataSource = SkeletonCollectionDataSource(tableViewDataSource: originalDataSource,
rowHeight: rowHeight)
self.skeletonDataSource = dataSource
reloadData()
}
func removeDummyDataSource(reloadAfter: Bool) {
guard let dataSource = self.dataSource as? SkeletonCollectionDataSource else { return }
restoreRowHeight()
self.skeletonDataSource = nil
self.dataSource = dataSource.originalTableViewDataSource
if reloadAfter { self.reloadData() }
}
private func restoreRowHeight() {
guard let dataSource = self.dataSource as? SkeletonCollectionDataSource else { return }
rowHeight = dataSource.rowHeight
}
private func calculateRowHeight() -> CGFloat {
guard rowHeight == UITableView.automaticDimension else { return rowHeight }
rowHeight = estimatedRowHeight
return estimatedRowHeight
}
}
| mit | b87b114a3ca5c53df9e987850b8274e8 | 34.870968 | 111 | 0.671763 | 5.63038 | false | false | false | false |
naebada-dev/swift | language-guide/Tests/language-guideTests/typecasting/TypeCastingTests.swift | 1 | 5864 | import XCTest
class TypeCastingTests : XCTestCase {
override func setUp() {
super.setUp();
print("############################");
}
override func tearDown() {
print("############################");
super.tearDown();
}
/*
Type Casting
타입 캐스팅은 인스턴스의 타입을 검사히기 방법이다.
즉, 그 인스턴스를 클래스 계층에서 다른 슈퍼클래스나 서브클래스로써 다룬다.
스위프트에서 타입 캐스팅은 is 와 as 와 함께 구현된다.
타입 캐스팅은 타입이 프로토콜을 준수하는지 검사하는데도 사용된다.
*/
// Defining a Class Hierarchy for Type Casting
private class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
private class Movie : MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
private class Song : MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
private let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
/*
Checking Type
타입 검사(is)를 인스턴스가 어떤 서브클래스의 타입인지 검사하는데 사용하여라.
그 인스턴스가 그 서브클래스이면 타입 검사는 true를 반환하고, 그렇지 않으면 false를 반환한다.
*/
func testTypeCastCheckingType() {
var movieCount = 0
var songCount = 0
for item in library {
// 어떤 subclass인지 검사하기 위해 type check operator(is) 사용
// instance가 검사하려는 subclass가 맞으면 true 반환
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
print("Media library contains \(movieCount) movies and \(songCount) songs")
}
/*
Downcasting
확실한 클래스 타입의 val 또는 var는 실제로 서브클래스의 인스턴스를 참조할지도 모른다.
만약 이런 상황이라면 타입 캐스트 연산자(as? 또는 as!)를 이용해서 다운캐스트를 할 수 있다.
다운캐스트는 실패할수 있기 때문에, 타입 캐스트는 두가지 다른 형태를 제공한다.
조건 형태(as?)는 다운캐스트를 시도한 타입의 옵션널 값을 반환한다.
강제 형태(as!)는 다운캐스트와 강제풀기(force-unwrap)을 한번에 수행한다.
만약 다운캐스트가 성공할지 불확실할 때 조건 형태(as?)를 사용하라.
as?는 항상 옵션널 값을 반활 할것이고, 다운캐스트가 불가능하다면 nil을 반환할 것이다.
다운캐스트가 항상 성공할 것이라고 확신한다면 강제형태(as!)를 사용하라.
그러나 만약 타운캐스트가 실패하거나 부적절한 클래스타입으로 시도한다면 런타임 오류가 발생할 것이다.
*/
func testTypeCastDowncast() {
for item in library {
// optional binding
if let movie = item as? Movie {
print("Movie: \(movie.name), dir. \(movie.director)")
} else if let song = item as? Song {
print("Song: \(song.name), by \(song.artist)")
}
}
}
/*
Type Casting for Any and AnyObject
스위프트는 특별한 2개의 타입을 제공한다.
- Any: 함수 타입을 포함한 모든 타입의 인스턴스
- AnyObject: 클래스 타입의 인스턴스
*/
func testTypeAny() {
var things = [Any]()
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" })
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
print("a positive double value of \(someDouble)")
case is Double:
print("some other double value that I don't want to print")
case let someString as String:
print("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
print("an (x, y) point at \(x), \(y)")
case let movie as Movie:
print("a movie called \(movie.name), dir. \(movie.director)")
case let stringConverter as (String) -> String:
print(stringConverter("Michael"))
default:
print("something else")
}
}
}
/*
option value를 Any type으로 사용하기 위해서 as operator를 명시적으로 사용하여 casting 하라.
let optionalNumber: Int? = 3
things.append(optionalNumber) // Warning
things.append(optionalNumber as Any) // No warning
*/
}
| apache-2.0 | 598c3c538a86a37dde40c102214df380 | 27.452381 | 83 | 0.53159 | 3.431443 | false | false | false | false |
societymedia/SwiftyContainer | Pods/Nimble/Nimble/DSL.swift | 15 | 2256 | import Foundation
/// Make an expectation on a given actual value. The value given is lazily evaluated.
public func expect<T>(@autoclosure(escaping) expression: () throws -> T?, file: String = __FILE__, line: UInt = __LINE__) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Make an expectation on a given actual value. The closure is lazily invoked.
public func expect<T>(file: String = __FILE__, line: UInt = __LINE__, expression: () throws -> T?) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Always fails the test with a message and a specified location.
public func fail(message: String, location: SourceLocation) {
let handler = NimbleEnvironment.activeInstance.assertionHandler
handler.assert(false, message: FailureMessage(stringValue: message), location: location)
}
/// Always fails the test with a message.
public func fail(message: String, file: String = __FILE__, line: UInt = __LINE__) {
fail(message, location: SourceLocation(file: file, line: line))
}
/// Always fails the test.
public func fail(file: String = __FILE__, line: UInt = __LINE__) {
fail("fail() always fails", file: file, line: line)
}
/// Like Swift's precondition(), but raises NSExceptions instead of sigaborts
internal func nimblePrecondition(
@autoclosure expr: () -> Bool,
@autoclosure _ name: () -> String,
@autoclosure _ message: () -> String) -> Bool {
let result = expr()
if !result {
let e = NSException(
name: name(),
reason: message(),
userInfo: nil)
e.raise()
}
return result
}
@noreturn
internal func internalError(msg: String, file: String = __FILE__, line: UInt = __LINE__) {
fatalError(
"Nimble Bug Found: \(msg) at \(file):\(line).\n" +
"Please file a bug to Nimble: https://github.com/Quick/Nimble/issues with the " +
"code snippet that caused this error."
)
} | apache-2.0 | 30139863ffe7f7a89207e752fd53b638 | 36.616667 | 141 | 0.628546 | 4.288973 | false | true | false | false |
LittleLin/SwiftZhConverter | SwiftZhConverter/TraditionalZhConverter.swift | 1 | 1046 | //
// TraditionalZhConverter.swift
// SwiftZhConverter
//
import Foundation
public class TraditionalZhConverter : ZhConverter {
public init() {
}
public func convert(rawText: String) -> String {
var location = NSBundle(identifier: "SwiftZhConverter")?.resourcePath!.stringByAppendingString("/word_s2t.txt")
var mappingTable = Dictionary<Character, Character>();
if let var reader = StreamReader(path: location!) {
while let line = reader.nextLine() {
var tokens = split(line) {$0 == ","}
var token1 = tokens[0]
var token2 = tokens[1]
mappingTable[token1[0]] = token2[0]
}
}
var newText = "";
for char in rawText {
if let tc = mappingTable[char] {
var buf = mappingTable[char]
newText.append(tc);
} else {
newText.append(char)
}
}
return newText;
}
} | mit | b33ce63fd44be214f0d3683bb5e5d4ce | 26.552632 | 119 | 0.51912 | 4.690583 | false | false | false | false |
icapps/ios_objective_c_workshop | Teacher/ObjcTextInput/Pods/Faro/Sources/Request/Call.swift | 2 | 6111 | public enum HTTPMethod: String {
case GET, POST, PUT, DELETE, PATCH
}
public enum CallError: Error, CustomDebugStringConvertible {
case invalidUrl(String, call: Call)
case malformed(info: String)
public var debugDescription: String {
switch self {
case .invalidUrl(let url):
return "📡🔥invalid url: \(url)"
case .malformed(let info):
return "📡🔥 \(info)"
}
}
}
/// Defines a request that will be called in the DeprecatedService
/// You can add `[Parameter]` to the request and optionally authenticate the request when needed.
/// Optionally implement `Authenticatable` to make it possible to authenticate requests
open class Call {
open let path: String
open let httpMethod: HTTPMethod
open var parameters = [Parameter]()
fileprivate var request: URLRequest?
/// Initializes Call to retreive object(s) from the server.
/// parameter path: the path to point the call too
/// parameter method: the method to use for the urlRequest
/// parameter parameter: array of parameters to be added to the request when created.
public init(path: String, method: HTTPMethod = .GET, parameter: [Parameter]? = nil) {
self.path = path
self.httpMethod = method
if let parameters = parameter {
self.parameters = parameters
}
}
/// Makes a request from this call every time. This is done to every service call has its own request and can change time dependend parameters, like authorization.
/// Optionally implement `Authenticatable` to make it possible to authenticate requests. In this function on self the functions in 'Authenticatable` will be called.
open func request(with configuration: BackendConfiguration) -> URLRequest? {
var request = URLRequest(url: URL(string: "\(configuration.baseURLString)/\(path)")!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData) // uses default timeout
self.request = request
request.httpMethod = httpMethod.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
insertParameter(request: &request)
if let authenticatableSelf = self as? Authenticatable {
authenticatableSelf.authenticate(&request)
}
return request
}
/// Called when creating a request.
open func insertParameter(request: inout URLRequest) {
parameters.forEach {
do {
switch $0 {
case .httpHeader(let headers):
insertInHeaders(with: headers, request: &request)
case .urlComponentsInURL(let components):
insertInUrl(with: components, request: &request)
case .jsonNode(let json):
try insertInBodyInJson(with: json, request: &request)
case .jsonArray(let jsonArray):
try insertInBodyInJson(with: jsonArray, request: &request)
case .multipart(let multipart):
try insertMultiPartInBody(with: multipart, request: &request)
case .urlComponentsInBody(let components):
try insertInBodyAsURLComponents(with: components, request: &request)
case .encodedData(let data):
try insertInBody(data: data, request: &request)
}
} catch {
print(error)
}
}
}
private func insertInHeaders(with headers: [String: String], request: inout URLRequest) {
for (key, value) in headers {
request.setValue(value, forHTTPHeaderField: key)
}
}
private func insertInUrl(with componentsDict: [String: String], request: inout URLRequest) {
guard componentsDict.values.count > 0 else {
return
}
var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)
if (components?.queryItems == nil) {
components?.queryItems = [URLQueryItem]()
}
let sortedComponents = componentsDict.sorted(by: { $0.0 < $1.0 })
for (key, value) in sortedComponents {
components?.queryItems?.append(URLQueryItem(name: key, value: value))
}
request.url = components?.url
}
private func insertInBodyInJson(with json: Any, request: inout URLRequest) throws {
if request.httpMethod == HTTPMethod.GET.rawValue {
throw CallError.malformed(info: "HTTP " + request.httpMethod! + " request can't have a body")
}
request.httpBody = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
}
private func insertInBody(data: Data, request: inout URLRequest) throws {
if request.httpMethod == HTTPMethod.GET.rawValue {
throw CallError.malformed(info: "HTTP " + request.httpMethod! + " request can't have a body")
}
request.httpBody = data
}
private func insertInBodyAsURLComponents(with dict: [String: String], request: inout URLRequest) throws {
if request.httpMethod == HTTPMethod.GET.rawValue {
throw CallError.malformed(info: "HTTP " + request.httpMethod! + " request can't have a body")
}
request.httpBody = dict.queryParameters.data(using: .utf8)
}
private func insertMultiPartInBody(with multipart: MultipartFile, request: inout URLRequest) throws {
guard request.httpMethod != HTTPMethod.GET.rawValue else {
throw CallError.malformed(info: "HTTP " + request.httpMethod! + " request can't have a body")
}
let boundary = "Boundary-iCapps-Faro"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = createMultipartBody(with: multipart, boundary: boundary)
}
private func createMultipartBody(with multipart: MultipartFile, boundary: String) -> Data {
let boundaryPrefix = "--\(boundary)\r\n"
var body = Data()
body.appendString(boundaryPrefix)
body.appendString("Content-Disposition: form-data; name=\"\(multipart.parameterName)\"; filename=\"\(multipart.parameterName)\"\r\n")
body.appendString("Content-Type: \(multipart.mimeType)\r\n\r\n")
body.append(multipart.data)
body.appendString("\r\n")
body.appendString("\(boundaryPrefix)--\r\n")
return body
}
}
// MARK: - CustomDebugStringConvertible
extension Call: CustomDebugStringConvertible {
public var debugDescription: String {
let parameterString: String = parameters.reduce("Parameters", {"\($0)\n\($1)"})
return "Call \(request?.url?.absoluteString ?? "")\n• parameters: \(parameterString)"
}
}
| mit | 004196c18778ef1d3ad08b21b3a26e6b | 37.588608 | 165 | 0.718222 | 4.080991 | false | false | false | false |
NijiDigital/NetworkStack | Example/MoyaComparison/MoyaComparison/Models/Parser/JSONCodable/Video+JSONCodable.swift | 1 | 2411 | //
// Copyright 2017 niji
//
// 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 JSONCodable
import class JSONCodable.JSONEncoder
extension Video: JSONCodable {
convenience init(object: JSONObject) throws {
self.init()
let decoder = JSONDecoder(object: object)
// Attributes
self.identifier = try decoder.decode(Attributes.identifier)
self.title = try decoder.decode(Attributes.title)
self.creationDate = try decoder.decode(Attributes.creationDate, transformer: JSONTransformers.StringToDate)
self.likeCounts = try decoder.decode(Attributes.likeCounts)
self.hasSponsors.value = try decoder.decode(Attributes.hasSponsors)
self.statusCode.value = try decoder.decode(Attributes.statusCode)
// RelationShips
let relatedVideosSandbox: [Video] = try decoder.decode(Relationships.relatedVideos)
self.relatedVideos.append(objectsIn: relatedVideosSandbox)
}
func toJSON() throws -> JSONObject {
return try JSONEncoder.create({ (encoder: JSONEncoder) in
try encoder.encode(self.identifier, key: Attributes.identifier)
try encoder.encode(self.title, key: Attributes.title)
try encoder.encode(self.creationDate, key: Attributes.creationDate, transformer: JSONTransformers.StringToDate)
try encoder.encode(self.likeCounts, key: Attributes.likeCounts)
try encoder.encode(self.hasSponsors.value, key: Attributes.hasSponsors)
try encoder.encode(self.statusCode.value, key: Attributes.statusCode)
let relatedVideosSandbox: [Video] = Array(self.relatedVideos)
try encoder.encode(relatedVideosSandbox, key: Relationships.relatedVideos)
})
}
}
public struct JSONTransformers {
public static let StringToDate = JSONTransformer<String, Date?>(
decoding: {DateFormatter.iso8601Formatter.date(from: $0)},
encoding: {DateFormatter.iso8601Formatter.string(from: $0 ?? Date())})
}
| apache-2.0 | e7c2a3c7d89020421d42df6cb95b590c | 42.836364 | 117 | 0.754873 | 4.274823 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.