repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nvzqz/Sage
|
refs/heads/develop
|
Sources/Rank.swift
|
apache-2.0
|
1
|
//
// Rank.swift
// Sage
//
// Copyright 2016-2017 Nikolai Vazquez
//
// 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.
//
/// A chess board rank.
///
/// `Rank`s refer to the eight rows of a chess board, beginning with 1 at the bottom and ending with 8 at the top.
public enum Rank: Int, Comparable, CustomStringConvertible {
/// A direction in rank.
public enum Direction {
#if swift(>=3)
/// Up direction.
case up
/// Down direction.
case down
#else
/// Up direction.
case Up
/// Down direction.
case Down
#endif
}
#if swift(>=3)
/// Rank 1.
case one = 1
/// Rank 2.
case two = 2
/// Rank 3.
case three = 3
/// Rank 4.
case four = 4
/// Rank 5.
case five = 5
/// Rank 6.
case six = 6
/// Rank 7.
case seven = 7
/// Rank 8.
case eight = 8
#else
/// Rank 1.
case One = 1
/// Rank 2.
case Two = 2
/// Rank 3.
case Three = 3
/// Rank 4.
case Four = 4
/// Rank 5.
case Five = 5
/// Rank 6.
case Six = 6
/// Rank 7.
case Seven = 7
/// Rank 8.
case Eight = 8
#endif
}
extension Rank {
/// An array of all ranks.
public static let all: [Rank] = [1, 2, 3, 4, 5, 6, 7, 8]
/// The row index of `self`.
public var index: Int {
return rawValue - 1
}
/// A textual representation of `self`.
public var description: String {
return String(rawValue)
}
/// Create an instance from an integer value.
public init?(_ value: Int) {
self.init(rawValue: value)
}
/// Create a `Rank` from a zero-based row index.
public init?(index: Int) {
self.init(rawValue: index + 1)
}
/// Creates the starting `Rank` for the color.
public init(startFor color: Color) {
self = color.isWhite ? 1 : 8
}
/// Creates the ending `Rank` for the color.
public init(endFor color: Color) {
self = color.isWhite ? 8 : 1
}
/// Returns a rank from advancing `self` by `value` with respect to `color`.
public func advanced(by value: Int, for color: Color = ._white) -> Rank? {
return Rank(rawValue: rawValue + (color.isWhite ? value : -value))
}
/// The next rank after `self`.
public func next() -> Rank? {
return Rank(rawValue: (rawValue + 1))
}
/// The previous rank to `self`.
public func previous() -> Rank? {
return Rank(rawValue: (rawValue - 1))
}
/// The opposite rank of `self`.
public func opposite() -> Rank {
return Rank(rawValue: 9 - rawValue)!
}
/// The files from `self` to `other`.
public func to(_ other: Rank) -> [Rank] {
return _to(other)
}
/// The files between `self` and `other`.
public func between(_ other: Rank) -> [Rank] {
return _between(other)
}
}
#if swift(>=3)
extension Rank: ExpressibleByIntegerLiteral { }
#else
extension Rank: IntegerLiteralConvertible { }
#endif
extension Rank {
/// Create an instance initialized to `value`.
public init(integerLiteral value: Int) {
guard let rank = Rank(rawValue: value) else {
fatalError("Rank value not within 1 and 8, inclusive")
}
self = rank
}
}
/// Returns `true` if one rank is higher than the other.
public func < (lhs: Rank, rhs: Rank) -> Bool {
return lhs.rawValue < rhs.rawValue
}
|
e8dcaff190132fca34557b0673b8b8fc
| 19.953125 | 114 | 0.573453 | false | false | false | false |
taoalpha/XMate
|
refs/heads/vsync
|
appcode/X-Mates/ProfileViewController.swift
|
mit
|
1
|
//
// ProfileViewController.swift
// X-Mates
//
// Created by Jiangyu Mao on 3/5/16.
// Copyright ยฉ 2016 CloudGroup. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import CoreLocation
class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var email: UITextField!
private let SUCCESSE_STATUS = "1"
private let userURL = "http://192.168.99.100:4000/user/"
private let tableData = ["Gender", "Birthdate", "Height", "Weight"]
private let feetList = ["0'", "1'", "2'", "3'", "4'", "5'", "6'", "7'"]
private let inchList = ["0\"", "1\"", "2\"", "3\"", "4\"", "5\"", "6\"", "7\"", "8\"", "9\"", "10\"", "11\"", "12\""]
private let weightList = ["90 - 110 lbs", "110 - 130 lbs", "130 - 150 lbs", "150 - 170 lbs", "170 - 190 lbs", "190 - 210 lbs"]
private let normWeight = ["100", "120", "140", "160", "180", "200"]
private let heightPicker = UIPickerView(frame: CGRectMake(25, 0, 305, 200))
private let weightPicker = UIPickerView(frame: CGRectMake(25, 0, 305, 200))
private var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
private var gender = "Male"
private var birthday = ""
private var height = "0' 0\""
private var weight = "90 - 110 lbs"
override func viewDidLoad() {
super.viewDidLoad()
// self.firstName.text = self.appDelegate.xmate.user["first_name"] as? String
// self.lastName.text = self.appDelegate.xmate.user["last_name"] as? String
// self.email.text = self.appDelegate.xmate.user["email"] as? String
}
override func viewDidAppear(animated: Bool) {
print(self.appDelegate.xmate.user)
self.firstName.text = self.appDelegate.xmate.user["first_name"] as? String
self.lastName.text = self.appDelegate.xmate.user["last_name"] as? String
self.email.text = self.appDelegate.xmate.user["email"] as? String
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.tableData[indexPath.row], forIndexPath: indexPath)
let index = indexPath.row
cell.textLabel?.text = self.tableData[index]
if index == 0
{
cell.detailTextLabel?.text = self.appDelegate.xmate.user["gender"] as? String
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let index = indexPath.row
let cell = tableView.cellForRowAtIndexPath(indexPath)!
switch index
{
case 0:
genderPicker(cell)
break
case 1:
birthdatePicker(cell)
break
case 2:
heightPicker(cell)
break
case 3:
weightPicker(cell)
break
default:
break
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
if pickerView == heightPicker
{
return 2
}
else
{
return 1
}
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == heightPicker
{
if component == 0
{
return self.feetList.count
}
else
{
return self.inchList.count
}
}
else
{
return self.weightList.count
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == heightPicker
{
if component == 0
{
return self.feetList[row]
}
else
{
return self.inchList[row]
}
}
else
{
return self.weightList[row]
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == heightPicker
{
self.height = feetList[pickerView.selectedRowInComponent(0)] + " " + inchList[pickerView.selectedRowInComponent(1)]
}
else
{
self.weight = weightList[row]
}
}
func genderPicker(cell: UITableViewCell) {
let alertController = UIAlertController(title:nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let male = UIAlertAction(title: "Male", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
cell.detailTextLabel?.text = "Male"
self.gender = (cell.detailTextLabel?.text)!
})
let female = UIAlertAction(title: "Female", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
cell.detailTextLabel?.text = "Female"
self.gender = (cell.detailTextLabel?.text)!
})
alertController.addAction(male)
alertController.addAction(female)
self.presentViewController(alertController, animated: true, completion: nil)
}
func birthdatePicker(cell: UITableViewCell) {
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let datePicker = UIDatePicker(frame: CGRectMake(25, 0, 305, 200))
let formatter = NSDateFormatter()
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.date = NSDate()
formatter.dateStyle = .MediumStyle
let done = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
cell.detailTextLabel?.text = formatter.stringFromDate(datePicker.date)
self.birthday = (cell.detailTextLabel?.text)!
})
alertController.addAction(done)
alertController.view.addSubview(datePicker)
self.presentViewController(alertController, animated: true, completion: nil)
}
func weightPicker(cell: UITableViewCell) {
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
weightPicker.dataSource = self
weightPicker.delegate = self
let done = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
cell.detailTextLabel?.text = self.weight
})
alertController.addAction(done)
alertController.view.addSubview(weightPicker)
self.presentViewController(alertController, animated: true, completion: nil)
}
func heightPicker(cell: UITableViewCell) {
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
heightPicker.dataSource = self
heightPicker.delegate = self
let done = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
cell.detailTextLabel?.text = self.height
})
alertController.addAction(done)
alertController.view.addSubview(heightPicker)
self.presentViewController(alertController, animated: true, completion: nil)
}
@IBAction func goToHome(sender: UIBarButtonItem) {
self.appDelegate.xmate.user["first_name"] = firstName.text
self.appDelegate.xmate.user["last_name"] = lastName.text
self.appDelegate.xmate.user["email"] = email.text
self.appDelegate.xmate.user["gender"] = self.gender
self.appDelegate.xmate.user["birthday"] = self.birthday
self.appDelegate.xmate.user["height"] = self.height
self.appDelegate.xmate.user["weight"] = self.weight
self.appDelegate.xmate.post(self.userURL, mode: "user")
self.performSegueWithIdentifier("showHome", sender: self)
}
}
|
b78d843cae8e53f274e6c8aca2680087
| 29.508264 | 137 | 0.713531 | false | false | false | false |
KoheiHayakawa/Form
|
refs/heads/master
|
Form/KHAForm/KHATextViewFormCell.swift
|
mit
|
1
|
//
// KHATextViewCell.swift
// KHAForm
//
// Created by Kohei Hayakawa on 3/8/15.
// Copyright (c) 2015 Kohei Hayakawa. All rights reserved.
//
import UIKit
class KHATextViewFormCell: KHAFormCell {
let textView: UIPlaceholderTextView = UIPlaceholderTextView()
private let kCellHeight: CGFloat = 144
private let kFontSize: CGFloat = 16
class var cellID: String {
return "KHATextViewCell"
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
super.selectionStyle = .None
super.frame = CGRect(
x: super.frame.origin.x,
y: super.frame.origin.y,
width: super.frame.width,
height: kCellHeight)
super.contentView.addSubview(textView)
textView.font = UIFont.systemFontOfSize(kFontSize)
textView.setTranslatesAutoresizingMaskIntoConstraints(false)
// TODO: Fix constant value of left and right.
// Current value is optimized for iPhone 6.
// I don't have any good solution for this problem...
contentView.addConstraints([
NSLayoutConstraint(
item: textView,
attribute: .Left,
relatedBy: .Equal,
toItem: contentView,
attribute: .Left,
multiplier: 1,
constant: 10),
NSLayoutConstraint(
item: textView,
attribute: .Right,
relatedBy: .Equal,
toItem: contentView,
attribute: .Right,
multiplier: 1,
constant: -5),
NSLayoutConstraint(
item: textView,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: kCellHeight)]
)
}
}
class UIPlaceholderTextView: UITextView {
lazy var placeholderLabel:UILabel = UILabel()
var placeholderColor:UIColor = UIColor.lightGrayColor()
var placeholder:NSString = ""
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setText(text:NSString) {
super.text = text
self.textChanged(nil)
}
override internal func drawRect(rect: CGRect) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged:", name: UITextViewTextDidChangeNotification, object: nil)
if(self.placeholder.length > 0) {
self.placeholderLabel.frame = CGRectMake(4,8,self.bounds.size.width - 16,0)
self.placeholderLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
self.placeholderLabel.numberOfLines = 0
self.placeholderLabel.font = self.font
self.placeholderLabel.backgroundColor = UIColor.clearColor()
self.placeholderLabel.textColor = self.placeholderColor
self.placeholderLabel.alpha = 0
self.placeholderLabel.tag = 999
self.placeholderLabel.text = self.placeholder
self.placeholderLabel.sizeToFit()
self.addSubview(placeholderLabel)
}
self.sendSubviewToBack(placeholderLabel)
if(self.text.utf16Count == 0 && self.placeholder.length > 0){
self.viewWithTag(999)?.alpha = 1
}
super.drawRect(rect)
}
internal func textChanged(notification:NSNotification?) -> (Void) {
if(self.placeholder.length == 0){
return
}
if(countElements(self.text) == 0) {
self.viewWithTag(999)?.alpha = 1
}else{
self.viewWithTag(999)?.alpha = 0
}
}
}
|
c1ffa3567b53660455cfc1066300d31d
| 32.581197 | 144 | 0.577138 | false | false | false | false |
mohamede1945/quran-ios
|
refs/heads/master
|
Quran/Files.swift
|
gpl-3.0
|
1
|
//
// Files.swift
// Quran
//
// Created by Mohamed Afifi on 4/30/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
struct QuranURLs {
static var host: URL = URL(validURL: "http://android.quran.com/")
static var audioDatabaseURL: URL = host.appendingPathComponent("data/databases/audio/")
}
public struct Files {
public static let audioExtension = "mp3"
public static let downloadResumeDataExtension = "resume"
public static let databaseRemoteFileExtension = "zip"
public static let databaseLocalFileExtension = "db"
public static let databasesPathComponent = "databases"
public static let translationsPathComponent = "translations"
public static let translationCompressedFileExtension = "zip"
public static let quarterPrefixArray = fileURL("quarter_prefix_array", withExtension: "plist")
public static let readers = fileURL("readers", withExtension: "plist")
public static let ayahInfoPath: String = filePath("images_\(quranImagesSize)/databases/ayahinfo_\(quranImagesSize)", ofType: "db")
public static let quranTextPath = filePath("images_\(quranImagesSize)/databases/quran.ar", ofType: "db")
public static let databasesPath: String = FileManager.documentsPath.stringByAppendingPath(databasesPathComponent)
public static let translationsURL = FileManager.documentsURL.appendingPathComponent(translationsPathComponent)
}
private func fileURL(_ fileName: String, withExtension `extension`: String) -> URL {
guard let url = Bundle.main.url(forResource: fileName, withExtension: `extension`) else {
fatalError("Couldn't find file `\(fileName).\(`extension`)` locally ")
}
return url
}
private func filePath(_ fileName: String, ofType type: String) -> String {
guard let path = Bundle.main.path(forResource: fileName, ofType: type) else {
fatalError("Couldn't find file `\(fileName).\(type)` locally ")
}
return path
}
extension URL {
public func resumeURL() -> URL {
return appendingPathExtension(Files.downloadResumeDataExtension)
}
}
extension String {
public var resumePath: String {
return stringByAppendingExtension(Files.downloadResumeDataExtension)
}
}
|
39a72a8aa4d4e8573955e15296e2934f
| 37.708333 | 134 | 0.733764 | false | false | false | false |
MattCheetham/HarvestKit-Swift
|
refs/heads/master
|
HarvestKit-Shared/User.swift
|
mit
|
1
|
//
// Person.swift
// HarvestKit
//
// Created by Matthew Cheetham on 19/11/2015.
// Copyright ยฉ 2015 Matt Cheetham. All rights reserved.
//
import Foundation
/**
A struct representation of a user in the harvest system
*/
public struct User {
/**
A unique identifier for this User
*/
public var identifier: Int?
/**
The users first Name
*/
public var firstName: String?
/**
The users last name
*/
public var lastName: String?
/**
The users email address
*/
public var email: String?
/**
A boolean to indicate whether or not the user is active in the system. If false, this user has been deactivated
*/
public var active: Bool?
/**
A boolean to indicate whether or not the user is an admin in this system.
- note: Only populated when created from the Who Am I call
*/
public var admin: Bool?
/**
The name of the department that the user belongs to
*/
public var department: String?
/**
The timezone identifier as a string that the user has their account set to. E.g. "Europe/London"
- note: Only populated when created from the Who Am I call
*/
public var timezoneIdentifier: String?
/**
The timezone city. The harvest API doesn't give any documentation on this so I'm going to assume it always returns the city part of the `timezoneIdentifier`
- note: Only populated when created from the Who Am I call
*/
public var timezoneCity: String?
/**
A boolean indicating whether or not the user is a project manager
- note: Only populated when created from the Who Am I call
*/
public var projectManager: Bool?
/**
A boolean indicating whether or not the user can create new projects
- note: Only populated when created from the Who Am I call
*/
public var createProjects: Bool?
/**
A boolean indicating whether or not the user can see hourly rates
- note: Only populated when created from the Who Am I call
*/
public var seeRates: Bool?
/**
A boolean indicating whether or not the user can create new invoices
- note: Only populated when created from the Who Am I call
*/
public var createInvoices: Bool?
/**
The number of seconds that the user is offset from UTC with their current timezone settings
- note: Only populated when created from the Who Am I call
*/
public var timezoneOffsetSeconds: Int?
/**
No information was found about this property in the Harvest API Documentation
- note: Only populated when created from the Who Am I call
*/
public var timestampTimers: Bool?
/**
The URL to the users avatar if they have one
- note: Only populated when created from the Who Am I call
*/
public var avatarURL: NSURL?
internal init?(dictionary: [String: AnyObject]) {
guard let userDictionary = dictionary["user"] as? [String: AnyObject] else {
print("User was missing user key")
return nil
}
identifier = userDictionary["id"] as? Int
firstName = userDictionary["first_name"] as? String
lastName = userDictionary["last_name"] as? String
email = userDictionary["email"] as? String
active = userDictionary["is_active"] as? Bool
admin = userDictionary["admin"] as? Bool
department = userDictionary["department"] as? String
timezoneIdentifier = userDictionary["timezone_identifier"] as? String
timezoneCity = userDictionary["timezone"] as? String
if let projectManagerDictionary = userDictionary["project_manager"] as? [String: AnyObject] {
projectManager = projectManagerDictionary["is_project_manager"] as? Bool
createProjects = projectManagerDictionary["can_create_projects"] as? Bool
seeRates = projectManagerDictionary["can_see_rates"] as? Bool
createInvoices = projectManagerDictionary["can_create_invoices"] as? Bool
}
timezoneOffsetSeconds = userDictionary["timezone_utc_offset"] as? Int
timestampTimers = userDictionary["timestamp_timers"] as? Bool
if let avatarURLString = userDictionary["avatar_url"] as? String {
avatarURL = NSURL(string: avatarURLString)
}
}
}
|
1f733d866da22a3ee5f70f747cc515b1
| 31.121429 | 161 | 0.637456 | false | false | false | false |
andressbarnes/basicStart
|
refs/heads/master
|
basicStart/basicStart/CircleUIView.swift
|
mit
|
1
|
//
// CircleUIView.swift
// basicStart
//
// Created by John Barnes on 8/14/16.
// Copyright ยฉ 2016 Andress Barnes. All rights reserved.
//
import UIKit
class CircleUIView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let green_100: UIColor = UIColor.whiteColor()
let parentViewBounds = self.bounds
let parentViewWidth = CGRectGetWidth(parentViewBounds)
let parentViewHeight = CGRectGetHeight(parentViewBounds)
let ovalPath = UIBezierPath(ovalInRect: CGRect(x: 0, y: 0, width: parentViewWidth, height: parentViewHeight))
green_100.setFill()
ovalPath.fill()
}
}
|
71af606ebe3298432ac4f503f45d4796
| 20.902439 | 117 | 0.610245 | false | false | false | false |
StanZabroda/Hydra
|
refs/heads/master
|
Hydra/SinglyLinkedList.swift
|
mit
|
1
|
import Foundation
struct SinglyLinkedList<T> {
var head = HeadNode<SinglyNode<T>>()
func findNodeWithKey(key: String) -> SinglyNode<T>? {
if var currentNode = head.next {
while currentNode.key != key {
if let nextNode = currentNode.next {
currentNode = nextNode
} else {
return nil
}
}
return currentNode
} else {
return nil
}
}
func upsertNodeWithKey(key: String, AndValue val: T) -> SinglyNode<T> {
if var currentNode = head.next {
while let nextNode = currentNode.next {
if currentNode.key == key {
break
} else {
currentNode = nextNode
}
}
if currentNode.key == key {
currentNode.value = val
return currentNode
} else {
currentNode.next = SinglyNode<T>(key: key, value: val, nextNode: nil)
return currentNode.next!
}
} else {
head.next = SinglyNode<T>(key: key, value: val, nextNode: nil)
return head.next!
}
}
func displayNodes() {
print("Printing Nodes", terminator: "")
if var currentNode = head.next {
print("First Node's Value is \(currentNode.value!)", terminator: "")
while let nextNode = currentNode.next {
currentNode = nextNode
print("Next Node's Value is \(currentNode.value!)", terminator: "")
}
} else {
print("List is empty", terminator: "")
}
}
}
|
66465fa895ccb3227d9cfc753d42bd89
| 32.211538 | 85 | 0.48146 | false | false | false | false |
cliqz-oss/browser-ios
|
refs/heads/development
|
Client/Frontend/Widgets/SiteTableViewController.swift
|
mpl-2.0
|
2
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
struct SiteTableViewControllerUX {
static let HeaderHeight = CGFloat(25)
static let RowHeight = CGFloat(58)
static let HeaderBorderColor = UIColor(rgb: 0xCFD5D9).withAlphaComponent(0.8)
static let HeaderTextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor(rgb: 0x232323)
static let HeaderBackgroundColor = UIColor(rgb: 0xECF0F3).withAlphaComponent(0.3)
static let HeaderFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightMedium)
static let HeaderTextMargin = CGFloat(10)
}
class SiteTableViewHeader : UITableViewHeaderFooterView {
// I can't get drawRect to play nicely with the glass background. As a fallback
// we just use views for the top and bottom borders.
let topBorder = UIView()
let bottomBorder = UIView()
let titleLabel = UILabel()
override var textLabel: UILabel? {
return titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
topBorder.backgroundColor = UIColor.white
bottomBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
contentView.backgroundColor = UIColor.white
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
titleLabel.textColor = SiteTableViewControllerUX.HeaderTextColor
titleLabel.textAlignment = .left
addSubview(topBorder)
addSubview(bottomBorder)
contentView.addSubview(titleLabel)
topBorder.snp_makeConstraints { make in
make.left.right.equalTo(self)
make.top.equalTo(self).offset(-0.5)
make.height.equalTo(0.5)
}
bottomBorder.snp_makeConstraints { make in
make.left.right.bottom.equalTo(self)
make.height.equalTo(0.5)
}
// A table view will initialize the header with CGSizeZero before applying the actual size. Hence, the label's constraints
// must not impose a minimum width on the content view.
titleLabel.snp_makeConstraints { make in
make.left.equalTo(contentView).offset(SiteTableViewControllerUX.HeaderTextMargin).priorityHigh()
make.right.equalTo(contentView).offset(-SiteTableViewControllerUX.HeaderTextMargin).priorityHigh()
make.left.greaterThanOrEqualTo(contentView) // Fallback for when the left space constraint breaks
make.right.lessThanOrEqualTo(contentView) // Fallback for when the right space constraint breaks
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/**
* Provides base shared functionality for site rows and headers.
*/
class SiteTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
fileprivate let CellIdentifier = "CellIdentifier"
fileprivate let HeaderIdentifier = "HeaderIdentifier"
var profile: Profile! {
didSet {
reloadData()
}
}
var data: Cursor<Site> = Cursor<Site>(status: .Success, msg: "No data set")
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
return
}
tableView.delegate = self
tableView.dataSource = self
tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: CellIdentifier)
tableView.register(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: HeaderIdentifier)
tableView.layoutMargins = UIEdgeInsets.zero
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
tableView.backgroundColor = UIConstants.PanelBackgroundColor
tableView.separatorColor = UIConstants.SeparatorColor
tableView.accessibilityIdentifier = "SiteTable"
if #available(iOS 9, *) {
tableView.cellLayoutMarginsFollowReadableWidth = false
}
// Set an empty footer to prevent empty cells from appearing in the list.
tableView.tableFooterView = UIView()
}
deinit {
// The view might outlive this view controller thanks to animations;
// explicitly nil out its references to us to avoid crashes. Bug 1218826.
tableView.dataSource = nil
tableView.delegate = nil
}
func reloadData() {
if data.status != .Success {
print("Err: \(data.statusMessage)", terminator: "\n")
} else {
self.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath)
if self.tableView(tableView, hasFullWidthSeparatorForRowAtIndexPath: indexPath) {
cell.separatorInset = UIEdgeInsets.zero
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderIdentifier)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return SiteTableViewControllerUX.HeaderHeight
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return SiteTableViewControllerUX.RowHeight
}
func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool {
return false
}
}
|
04adb2a70bdaa1b14086f8cc4a3f2ffc
| 38.272727 | 130 | 0.698413 | false | false | false | false |
ashare80/ASTextInputAccessoryView
|
refs/heads/master
|
Example/ASTextInputAccessoryView/Extensions/NSDate.swift
|
mit
|
1
|
//
// NSDate.swift
// ASTextInputAccessoryView
//
// Created by Adam J Share on 4/19/16.
// Copyright ยฉ 2016 CocoaPods. All rights reserved.
//
import Foundation
extension NSDate {
var headerFormattedString: String {
let dateFormatter = NSDateFormatter()
let template = "MMM dd, hh:mm"
let locale = NSLocale.currentLocale()
let format = NSDateFormatter.dateFormatFromTemplate(template, options:0, locale:locale)
dateFormatter.setLocalizedDateFormatFromTemplate(format!)
var dateTimeString = dateFormatter.stringFromDate(self)
if NSCalendar.currentCalendar().isDateInToday(self) {
dateTimeString = "Today, " + dateTimeString
}
else {
dateFormatter.setLocalizedDateFormatFromTemplate("EEE")
let weekDay = dateFormatter.stringFromDate(self)
dateTimeString = weekDay + ", " + dateTimeString
}
return dateTimeString
}
}
|
c3dc2ddc06067555f04bae6f87f5239e
| 28.588235 | 95 | 0.640796 | false | false | false | false |
ben-ng/swift
|
refs/heads/master
|
benchmark/single-source/ArraySubscript.swift
|
apache-2.0
|
1
|
//===--- ArraySubscript.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks the performance of modifying an array element.
import TestsUtils
@inline(never)
public func run_ArraySubscript(_ N: Int) {
SRand()
let numArrays = 200*N
let numArrayElements = 100
func bound(_ x: Int) -> Int { return min(x, numArrayElements-1) }
var arrays = [[Int]](repeating: [], count: numArrays)
for i in 0..<numArrays {
for _ in 0..<numArrayElements {
arrays[i].append(Int(truncatingBitPattern: Random()))
}
}
// Do a max up the diagonal.
for i in 1..<numArrays {
arrays[i][bound(i)] =
max(arrays[i-1][bound(i-1)], arrays[i][bound(i)])
}
CheckResults(arrays[0][0] <= arrays[numArrays-1][bound(numArrays-1)],
"Incorrect results in QuickSort.")
}
|
cc11c1239317d7f17a0861f7efb6fe7c
| 31.205128 | 80 | 0.600318 | false | true | false | false |
AaronMT/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/FaviconHandler.swift
|
mpl-2.0
|
7
|
/* 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 SDWebImage
class FaviconHandler {
static let MaximumFaviconSize = 1 * 1024 * 1024 // 1 MiB file size limit
private let backgroundQueue = OperationQueue()
init() {
register(self, forTabEvents: .didLoadPageMetadata, .pageMetadataNotAvailable)
}
func loadFaviconURL(_ faviconURL: String, forTab tab: Tab) -> Deferred<Maybe<(Favicon, Data?)>> {
guard let iconURL = URL(string: faviconURL), let currentURL = tab.url else {
return deferMaybe(FaviconError())
}
let deferred = Deferred<Maybe<(Favicon, Data?)>>()
let manager = SDWebImageManager.shared
let url = currentURL.absoluteString
let site = Site(url: url, title: "")
let options: SDWebImageOptions = tab.isPrivate ? [SDWebImageOptions.lowPriority, SDWebImageOptions.fromCacheOnly] : SDWebImageOptions.lowPriority
var fetch: SDWebImageOperation?
let onProgress: SDWebImageDownloaderProgressBlock = { (receivedSize, expectedSize, _) -> Void in
if receivedSize > FaviconHandler.MaximumFaviconSize || expectedSize > FaviconHandler.MaximumFaviconSize {
fetch?.cancel()
}
}
let onSuccess: (Favicon, Data?) -> Void = { [weak tab] (favicon, data) -> Void in
tab?.favicons.append(favicon)
guard !(tab?.isPrivate ?? true), let appDelegate = UIApplication.shared.delegate as? AppDelegate, let profile = appDelegate.profile else {
deferred.fill(Maybe(success: (favicon, data)))
return
}
profile.favicons.addFavicon(favicon, forSite: site) >>> {
deferred.fill(Maybe(success: (favicon, data)))
}
}
let onCompletedSiteFavicon: SDInternalCompletionBlock = { (img, data, _, _, _, url) -> Void in
guard let urlString = url?.absoluteString else {
deferred.fill(Maybe(failure: FaviconError()))
return
}
let favicon = Favicon(url: urlString, date: Date())
guard let img = img else {
favicon.width = 0
favicon.height = 0
onSuccess(favicon, data)
return
}
favicon.width = Int(img.size.width)
favicon.height = Int(img.size.height)
onSuccess(favicon, data)
}
let onCompletedPageFavicon: SDInternalCompletionBlock = { (img, data, _, _, _, url) -> Void in
guard let img = img, let urlString = url?.absoluteString else {
// If we failed to download a page-level icon, try getting the domain-level icon
// instead before ultimately failing.
let siteIconURL = currentURL.domainURL.appendingPathComponent("favicon.ico")
fetch = manager.loadImage(with: siteIconURL, options: options, progress: onProgress, completed: onCompletedSiteFavicon)
return
}
let favicon = Favicon(url: urlString, date: Date())
favicon.width = Int(img.size.width)
favicon.height = Int(img.size.height)
onSuccess(favicon, data)
}
fetch = manager.loadImage(with: iconURL, options: options, progress: onProgress, completed: onCompletedPageFavicon)
return deferred
}
}
extension FaviconHandler: TabEventHandler {
func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {
tab.favicons.removeAll(keepingCapacity: false)
guard let faviconURL = metadata.faviconURL else {
return
}
loadFaviconURL(faviconURL, forTab: tab).uponQueue(.main) { result in
guard let (favicon, data) = result.successValue else { return }
TabEvent.post(.didLoadFavicon(favicon, with: data), for: tab)
}
}
func tabMetadataNotAvailable(_ tab: Tab) {
tab.favicons.removeAll(keepingCapacity: false)
}
}
class FaviconError: MaybeErrorType {
internal var description: String {
return "No Image Loaded"
}
}
|
6980ec344642a4f44cc792e6621431b5
| 36.482759 | 153 | 0.618905 | false | false | false | false |
liuxianghong/SmartLight
|
refs/heads/master
|
Code/SmartLight/SmartLight/Model/ServerModel.swift
|
apache-2.0
|
1
|
//
// ServerModel.swift
// RXS
//
// Created by ๅๅๅฎ on 2017/4/24.
// Copyright ยฉ 2017ๅนด ๅๅๅฎ. All rights reserved.
//
import UIKit
import Compression
class ServerResult: NSObject {
var retCode: String?
var retMsg: String?
}
class ServerLoginResult: ServerResult {
var userId: String?
var token: String?
var loginName: String?
}
class ServerHomeDeviceResult: ServerResult {
var totalCount: String?
var homeDeviceList: [[String: String]]? {
didSet {
guard let homeDeviceList = homeDeviceList else {
deviceList = nil
return
}
deviceList = [ServerHomeLampResult]()
for deviceJSON in homeDeviceList {
if let device = ServerHomeLampResult.model(withJSON: deviceJSON) {
deviceList?.append(device)
}
}
}
}
var deviceList: [ServerHomeLampResult]?
}
class ServerHomeLampResult: NSObject {
var deviceId: String?
var deviceName: String?
var deviceLogoURL: String?
var macAddress: String?
var brandId: String?
//var description: String?
var power: String?
var brightness: String?
var tonal: String?
var colorTemperature: String?
var ra: String?
var saturation: String?
var redColor: String?
var greenColor: String?
var blueColor: String?
var poweron: String?
var timingOn: String?
var startTime: String?
var endTime: String?
var randomOn: String?
var delayOn: String?
var delayTime: String?
}
extension String {
func md5String() -> String{
let cStr = self.cString(using: String.Encoding.utf8);
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
CC_MD5(cStr!,(CC_LONG)(strlen(cStr!)), buffer)
let md5String = NSMutableString();
for i in 0 ..< 16{
md5String.appendFormat("%02x", buffer[i])
}
buffer.deallocate(capacity: 16)
return md5String as String
}
}
|
9c7311ffbe6d76e243fb1eff3aa9fe94
| 23.590361 | 82 | 0.613915 | false | false | false | false |
moray95/MCChat
|
refs/heads/master
|
Pod/Classes/MapViewController.swift
|
mit
|
1
|
//
// MapViewController.swift
// MultipeerConnectivityChat
//
// Created by Moray on 01/07/15.
// Copyright ยฉ 2015 Moray. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class UnlocatedPeerCell : UICollectionViewCell
{
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
}
class Annotation : NSObject, MKAnnotation
{
@objc var coordinate : CLLocationCoordinate2D
@objc var title : String? = ""
@objc let subtitle : String? = ""
init(location : CLLocation, title : String)
{
self.coordinate = location.coordinate
self.title = title
}
}
class RotationToggleBarButtonItem : UIBarButtonItem
{
var state = true
}
class MapViewController: UIViewController, MKMapViewDelegate
{
@IBOutlet weak var mapView: MyMapView!
@IBOutlet weak var collectionView: UICollectionView!
var unlocatedPeers = [String]()
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.rightBarButtonItem = RotationToggleBarButtonItem(title: "Rotation: On", style: UIBarButtonItemStyle.Plain, target: self, action: "toggleRotation:")
var location = locations[NSUserDefaults.displayName]
mapView.delegate = self
mapView.userTrackingMode = .FollowWithHeading
for (displayName, peerLocation) in locations
{
if displayName != NSUserDefaults.displayName
{
let annotation = Annotation(location: peerLocation, title: displayName)
mapView.addAnnotation(annotation)
location = location ?? peerLocation
}
}
/*if location != nil
{
var maxLong = location!.coordinate.longitude + location!.horizontalAccuracy/(111_111.0 * cos(location!.coordinate.latitude))
var minLong = location!.coordinate.longitude - location!.horizontalAccuracy/(111_111.0 * cos(location!.coordinate.latitude))
var maxLat = location!.coordinate.latitude + location!.horizontalAccuracy/111_111.0
var minLat = location!.coordinate.latitude - location!.horizontalAccuracy/111_111.0
for (_, location) in locations
{
let error = location.horizontalAccuracy
if location.coordinate.latitude - error/111_111.0 < minLat
{
minLat = location.coordinate.latitude - error/111_111.0
}
if location.coordinate.latitude + error/111_111.0 > maxLat
{
maxLat = location.coordinate.latitude + error/111_111.0
}
if location.coordinate.longitude - error/(111_111.0 * cos(minLat)) < minLong
{
minLong = location.coordinate.longitude - error/(111_111.0 * cos(minLat))
}
if location.coordinate.longitude - error/(111_111.0 * cos(maxLat)) < maxLong
{
maxLong = location.coordinate.longitude - error/(111_111.0 * cos(maxLat))
}
}
mapView.region = MKCoordinateRegion(center: location!.coordinate,
span: MKCoordinateSpan(
latitudeDelta: abs(maxLat - minLat),
longitudeDelta: abs(maxLong - minLong)))
mapView.showsUserLocation = true
}*/
for (peer, _) in connectedUserInfo
{
if locations[peer] == nil
{
unlocatedPeers.append(peer)
}
}
collectionView.reloadData()
}
// MARK: Actions
func toggleRotation(sender : RotationToggleBarButtonItem)
{
sender.state = !sender.state
if !sender.state
{
mapView.userTrackingMode = .None
sender.title = "Rotation: Off"
}
else
{
mapView.userTrackingMode = .FollowWithHeading
sender.title = "Rotation: On"
}
}
// MARK: MKMapViewDelegate
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
if annotation.title!! == "Current Location"
{
return nil
}
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
annotationView.image = avatarForDisplayName(annotation.title!!).avatarImage()
annotationView.canShowCallout = true
return annotationView
}
func mapView(mapView: MKMapView,
didChangeUserTrackingMode mode: MKUserTrackingMode,
animated: Bool)
{
let button = navigationItem.rightBarButtonItem as! RotationToggleBarButtonItem
switch mode
{
case .None, .Follow:
button.title = "Rotation: Off"
button.state = false
case .FollowWithHeading:
button.title = "Rotation On"
button.state = true
}
}
func mapView(mapView: MKMapView,
rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer
{
let renderer = MKCircleRenderer(overlay: overlay)
let comps = UnsafeMutablePointer<CGFloat>(malloc(sizeof(CGFloat) * 3))
UIColor.greenColor().getRed(comps, green: comps.successor(), blue: comps.successor().successor(), alpha: nil)
let color = UIColor(red: comps.memory, green: comps.successor().memory, blue: comps.successor().successor().memory, alpha: 0.2)
renderer.fillColor = color
return renderer
}
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int
{
return unlocatedPeers.count
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("unlocatedPeerCell", forIndexPath: indexPath) as? UnlocatedPeerCell
if cell == nil
{
cell = UnlocatedPeerCell()
}
cell?.imageView.image = avatarForDisplayName(unlocatedPeers[indexPath.item]).avatarImage()
cell?.label.text = unlocatedPeers[indexPath.item]
return cell!
}
}
|
1fb780c867df452f0af0c4e6f45cdd95
| 32.082051 | 170 | 0.605798 | false | false | false | false |
BelledonneCommunications/linphone-iphone
|
refs/heads/master
|
Classes/Swift/Voip/VoipDialog_BASE_1064.swift
|
gpl-3.0
|
4
|
/*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import UIKit
class VoipDialog : UIView{
// Layout constants
let center_corner_radius = 7.0
let title_margin_top = 20
let button_margin = 20.0
let button_width = 135.0
let button_height = 40.0
let button_radius = 3.0
let button_spacing = 15.0
let center_view_sides_margin = 13.0
let title = StyledLabel(VoipTheme.basic_popup_title)
init(message:String, givenButtons:[ButtonAttributes]? = nil) {
super.init(frame: .zero)
backgroundColor = VoipTheme.voip_translucent_popup_background
let centerView = UIView()
centerView.backgroundColor = VoipTheme.dark_grey_color.withAlphaComponent(0.8)
centerView.layer.cornerRadius = center_corner_radius
centerView.clipsToBounds = true
addSubview(centerView)
title.numberOfLines = 0
centerView.addSubview(title)
title.alignParentTop(withMargin:title_margin_top).matchParentSideBorders().done()
title.text = message
let buttonsView = UIStackView()
buttonsView.axis = .horizontal
buttonsView.spacing = button_spacing
var buttons = givenButtons
if (buttons == nil) { // assuming info popup, just putting an ok button
let ok = ButtonAttributes(text:VoipTexts.ok, action: {}, isDestructive:false)
buttons = [ok]
}
buttons?.forEach {
let b = ButtonWithStateBackgrounds(backgroundStateColors: $0.isDestructive ? VoipTheme.primary_colors_background_gray : VoipTheme.primary_colors_background)
b.setTitle($0.text, for: .normal)
b.layer.cornerRadius = button_radius
b.clipsToBounds = true
buttonsView.addArrangedSubview(b)
b.applyTitleStyle(VoipTheme.form_button_bold)
let action = $0.action
b.onClick {
self.removeFromSuperview()
action()
}
b.size(w: button_width,h: button_height).done()
}
centerView.addSubview(buttonsView)
buttonsView.alignUnder(view:title,withMargin:button_margin).alignParentBottom(withMargin:button_margin).centerX().done()
centerView.matchParentSideBorders(insetedByDx: center_view_sides_margin).center().done()
}
func show() {
VoipDialog.rootVC()?.view.addSubview(self)
matchParentDimmensions().done()
}
private static func rootVC() -> UIViewController? {
return PhoneMainView.instance().mainViewController
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
static var toastQueue: [String] = []
static func toast(message:String, timeout:CGFloat = 1.5) {
if (toastQueue.count > 0) {
toastQueue.append(message)
return
}
let alert = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
rootVC()?.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + timeout) {
alert.dismiss(animated: true)
if (toastQueue.count > 0) {
let message = toastQueue.first
toastQueue.remove(at: 0)
self.toast(message: message!)
}
}
}
}
struct ButtonAttributes {
let text:String
let action: (()->Void)
let isDestructive: Bool
}
|
2f3a92ef89e2baf71a5a31bcd941229b
| 28.428571 | 159 | 0.729234 | false | false | false | false |
mercadopago/px-ios
|
refs/heads/develop
|
MercadoPagoSDK/MercadoPagoSDK/Services/Models/PXDiscountsTouchpoint.swift
|
mit
|
1
|
import Foundation
@objcMembers
public class PXDiscountsTouchpoint: NSObject, Codable {
let id: String
let type: String
let content: PXCodableDictionary
let tracking: PXCodableDictionary?
let additionalEdgeInsets: PXCodableDictionary?
public init(id: String, type: String, content: [String: Any], tracking: [String: Any]?, additionalEdgeInsets: [String: Any]?) {
self.id = id
self.type = type
self.content = PXCodableDictionary(value: content)
if let trackingDictionary = tracking {
self.tracking = PXCodableDictionary(value: trackingDictionary)
} else {
self.tracking = nil
}
if let additionalEdgeInsetsDictionary = additionalEdgeInsets {
self.additionalEdgeInsets = PXCodableDictionary(value: additionalEdgeInsetsDictionary)
} else {
self.additionalEdgeInsets = nil
}
}
init(id: String, type: String, content: PXCodableDictionary, tracking: PXCodableDictionary?, additionalEdgeInsets: PXCodableDictionary?) {
self.id = id
self.type = type
self.content = content
self.tracking = tracking
self.additionalEdgeInsets = additionalEdgeInsets
}
enum CodingKeys: String, CodingKey {
case id
case type
case content
case tracking
case additionalEdgeInsets = "additional_edge_insets"
}
}
|
69cdf244d9f28be7939a90b59f75aa07
| 31.454545 | 142 | 0.661765 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceKit/Tests/EurofurenceKitTests/EurofurenceModelTestBuilder.swift
|
mit
|
1
|
import CoreData
@testable import EurofurenceKit
import EurofurenceWebAPI
import XCTest
class FakeClock: Clock {
let significantTimeChangePublisher = SignificantTimeChangePublisher(.distantPast)
func simulateTimeChange(to time: Date) {
significantTimeChangePublisher.send(time)
}
}
@MainActor
class EurofurenceModelTestBuilder {
@MainActor
struct Scenario {
var model: EurofurenceModel
var modelProperties: FakeModelProperties
var api: FakeEurofurenceAPI
var clock: FakeClock
var calendar: FakeEventCalendar
}
private var conventionIdentifier: ConventionIdentifier = .current
private var keychain: Keychain = UnauthenticatedKeychain()
private var api = FakeEurofurenceAPI()
private var eventCalendar = FakeEventCalendar()
func with(conventionIdentifier: ConventionIdentifier) -> Self {
self.conventionIdentifier = conventionIdentifier
return self
}
func with(keychain: Keychain) -> Self {
self.keychain = keychain
return self
}
func with(api: FakeEurofurenceAPI) -> Self {
self.api = api
return self
}
func with(eventCalendar: FakeEventCalendar) -> Self {
self.eventCalendar = eventCalendar
return self
}
@discardableResult
func build() async -> Scenario {
let properties = FakeModelProperties()
let clock = FakeClock()
let configuration = EurofurenceModel.Configuration(
environment: .memory,
properties: properties,
keychain: keychain,
api: api,
calendar: eventCalendar,
conventionIdentifier: conventionIdentifier,
clock: clock
)
let model = EurofurenceModel(configuration: configuration)
await model.prepareForPresentation()
return Scenario(model: model, modelProperties: properties, api: api, clock: clock, calendar: eventCalendar)
}
}
extension EurofurenceModelTestBuilder.Scenario {
var viewContext: NSManagedObjectContext {
model.viewContext
}
func stubSyncResponse(
with result: Result<SynchronizationPayload, Error>,
for generationToken: SynchronizationPayload.GenerationToken? = nil
) async {
api.stub(request: APIRequests.FetchLatestChanges(since: generationToken), with: result)
// Pre-emptively mark all image requests as successful. Failing requests will need to be designated by the
// corresponding tests.
if case .success(let payload) = result {
for image in payload.images.changed {
let expectedRequest = APIRequests.DownloadImage(
imageIdentifier: image.id,
lastKnownImageContentHashSHA1: image.contentHashSha1,
downloadDestinationURL: modelProperties.proposedURL(forImageIdentifier: image.id)
)
api.stub(request: expectedRequest, with: .success(()))
}
}
}
func updateLocalStore(using response: SampleResponse) async throws {
let synchronizationPayload = try response.loadResponse()
await stubSyncResponse(with: .success(synchronizationPayload))
try await model.updateLocalStore()
}
func updateLocalStore() async throws {
try await model.updateLocalStore()
}
func simulateTimeChange(to time: Date) {
clock.simulateTimeChange(to: time)
}
}
|
a188815e4c6293a8415877d2b6b8468f
| 29.888889 | 115 | 0.646099 | false | true | false | false |
dnpp73/SimpleCamera
|
refs/heads/master
|
Sources/View/Parts/ZoomIndicatorButton.swift
|
mit
|
1
|
#if canImport(UIKit)
import UIKit
private extension UIImage {
convenience init?(color: UIColor, size: CGSize) {
if size.width <= 0 || size.height <= 0 {
self.init()
return nil
}
UIGraphicsBeginImageContext(size)
defer {
UIGraphicsEndImageContext()
}
let rect = CGRect(origin: CGPoint.zero, size: size)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.setFillColor(color.cgColor)
context.fill(rect)
guard let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
return nil
}
self.init(cgImage: image)
}
}
internal final class ZoomIndicatorButton: UIButton {
// MARK: - UIView Extension
@IBInspectable dynamic var cornerRadius: CGFloat {
get {
layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable dynamic var borderColor: UIColor? {
get {
if let cgColor = layer.borderColor {
return UIColor(cgColor: cgColor)
} else {
return nil
}
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable dynamic var borderWidth: CGFloat {
get {
layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
// MARK: - UIButton Extension
private func setBackgroundColor(_ color: UIColor?, for state: UIControl.State) {
if let color = color {
let image = UIImage(color: color, size: bounds.size)
setBackgroundImage(image, for: state)
} else {
setBackgroundImage(nil, for: state)
}
}
@IBInspectable dynamic var normalBackgroundColor: UIColor? {
get {
nil // dummy
}
set {
setBackgroundColor(newValue, for: .normal)
}
}
@IBInspectable dynamic var highlightedBackgroundColor: UIColor? {
get {
nil // dummy
}
set {
setBackgroundColor(newValue, for: .highlighted)
}
}
@IBInspectable dynamic var disabledBackgroundColor: UIColor? {
get {
nil // dummy
}
set {
setBackgroundColor(newValue, for: .disabled)
}
}
// MARK: - Initializer
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
updateTitleForCurrentZoomFactor()
SimpleCamera.shared.add(simpleCameraObserver: self)
}
// MARK: -
func updateTitleForCurrentZoomFactor() {
let zoomFactor = SimpleCamera.shared.zoomFactor
let zoomFactorString = String(format: "%.1f", zoomFactor)
let title: String
if zoomFactorString.hasSuffix(".0") {
let l = zoomFactorString.count - 2
title = zoomFactorString.prefix(l) + "x"
} else {
title = zoomFactorString + "x"
}
setTitle(title, for: .normal)
}
}
import AVFoundation
extension ZoomIndicatorButton: SimpleCameraObservable {
func simpleCameraDidStartRunning(simpleCamera: SimpleCamera) {}
func simpleCameraDidStopRunning(simpleCamera: SimpleCamera) {}
func simpleCameraDidChangeFocusPointOfInterest(simpleCamera: SimpleCamera) {}
func simpleCameraDidChangeExposurePointOfInterest(simpleCamera: SimpleCamera) {}
func simpleCameraDidResetFocusAndExposure(simpleCamera: SimpleCamera) {}
func simpleCameraDidSwitchCameraInput(simpleCamera: SimpleCamera) {}
// func simpleCameraSessionRuntimeError(simpleCamera: SimpleCamera, error: AVError) {}
// @available(iOS 9.0, *)
// func simpleCameraSessionWasInterrupted(simpleCamera: SimpleCamera, reason: AVCaptureSession.InterruptionReason) {}
func simpleCameraSessionInterruptionEnded(simpleCamera: SimpleCamera) {}
internal func simpleCameraDidChangeZoomFactor(simpleCamera: SimpleCamera) {
updateTitleForCurrentZoomFactor()
}
}
#endif
|
cbdcecea897819b9bbb7baf169cc0479
| 27.067114 | 120 | 0.611908 | false | false | false | false |
fuzza/functional-swift-examples
|
refs/heads/master
|
functional-swift-playground.playground/Pages/tries.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import Foundation
struct Trie <Element: Hashable> {
let isElement: Bool
let children: [ Element : Trie <Element> ]
}
extension Trie {
init() {
self.isElement = false
self.children = [:]
}
}
extension Trie {
var elements: [[Element]] {
var result: [[Element]] = self.isElement ? [[]] : []
for (key, value) in children {
result += value.elements.map { [key] + $0 }
}
return result
}
}
// Decompose helper
extension Array {
var decompose: (Element, [Element])? {
return isEmpty ? nil : (self[startIndex], Array(self.dropFirst()))
}
}
func sum(_ xs:[Int]) -> Int {
guard let (head, tail) = xs.decompose else { return 0 }
return head + sum(tail)
}
let array = [12,1,6,3,2,5]
let arraySum = sum(array)
func qsort(_ xs:[Int]) -> [Int] {
guard let (pivot, rest) = xs.decompose else { return [] }
let lesser = rest.filter { $0 < pivot }
let greater = rest.filter { $0 >= pivot }
return qsort(lesser) + Array([pivot]) + qsort(greater)
}
let sortedArray = qsort(array)
// Lookup
extension Trie {
func lookup(_ key: [Element]) -> Bool {
guard let (head, tail) = key.decompose else { return isElement }
guard let subtree = self.children[head] else { return false }
return subtree.lookup(tail)
}
}
extension Trie {
func withPrefix(_ prefix: [Element]) -> Trie<Element>? {
guard let (head, tail) = prefix.decompose else { return self }
guard let remainder = children[head] else { return nil }
return remainder.withPrefix(tail)
}
}
extension Trie {
func autocomplete(_ key: [Element]) -> [[Element]] {
return self.withPrefix(key)?.elements ?? []
}
}
extension Trie {
init(_ key: [Element]) {
if let (head, tail) = key.decompose {
let children = [head : Trie(tail)]
self = Trie(isElement: false, children: children)
} else {
self = Trie(isElement: true, children: [:])
}
}
}
extension Trie {
func insert(_ key: [Element]) -> Trie<Element> {
guard let (head, tail) = key.decompose else {
return Trie(isElement: true, children: self.children)
}
var newChildren = children
if let nextTrie = children[head] {
newChildren[head] = nextTrie.insert(tail)
} else {
newChildren[head] = Trie(tail)
}
return Trie(isElement: true, children:newChildren)
}
mutating func insert1(_ key: [Element]) {
guard let (head, tail) = key.decompose else {
self = Trie(isElement: true, children: self.children)
return
}
var newChildren = children
if let nextTrie = children[head] {
nextTrie.insert(tail)
newChildren[head] = nextTrie
} else {
newChildren[head] = Trie(tail)
}
self = Trie(isElement: true, children:newChildren)
}
}
func buildStringTrie(_ words: [String]) -> Trie<Character> {
let emptyTrie = Trie<Character>()
return words.reduce(emptyTrie) { trie, word in
trie.insert(Array(word.characters))
}
}
func autocompleteString(_ word: String, knownWords:Trie<Character>) -> [String] {
let chars = Array(word.characters)
let completed = knownWords.autocomplete(chars)
return completed.map {
return word + String(describing: $0)
}
}
let contents = ["cart", "car", "cat", "dog"]
let trie = buildStringTrie(contents)
let completions = autocompleteString("car", knownWords: trie)
//: [Next](@next)
|
cabe7635a0ae93fa76d421cd3f0a894d
| 25.06383 | 81 | 0.582313 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox
|
refs/heads/master
|
nRF Toolbox/Scanner/ScannedPeripheral.swift
|
bsd-3-clause
|
1
|
/*
* Copyright (c) 2020, Nordic Semiconductor
* 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 CoreBluetooth
class DiscoveredPeripheral: Equatable {
let peripheral: CBPeripheral
var rssi: Int32
init(with peripheral: CBPeripheral, RSSI rssi:Int32 = 0) {
self.peripheral = peripheral
self.rssi = rssi
}
var name: String { peripheral.name ?? "No name" }
var isConnected: Bool { peripheral.state == .connected }
}
func ==(lhs: DiscoveredPeripheral, rhs: DiscoveredPeripheral) -> Bool {
lhs.peripheral == rhs.peripheral
&& lhs.isConnected == rhs.isConnected
&& lhs.rssi == rhs.rssi
}
|
614a70dcd71424ef4d065eb3aca708ad
| 38.648148 | 84 | 0.74638 | false | false | false | false |
RichRelevance/rr-ios-sdk
|
refs/heads/master
|
Demo/RCHSearchViewController.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2016 Rich Relevance Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
private let reuseIdentifier = "productCell"
extension UIAlertController {
static func createFacetActionSheet(withTitle titles: [String?], onSelected: @escaping ((Int) -> ())) -> UIAlertController {
let filterAlertController = UIAlertController(title: nil, message: "Choose Filter", preferredStyle: .actionSheet)
for (index, title) in titles.enumerated() {
let facetAction = UIAlertAction(title: title, style: .default, handler: {
(alert: UIAlertAction!) -> Void in
onSelected(index)
})
filterAlertController.addAction(facetAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
})
filterAlertController.addAction(cancelAction)
return filterAlertController
}
}
enum SortingOptions: String {
case priceLowest = "Price Low to High"
case priceHighest = "Price High to Low"
case newest = "Newest"
case relevance = "Relevance"
static let allValues = [priceLowest, priceHighest, newest, relevance]
}
class RCHSearchViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchBarView: UIView!
@IBOutlet weak var searchProductsView: UIView!
@IBOutlet weak var searchResultsCollectionView: UICollectionView!
@IBOutlet weak var searchProductsLabel: UILabel!
@IBOutlet weak var searchProductsImageView: UIImageView!
@IBOutlet weak var autocompleteTableView: UITableView!
@IBOutlet weak var sortFilterView: UIView!
@IBOutlet weak var sortButton: UIButton!
@IBOutlet weak var filterButton: UIButton!
var nextButton = UIButton()
var previousButton = UIButton()
var sortPicker = UIPickerView()
var pickerView = UIView()
weak var timer = Timer()
var searchFacets: [String: [RCHSearchFacet]] = [:]
var currentFilter: RCHSearchFacet? = nil {
didSet {
var titleString = ""
if currentFilter != nil {
guard let currentTitle = currentFilter?.title else {
return
}
titleString = "Filter: \(currentTitle)"
filterButton.setTitle(titleString, for: .normal)
} else {
titleString = "Filter"
}
filterButton.setTitle(titleString, for: .normal)
}
}
var currentSort: SortingOptions = .relevance {
didSet {
pickerView.isHidden = true
let titleString = "Sort: \(currentSort.rawValue)"
sortButton.setTitle(titleString, for: .normal)
}
}
var pageCount = 0 {
didSet {
if pageCount > 0 {
previousButton.isEnabled = true
previousButton.setTitleColor(.blue, for: .normal)
} else {
previousButton.isEnabled = false
previousButton.setTitleColor(.gray, for: .normal)
}
}
}
var products: [RCHSearchProduct] = [] {
didSet {
searchResultsCollectionView.reloadData()
if products.isEmpty {
searchResultsCollectionView.isHidden = true
} else {
searchResultsCollectionView.isHidden = false
}
updateSearchProductsView()
updateSortFilterHiddentState()
}
}
var autocompleteSuggestions: [String] = [] {
didSet {
autocompleteTableView.reloadData()
if autocompleteSuggestions.isEmpty {
autocompleteTableView.isHidden = true
} else {
autocompleteTableView.isHidden = false
}
updateSortFilterHiddentState()
}
}
var searchTerm = "" {
didSet {
if searchTerm.isEmpty {
products.removeAll()
autocompleteSuggestions.removeAll()
pageCount = 0
}
else {
searchBar.text = searchTerm
searchProductsView.isHidden = true
}
}
}
func updateSortFilterHiddentState() {
sortFilterView.isHidden = products.isEmpty || autocompleteTableView.isHidden == false
}
func updateSearchProductsView() {
searchProductsView.isHidden = !products.isEmpty
searchProductsLabel.text = searchTerm.isEmpty ? "Search Products" : "No Results"
searchProductsImageView.image = UIImage(named: searchTerm.isEmpty ? "img-search.pdf" : "img-noresults.pdf")
}
}
extension SortingOptions: CustomStringConvertible {
var description: String {
switch self {
case .relevance: return ""
case .newest: return "product_release_date"
case .priceLowest: return "product_pricecents"
case .priceHighest: return "product_pricecents"
}
}
var order: Bool {
switch self {
case .relevance: return true
case .newest: return false
case .priceLowest: return true
case .priceHighest: return false
}
}
}
extension RCHSearchViewController: UISearchBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = true
}
func setupView() {
searchResultsCollectionView.isHidden = true
searchProductsView.isHidden = false
let footerViewFrame = CGRect(x: 0, y: 0, width: autocompleteTableView.frame.width, height: autocompleteTableView.frame.height)
let footerView = UIView(frame: footerViewFrame)
footerView.backgroundColor = UIColor.clear
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(RCHSearchViewController.handleTapOnFooter))
tapRecognizer.numberOfTapsRequired = 1
footerView.addGestureRecognizer(tapRecognizer)
autocompleteTableView.tableFooterView = footerView
pickerView.frame = CGRect(x: 0, y: view.frame.height - 300, width: view.frame.width, height: 300)
sortPicker.dataSource = self
sortPicker.delegate = self
sortPicker.frame = CGRect(x: 0, y: 30, width: view.frame.width, height: 270)
sortPicker.backgroundColor = UIColor.lightGray
sortPicker.showsSelectionIndicator = true
searchResultsCollectionView!.register(UINib(nibName: "RCHProductCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
let toolBar = UIToolbar()
toolBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 30)
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.blue
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.sortPickerDoneSelected))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.sortPickerCancelSelected))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
sortFilterView.isHidden = true
pickerView.addSubview(sortPicker)
pickerView.addSubview(toolBar)
view.addSubview(pickerView)
pickerView.isHidden = true
previousButton.isEnabled = false
nextButton.isEnabled = false
}
func dismissSearch() {
view.endEditing(true)
autocompleteSuggestions.removeAll()
sortButton.setTitle("Sort", for: .normal)
updateSearchProductsView()
}
// MARK: API
func searchForProducts() {
let placement: RCHRequestPlacement = RCHRequestPlacement.init(pageType: .search, name: "find")
let searchBuilder: RCHSearchBuilder = RCHSDK.builder(forSearch: placement, withQuery: searchTerm)
searchBuilder.setPageStart(pageCount * 20)
if let searchFilter = currentFilter {
searchBuilder.addFilter(from: searchFilter)
}
let sortString = currentSort.description
let orderASC = currentSort.order
if currentSort != .relevance {
searchBuilder.addSortOrder(sortString, ascending: orderASC)
}
RCHSDK.defaultClient().sendRequest(searchBuilder.build(), success: { (responseObject) in
guard let searchResult = responseObject as? RCHSearchResult else { return }
// If the search term has been emptied, ignore this response since there will not be another request to update it.
guard !self.searchTerm.isEmpty else { return }
self.products = searchResult.products!
self.searchFacets = searchResult.facets!
if searchResult.count > 20 && self.products.count >= 20 {
self.nextButton.isEnabled = true
self.nextButton.setTitleColor(.blue, for: .normal)
} else {
self.nextButton.isEnabled = false
self.nextButton.setTitleColor(.gray, for: .normal)
}
}) { (responseObject, error) in
let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
print(error)
}
}
func autocomplete(withQuery text: String) {
let autocompleteBuilder: RCHAutocompleteBuilder = RCHSDK.builderForAutocomplete(withQuery: text)
RCHSDK.defaultClient().sendRequest(autocompleteBuilder.build(), success: { (responseObject) in
guard let responseAutocompleteSuggestions = responseObject as? [RCHAutocompleteSuggestion] else {
print("Result Error")
return
}
self.autocompleteSuggestions = responseAutocompleteSuggestions.map({$0.text!})
}) { (responseObject, error) in
let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
print(error)
}
}
// MARK: IBActions
@IBAction func handleTapOnFooter(sender: UITapGestureRecognizer) {
dismissSearch()
}
@IBAction func filterSelected(_ sender: AnyObject) {
let titles = searchFacets.map({ $0.key })
let alertController = UIAlertController.createFacetActionSheet(withTitle: titles) { index in
guard let facetSelected = self.searchFacets[titles[index]] else {
return
}
self.showSubFilter(withFacets: facetSelected)
}
if currentFilter != nil {
let removeFilterAction = UIAlertAction(title: "Remove Filter", style: .destructive, handler: {
(alert: UIAlertAction!) -> Void in
self.currentFilter = nil
self.searchForProducts()
})
alertController.addAction(removeFilterAction)
}
self.present(alertController, animated: true, completion: nil)
}
func showSubFilter(withFacets facets: [RCHSearchFacet]) {
let titles = facets.map( { $0.title })
let alertController = UIAlertController.createFacetActionSheet(withTitle: titles) { index in
let facetSelected = facets[index]
self.currentFilter = facetSelected
self.searchForProducts()
}
self.present(alertController, animated: true, completion: nil)
}
@IBAction func sortSelected(_ sender: AnyObject) {
pickerView.isHidden = false
}
@IBAction func sortPickerDoneSelected(_ sender: AnyObject) {
currentSort = SortingOptions.allValues[sortPicker.selectedRow(inComponent: 0)]
searchForProducts()
}
@IBAction func sortPickerCancelSelected(_ sender: AnyObject) {
pickerView.isHidden = true
}
@IBAction func footerButtonSelected(_ sender: AnyObject) {
searchResultsCollectionView.setContentOffset(CGPoint.zero, animated: false)
if sender.tag == 2 {
pageCount += 1
} else if sender.tag == 3 {
pageCount -= 1
}
searchForProducts()
}
// MARK: UISearchBarDelegate
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchProductsView.isHidden = true
currentFilter = nil
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
dismissSearch()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchTerm = searchText.replacingOccurrences(of: " ", with: "")
timer?.invalidate()
if !searchTerm.isEmpty {
autocomplete(withQuery: searchText)
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.searchForProducts), userInfo: nil, repeats: false)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
dismissSearch()
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return products.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! RCHProductCollectionViewCell
let product = products[indexPath.row]
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
let priceCentsToDollars = (product.priceCents?.intValue)! / 100 as NSNumber
cell.priceLabel.text = numberFormatter.string(from: priceCentsToDollars)
cell.productImage.sd_setImage(with: URL(string: product.imageURL!))
cell.brandLabel.text = product.brand?.uppercased()
cell.titleLabel.text = product.name
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "productDetailSegue", sender: self)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footerView", for: indexPath) as! RCHSearchResultsCollectionReusableView
previousButton = headerView.previousButton
nextButton = headerView.nextButton
return headerView
}
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autocompleteSuggestions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "autocompleteCell", for: indexPath)
cell.textLabel?.attributedText = attributedText(for: indexPath.row)
let blurEffect = UIBlurEffect(style: .light)
let effectView = UIVisualEffectView(effect: blurEffect)
cell.backgroundView = effectView
return cell
}
func attributedText(for row: Int) -> NSAttributedString {
let autocompleteString = autocompleteSuggestions[row]
let attributedString = NSMutableAttributedString(string: autocompleteString)
if !searchTerm.isEmpty && autocompleteSuggestions.count > 0 {
let searchString = searchTerm.lowercased()
let highlightColor = UIColor(red: 0, green: 121/255, blue: 253/255, alpha: 1)
let blueAttribute = [NSBackgroundColorAttributeName : highlightColor]
if let range: Range<String.Index> = autocompleteString.range(of: searchString) {
let index: Int = autocompleteString.distance(from: autocompleteString.startIndex, to: range.lowerBound)
let nsRange = NSMakeRange(index, searchString.characters.count)
attributedString.addAttributes(blueAttribute, range: nsRange)
}
}
return attributedString
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
searchTerm = autocompleteSuggestions[indexPath.row]
dismissSearch()
searchForProducts()
}
// MARK: UIPickerViewDelegate
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return SortingOptions.allValues.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return SortingOptions.allValues[row].rawValue
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "productDetailSegue" {
if let destinationViewControler = segue.destination as? RCHProductDetailViewController {
guard let selectedIndexPath = searchResultsCollectionView.indexPathsForSelectedItems else {
return
}
let selectedProduct = products[selectedIndexPath[0].row]
destinationViewControler.product = selectedProduct
}
}
}
}
|
6df6c0e0ebdf5a0c10ae1a38c20c4e42
| 37.870707 | 200 | 0.643106 | false | false | false | false |
LuizZak/TaskMan
|
refs/heads/master
|
TaskMan/TaskSegment.swift
|
mit
|
1
|
//
// TaskSegment.swift
// TaskMan
//
// Created by Luiz Fernando Silva on 16/09/16.
// Copyright ยฉ 2016 Luiz Fernando Silva. All rights reserved.
//
import Cocoa
import SwiftyJSON
/// Represents a segment in time in which a task was executed
struct TaskSegment {
/// The identifier type for task segments
typealias IDType = Int
/// Unique ID of this task segment
var id: IDType
/// ID of the associated task
var taskId: Task.IDType
/// The start/end date ranges for this task
var range: DateRange
init(id: Int, taskId: Task.IDType, range: DateRange) {
self.id = id
self.taskId = taskId
self.range = range
}
}
extension TaskSegment: Equatable {
static func ==(lhs: TaskSegment, rhs: TaskSegment) -> Bool {
return lhs.id == rhs.id && lhs.taskId == rhs.taskId && lhs.range == rhs.range
}
}
|
d564f8e30d9c18f7a4d56af4cbb8e690
| 22.684211 | 85 | 0.631111 | false | false | false | false |
Miridescen/M_365key
|
refs/heads/master
|
365KEY_swift/365KEY_swift/MainController/Class/News/model/SKNewsListModel.swift
|
apache-2.0
|
1
|
//
// SKNewsListModel.swift
// 365KEY_swift
//
// Created by ็ๆพ on 2016/11/25.
// Copyright ยฉ 2016ๅนด DoNews. All rights reserved.
//
import UIKit
class SKNewsListModel: NSObject {
var id: Int64 = 0
var inputtime: Date? {
didSet{
let inputTimeStr = inputtime?.description
let showTimeIndex = inputTimeStr?.index((inputTimeStr?.startIndex)!, offsetBy: 10)
showTime = inputTimeStr?.substring(to: showTimeIndex!)
let nowTimeInterval = Date().timeIntervalSince1970
let inputTimeInterval = inputtime?.timeIntervalSince1970
let zome = NSTimeZone.local
let second = zome.secondsFromGMT()
let mistiming = Int(nowTimeInterval) + second - Int(inputTimeInterval!)
if (mistiming<3600) {
let minute = mistiming/60
timeLabelStr = minute == 0 ? "ๅๅ": "\(minute)ๅ้ๅ"
} else if mistiming >= 3600 && mistiming <= 86400 {
let day = mistiming/3600
timeLabelStr = "\(day)ๅฐๆถๅ"
} else {
let strIndex = inputTimeStr?.index((inputTimeStr?.startIndex)!, offsetBy: 10)
let timStr = inputTimeStr?.substring(to: strIndex!)
let strArray = timStr?.components(separatedBy: "-")
guard let strArr = strArray else {
return
}
timeLabelStr = "\(strArr[1])ๆ\(strArr[2])ๆฅ"
}
}
}
var showTime: String?
var timeLabelStr: String?
var content: String?
var userinfo: SKProductUserModel?
var counts: Int64 = 0
var isgood: String?
override var description: String{
return yy_modelDescription()
}
}
|
ec845fb116870c99ae7d150929023b8d
| 26.126761 | 94 | 0.521807 | false | false | false | false |
justin999/gitap
|
refs/heads/master
|
gitap/ReposViewController.swift
|
mit
|
1
|
//
// ReposViewController.swift
// gitap
//
// Created by Koichi Sato on 12/24/16.
// Copyright ยฉ 2016 Koichi Sato. All rights reserved.
//
import UIKit
class ReposViewController: UIViewController {
var stateController: StateController?
@IBOutlet weak var tableView: UITableView!
var tableViewDataSource: ReposTableViewDataSource?
var tableViewDelegate: ReposTableViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
if let stateController = stateController {
tableViewDataSource = ReposTableViewDataSource(tableView: tableView, stateController: stateController)
tableViewDelegate = ReposTableViewDelegate(tableView: tableView, stateController: stateController)
}
}
override func viewDidAppear(_ animated: Bool) {
stateController?.viewController = self
if GitHubAPIManager.shared.hasOAuthToken() {
stateController?.getRepos { success in
switch success {
case true:
// reloading data should be done in main thread, otherwise the autolayout waring will occur.
// ref. http://stackoverflow.com/questions/38983363/this-application-is-modifying-the-autolayout-engine-error-swift-ios
DispatchQueue.main.async {
self.tableView.reloadData()
}
case false:
print("fetching faield")
}
}
// GitHubAPIManager.shared.printIssues()
} else {
// self.showOAuthLoginView()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "presentEditIssue",
let destiantion = segue.destination as? UINavigationController,
let vc = destiantion.topViewController as? CreateIssuesViewController {
vc.stateController = stateController
}
}
}
|
b6eaa63a65cca90ecd77af6d11c79bf9
| 34.060606 | 139 | 0.627053 | false | false | false | false |
CartoDB/mobile-ios-samples
|
refs/heads/master
|
AdvancedMap.Swift/Feature Demo/Routing.swift
|
bsd-2-clause
|
1
|
//
// Routing.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 22/06/2017.
// Copyright ยฉ 2017 CARTO. All rights reserved.
//
import Foundation
import CartoMobileSDK
class Routing {
static let ROUTING_TAG = "routing:"
static let OFFLINE_ROUTING_SOURCE = "nutiteq.osm.car"
static let MAP_SOURCE = "carto.streets"
var service: NTRoutingService?
var startMarker, stopMarker: NTMarker?
var instructionUp, instructionLeft, instructionRight: NTMarkerStyle?
var routeDataSource, routeIntructionSource, routeStartStopDataSource: NTLocalVectorDataSource?
var mapView: NTMapView!
var projection: NTProjection!
var showTurns: Bool = true
init(mapView: NTMapView) {
self.mapView = mapView
projection = mapView.getOptions().getBaseProjection()
let start = NTBitmapFromString(path: "icon_pin_red.png")
let stop = NTBitmapFromString(path: "icon_pin_red.png")
let up = NTBitmapFromString(path: "direction_up.png")
let upleft = NTBitmapFromString(path: "direction_upthenleft.png")
let upright = NTBitmapFromString(path: "direction_upthenright")
// Define layer and datasource for route line and instructions
routeDataSource = NTLocalVectorDataSource(projection: projection)
let routeLayer = NTVectorLayer(dataSource: routeDataSource)
mapView.getLayers().add(routeLayer)
routeIntructionSource = NTLocalVectorDataSource(projection: projection)
let routeInstructionLayer = NTVectorLayer(dataSource: routeIntructionSource)
mapView.getLayers().add(routeInstructionLayer)
// Define layer and datasource for route start and stop markers
routeStartStopDataSource = NTLocalVectorDataSource(projection: projection)
let vectorLayer = NTVectorLayer(dataSource: routeStartStopDataSource)
mapView.getLayers().add(vectorLayer)
// Set visible zoom range for the vector layer
vectorLayer?.setVisibleZoom(NTMapRange(min: 0, max: 22))
let markerBuilder = NTMarkerStyleBuilder()
markerBuilder?.setBitmap(start)
markerBuilder?.setHideIfOverlapped(false)
// Note: When setting the size on Android, you need to account for Resources.DisplayMetrics.Density
markerBuilder?.setSize(20)
let defaultPosition = NTMapPos(x: 0, y: 0)
startMarker = NTMarker(pos: defaultPosition, style: markerBuilder?.buildStyle())
startMarker?.setVisible(false)
routeStartStopDataSource?.add(startMarker)
markerBuilder?.setBitmap(stop)
stopMarker = NTMarker(pos: defaultPosition, style: markerBuilder?.buildStyle())
stopMarker?.setVisible(false)
routeStartStopDataSource?.add(stopMarker)
markerBuilder?.setBitmap(up)
instructionUp = markerBuilder?.buildStyle()
markerBuilder?.setBitmap(upleft)
instructionLeft = markerBuilder?.buildStyle()
markerBuilder?.setBitmap(upright)
instructionRight = markerBuilder?.buildStyle()
routeLayer?.setOpacity(0.5)
}
func updateMode(mode: String) {
}
func updateFinishMarker(icon: String, size: Float, color: NTColor? = nil) {
let builder = NTMarkerStyleBuilder()
builder?.setBitmap(NTBitmapFromString(path: icon))
builder?.setSize(size)
builder?.setHideIfOverlapped(false)
if (color != nil) {
builder?.setColor(color)
}
builder?.setAnchorPointX(0, anchorPointY: 0)
stopMarker?.setStyle(builder?.buildStyle())
}
func NTBitmapFromString(path: String) -> NTBitmap {
let image = UIImage(named: path)
return NTBitmapUtils.createBitmap(from: image)
}
/*
* Return bounds on complete so we can start downloading the BBOX
*/
func show(result: NTRoutingResult, lineColor: NTColor, complete: (_ route: Route) -> Void) {
routeDataSource?.clear()
startMarker?.setVisible(true)
let line = createPolyLine(result: result, color: lineColor)
routeDataSource?.add(line)
let instructions = result.getInstructions()
let vector = NTMapPosVector()
let count = Int((instructions?.size())!)
for i in stride(from: 0, to: count, by: 1) {
let instruction = instructions?.get(Int32(i))
let index = Int32((instruction?.getPointIndex())!)
let position = result.getPoints().get(index)
if (showTurns) {
createRoutePoint(position: position!, instruction: instruction!, source: routeIntructionSource!)
}
vector?.add(position)
}
let polygon = NTPolygon(poses: vector, style: NTPolygonStyleBuilder().buildStyle())
let route = Route()
route.bounds = polygon?.getBounds()
route.length = result.getTotalDistance()
complete(route)
}
func getMessage(result: NTRoutingResult) -> String {
let distance = round(result.getTotalDistance() / 1000 * 100) / 100
let message = "Your route is " + String(distance) + "km"
return message
}
func getResult(startPos: NTMapPos, stopPos: NTMapPos) -> NTRoutingResult? {
let positions = NTMapPosVector()
positions?.add(startPos)
positions?.add(stopPos)
let request = NTRoutingRequest(projection: projection, points: positions)
var result: NTRoutingResult?
do {
try NTExceptionWrapper.catchException {
result = self.service?.calculateRoute(request)
}
return result
}
catch {
NSLog("Failed to calculate route")
return nil
}
}
func createRoutePoint(position: NTMapPos, instruction: NTRoutingInstruction, source: NTLocalVectorDataSource) {
let action = instruction.getAction()
var style = instructionUp
if (action == .ROUTING_ACTION_TURN_LEFT) {
style = instructionLeft
} else if (action == .ROUTING_ACTION_TURN_RIGHT) {
style = instructionRight
}
let marker = NTMarker(pos: position, style: style)
source.add(marker)
}
func createPolyLine(result: NTRoutingResult, color: NTColor) -> NTLine {
let builder = NTLineStyleBuilder()
builder?.setColor(color)
builder?.setWidth(10)
return NTLine(poses: result.getPoints(), style: builder?.buildStyle())
}
func setStartMarker(position: NTMapPos) {
routeDataSource?.clear()
stopMarker?.setVisible(false)
startMarker?.setPos(position)
startMarker?.setVisible(true)
}
func setStopMarker(position: NTMapPos) {
stopMarker?.setPos(position)
stopMarker?.setVisible(true)
}
func isPointOnRoute(point: NTMapPos) -> Bool {
let line = getLine()
if (line == nil) {
return false
}
let positions = line?.getPoses()
let count = Int(positions!.size())
for i in 0..<count {
if (i < count - 1) {
let segmentStart = positions!.get(Int32(i))!
let segmentEnd = positions!.get(Int32(i + 1))!
let distance = distanceFromLineSegment(point: point, start: segmentStart, end: segmentEnd)
print("Distance: " + String(describing: distance))
// TODO: The number it returns should be translated further,
// due to the earth's curviture, it's smaller near the equator. Normalize it.
if (distance < 3) {
return true
}
}
}
return false
}
func getLine() -> NTLine? {
let elements = routeDataSource?.getAll()
let count: Int32 = Int32(elements!.size())
for i in 0..<count {
let element = elements?.get(i)
if (element is NTLine) {
return element as? NTLine
}
}
return nil
}
/*
* Translated from:
* https://github.com/CartoDB/mobile-sdk/blob/a1a9c175867f3a47bd5eda2062a7d213c42da01a/all/native/utils/GeomUtils.cpp#L30
*/
func distanceFromLineSegment(point: NTMapPos, start: NTMapPos, end: NTMapPos) -> Double {
let nearest = calculateNearestPointOnLineSegment(point: point, start: start, end: end)
return distanceFromPoint(point1: nearest, point2: point)
}
/*
* Translated from:
* https://github.com/CartoDB/mobile-sdk/blob/a1a9c175867f3a47bd5eda2062a7d213c42da01a/all/native/utils/GeomUtils.cpp#L14
*/
func distanceFromPoint(point1: NTMapPos, point2: NTMapPos) -> Double {
let diff = getDiff(a: point2, b: point1)
return sqrt(diff.dotProduct(diff))
}
/*
* Translated from:
* https://github.com/CartoDB/mobile-sdk/blob/a1a9c175867f3a47bd5eda2062a7d213c42da01a/all/native/utils/GeomUtils.cpp#L35
*/
func calculateNearestPointOnLineSegment(point: NTMapPos, start: NTMapPos, end: NTMapPos) -> NTMapPos {
if (start.isEqual(end)) {
return start
}
let diff = getDiff(a: point, b: start)
let dir = getDiff(a: end, b: start)
let u = clamp(value: diff.dotProduct(dir) / dir.dotProduct(dir), low: 0.0, high: 1.0)
let x = (dir.getX() * u) + start.getX()
let y = (dir.getY() * u) + start.getY()
return NTMapPos(x: x, y: y)
}
/*
* Translated from:
* https://github.com/CartoDB/mobile-sdk/blob/3b3b2fa1b91f1395ebd3e166a0609a762c95a9ea/all/native/utils/GeneralUtils.h#L19
*/
func clamp(value: Double, low: Double, high: Double) -> Double {
return value < low ? low : (value > high ? high : value)
}
func getDiff(a: NTMapPos, b: NTMapPos) -> NTMapVec {
return NTMapVec(x: a.getX() - b.getX(), y: a.getY() - b.getY())
}
}
|
cd774601270906574cab6289587942b6
| 32.04717 | 126 | 0.598439 | false | false | false | false |
eliburke/swamp
|
refs/heads/master
|
Swamp/Serialization/MsgpackSwampSerializer.swift
|
mit
|
1
|
//
// MsgpackSwampSerializer.swift
// Swamp
//
#if MSGPACK_SUPPORT
import Foundation
import MessagePack
open class MsgpackSwampSerializer: SwampSerializer {
public init() {}
open func anyToMPValue(anyVal : Any) -> MessagePackValue? {
switch(anyVal) {
case is Bool:
return MessagePackValue(anyVal as! Bool)
case is Int:
return MessagePackValue(anyVal as! Int)
case is Int8:
return MessagePackValue(anyVal as! Int8)
case is Int16:
return MessagePackValue(anyVal as! Int16)
case is Int32:
return MessagePackValue(anyVal as! Int32)
case is Int64:
return MessagePackValue(anyVal as! Int64)
case is UInt:
return MessagePackValue(anyVal as! UInt)
case is UInt8:
return MessagePackValue(anyVal as! UInt8)
case is UInt16:
return MessagePackValue(anyVal as! UInt16)
case is UInt32:
return MessagePackValue(anyVal as! UInt32)
case is UInt64:
return MessagePackValue(anyVal as! UInt64)
case is Float:
return MessagePackValue(anyVal as! Float)
case is Double:
return MessagePackValue(anyVal as! Double)
case is String:
return MessagePackValue(anyVal as! String)
case is Data:
return MessagePackValue(anyVal as! Data)
case is Array<Any>:
let arrayVal = anyVal as! Array<Any>
var mpArray = Array<MessagePackValue>()
for value in arrayVal {
if let mpValue = anyToMPValue(anyVal: value) {
mpArray.append(mpValue)
} else {
print("Failed to convert '\(value)' to mpValue")
}
}
return MessagePackValue(mpArray)
case is Dictionary<String, Any>:
let dictVal = anyVal as! Dictionary<String, Any>
var mpDict = [MessagePackValue : MessagePackValue]()
for (key,value) in dictVal {
let mpKey = MessagePackValue(key)
if let mpValue = anyToMPValue(anyVal: value) {
mpDict[mpKey] = mpValue
} else {
print("Failed to convert '\(value)'")
}
}
return MessagePackValue(mpDict)
default:
print("Unknown type for `\(anyVal)` -- cannot convert to mpValue")
return nil;
}
}
open func mpValueToAny(_ mpValue : MessagePackValue) -> Any? {
switch(mpValue) {
case .bool:
return mpValue.boolValue
case .int:
return mpValue.integerValue
case .uint:
return mpValue.unsignedIntegerValue
case .float:
return mpValue.floatValue
case .double:
return mpValue.doubleValue
case .string:
return mpValue.stringValue
case .binary:
return mpValue.dataValue
case .array:
var array = [Any]()
if let mpArray = mpValue.arrayValue {
for mpSubVal in mpArray {
if let subVal = mpValueToAny(mpSubVal) {
array.append(subVal)
}
}
}
return array
case .map:
var dict = [String : Any]()
if let mpDict = mpValue.dictionaryValue {
for (mpKey, mpSubVal) in mpDict {
if let key = mpKey.stringValue, let val = mpValueToAny(mpSubVal) {
dict[key] = val
} else {
print("Failed to convert '\(mpKey)' and '\(mpSubVal)'")
}
}
}
return dict
default:
print("Failed to covnert unknown mpValue type: \(mpValue)")
return nil
}
}
//MARK: Serializers
open func pack(_ data: [MessagePackValue]) -> Data? { // untested
var packed = Data()
for mpValue in data {
packed.append(MessagePack.pack(mpValue))
}
return packed
}
open func pack(_ data: [Any]) -> Data? {
var packed = Data()
if let mpValue = anyToMPValue(anyVal: data) {
packed.append(MessagePack.pack(mpValue))
}
return packed
}
open func unpack(_ data: Data) -> [Any]? {
do {
var unpacked = [Any]()
let mpArray = try unpackAll(data)
for mpValue in mpArray {
if let value = mpValueToAny(mpValue) {
unpacked.append(value)
}
}
return unpacked[0] as? [Any]
}
catch {
return nil
}
}
}
#endif // MESSAGEPACK_SUPPORT
|
5956a57c8c50244046a8eaa642b6a381
| 29.717791 | 86 | 0.505492 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/RecentSessionRowItem.swift
|
gpl-2.0
|
1
|
//
// RecentSessionRowItem.swift
// Telegram
//
// Created by keepcoder on 08/03/2017.
// Copyright ยฉ 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import DateUtils
class RecentSessionRowItem: GeneralRowItem {
let session:RecentAccountSession
let headerLayout:TextViewLayout
let descLayout:TextViewLayout
let dateLayout:TextViewLayout
let handler:()->Void
let icon: (CGImage?, LocalAnimatedSticker?, NSColor?, [String]?)
init(_ initialSize: NSSize, session:RecentAccountSession, stableId:AnyHashable, viewType: GeneralViewType, icon: (CGImage?, LocalAnimatedSticker?, NSColor?, [String]?), handler: @escaping()->Void) {
self.session = session
self.handler = handler
self.icon = icon
headerLayout = TextViewLayout(.initialize(string: session.deviceModel, color: theme.colors.text, font: .normal(.title)), maximumNumberOfLines: 1)
let attr = NSMutableAttributedString()
_ = attr.append(string:session.appName + " " + session.appVersion.prefixWithDots(30) + ", " + session.platform + " " + session.systemVersion, color: theme.colors.text, font: .normal(.text))
_ = attr.append(string: "\n")
_ = attr.append(string: session.ip + " " + session.country, color: theme.colors.grayText, font: .normal(.text))
descLayout = TextViewLayout(attr, maximumNumberOfLines: 2, lineSpacing: 2)
dateLayout = TextViewLayout(.initialize(string: session.isCurrent ? strings().peerStatusOnline : DateUtils.string(forMessageListDate: session.activityDate), color: session.isCurrent ? theme.colors.accent : theme.colors.grayText, font: .normal(.text)))
super.init(initialSize, stableId: stableId, viewType: viewType)
_ = makeSize(initialSize.width, oldWidth: initialSize.width)
}
override func makeSize(_ width: CGFloat, oldWidth: CGFloat) -> Bool {
let success = super.makeSize(width, oldWidth: oldWidth)
headerLayout.measure(width: blockWidth - 90 - (icon.0 != nil ? 38 : 0))
descLayout.measure(width: blockWidth - 40 - (icon.0 != nil ? 38 : 0))
dateLayout.measure(width: .greatestFiniteMagnitude)
return success
}
override var height: CGFloat {
return 75
}
override func viewClass() -> AnyClass {
return RecentSessionRowView.self
}
}
class RecentSessionRowView : GeneralContainableRowView {
private let headerTextView = TextView()
private let descTextView = TextView()
private let dateTextView = TextView()
private let iconView: ImageView = ImageView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.addSubview(headerTextView)
self.addSubview(descTextView)
self.addSubview(dateTextView)
addSubview(iconView)
headerTextView.userInteractionEnabled = false
headerTextView.isSelectable = false
dateTextView.userInteractionEnabled = false
dateTextView.isSelectable = false
descTextView.userInteractionEnabled = false
descTextView.isSelectable = false
containerView.set(handler: { [weak self] _ in
if let item = self?.item as? RecentSessionRowItem {
item.handler()
}
}, for: .Click)
}
override func updateColors() {
super.updateColors()
headerTextView.backgroundColor = backdorColor
descTextView.backgroundColor = backdorColor
dateTextView.backgroundColor = backdorColor
containerView.backgroundColor = backdorColor
if let item = item as? RecentSessionRowItem {
self.background = item.viewType.rowBackground
}
}
override var backdorColor: NSColor {
return theme.colors.background
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item)
if let item = item as? RecentSessionRowItem {
self.iconView.image = item.icon.0
self.iconView.sizeToFit()
}
self.needsLayout = true
}
override func layout() {
super.layout()
guard let item = item as? RecentSessionRowItem else {
return
}
let insets = item.viewType.innerInset
self.iconView.setFrameOrigin(NSMakePoint(insets.left, insets.top))
let left: CGFloat = (item.icon.0 != nil ? 38 : 0)
self.headerTextView.update(item.headerLayout, origin: NSMakePoint(left + insets.left, insets.top - 2))
self.descTextView.update(item.descLayout, origin: NSMakePoint(left + insets.left, headerTextView.frame.maxY + 4))
self.dateTextView.update(item.dateLayout, origin: NSMakePoint(self.containerView.frame.width - insets.right - item.dateLayout.layoutSize.width, insets.top))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
027e0d2cf93e4816ed42ba7c1a6524d5
| 35.340426 | 259 | 0.648322 | false | false | false | false |
xcplaygrounds/uikitplayground
|
refs/heads/master
|
Animations.playground/Pages/UIKit Dynamics.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: # UIKit Dynamics : Physics Fun !
import UIKit
import XCPlayground
//: Lets take a fun tour of UIKit Dynamics. Instead of using explicit animations , your views can now snap , stretch , crash and bounce based on physics !
//:
//: Lets create a white container to hold our animations.
let container = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 300.0))
container.backgroundColor = UIColor.whiteColor()
//: You can see the action in the assistant editor on the right.
//: Lets add a shiny black square .
let view = UIView(frame: CGRect(x: 20.0, y: 10.0, width: 50.0, height: 50.0))
view.backgroundColor = UIColor.blackColor()
container.addSubview(view)
//: Now lets make him fall to the floor and bounce to a halt.
//: ### Step 1 : Create the animator :
//: We create the animator. The animator is an instance of *UIDynamicAnimator* which animates its items with respect to its referenceView. You usually do this in *viewDidLoad* and assign it as a property on the viewController.
var animator = UIDynamicAnimator(referenceView: container)
//: ### Step 2 : Create the behaviours :
//: Now we move on to behaviors. Each behavior applies to a set of items . We need two behaviors here. A Collission behavior and a gravity behavior.
var collision = UICollisionBehavior(items: [view])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
let itemBehaviour = UIDynamicItemBehavior(items: [view])
itemBehaviour.elasticity = 0.7 // try values from 0->1
animator.addBehavior(itemBehaviour)
var gravity = UIGravityBehavior(items: [view])
animator.addBehavior(gravity)
XCPShowView("container", view: container)
//: WHEEE !!
//: [Next](@next)
|
3c0c2eefadf60c9a8cf6a3a82a937df4
| 39.906977 | 226 | 0.720296 | false | false | false | false |
glyuck/MAActivityIndicator
|
refs/heads/master
|
MAActivityIndicator-Demo/MAActivityIndicator-Demo/ViewController.swift
|
mit
|
2
|
//
// ViewController.swift
// MAActivityIndicator-Demo
//
// Created by Michaรซl Azevedo on 09/02/2015.
// Copyright (c) 2015 Michaรซl Azevedo. All rights reserved.
//
import UIKit
class ViewController: UIViewController, MAActivityIndicatorViewDelegate {
//MARK: - Properties
@IBOutlet var viewForActivity1: UIView!
@IBOutlet var sliderNbCircles: UISlider!
@IBOutlet var labelNbCircles: UILabel!
@IBOutlet var sliderMaxRadius: UISlider!
@IBOutlet var labelMaxRadius: UILabel!
@IBOutlet var sliderSpacing: UISlider!
@IBOutlet var labelSpacing: UILabel!
var indicatorView1 : MAActivityIndicatorView!
// MARK: - Init methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// dispatch async is used in order to have the frame OK (else you have to declare this in viewDidAppear() )
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.indicatorView1 = MAActivityIndicatorView(frame: self.viewForActivity1.frame)
self.indicatorView1.defaultColor = UIColor.redColor()
self.indicatorView1.animationDuration = 1
self.indicatorView1.numberOfCircles = 15
self.indicatorView1.maxRadius = 40
self.indicatorView1.delegate = self
// self.indicatorView1.backgroundColor = UIColor.lightGrayColor()
self.indicatorView1.startAnimating()
self.view.addSubview(self.indicatorView1)
})
}
//MARK: - Action methods
@IBAction func sliderValueChanged(sender: UISlider) {
if sender == sliderNbCircles {
let nbCircles = Int(sliderNbCircles.value)
labelNbCircles.text = "nb Circles : \(nbCircles)"
indicatorView1.numberOfCircles = nbCircles
} else if sender == sliderMaxRadius {
let maxRadius = CGFloat(sliderMaxRadius.value)
labelMaxRadius.text = String(format:"max radius : %3.2f", Double(maxRadius))
indicatorView1.maxRadius = maxRadius
} else if sender == sliderSpacing {
let spacing = CGFloat(sliderSpacing.value)
labelSpacing.text = String(format: "spacing : %3.2f", Double(spacing))
indicatorView1.internalSpacing = spacing
}
}
//MARK: - MAActivityIndicatorViewDelegate protocol conformance
func activityIndicatorView(activityIndicatorView: MAActivityIndicatorView, circleBackgroundColorAtIndex index: NSInteger) -> UIColor {
let R = CGFloat(arc4random() % 256)/255
let G = CGFloat(arc4random() % 256)/255
let B = CGFloat(arc4random() % 256)/255
return UIColor(red: R, green: G, blue: B, alpha: 1)
}
}
|
04c150b5fd2c563b9c841ba2bb4bfaac
| 34.703704 | 138 | 0.642462 | false | false | false | false |
romaonthego/TableViewDataManager
|
refs/heads/master
|
Source/Classes/Components/Slider/TableViewSliderCell.swift
|
mit
|
1
|
//
// TableViewSliderCell.swift
// TableViewDataManager
//
// Copyright (c) 2016 Roman Efimov (https://github.com/romaonthego)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public class TableViewSliderCell: TableViewFormCell {
// MARK: Public variables
//
public override var item: TableViewItem! { get { return sliderItem } set { sliderItem = newValue as! TableViewSliderItem } }
// MARK: Private variables
//
private var sliderItem: TableViewSliderItem!
// MARK: Interface builder outlets
//
@IBOutlet public private(set) var slider: UISlider!
// MARK: View Lifecycle
//
public override func cellDidLoad() {
super.cellDidLoad()
}
public override func cellWillAppear() {
super.cellWillAppear()
slider.value = self.sliderItem.value
}
// MARK: Actions
//
@IBAction func sliderValueChanged(sender: UISlider!) {
self.sliderItem.value = sender.value
guard let changeHandler = self.sliderItem.changeHandler, let tableView = self.tableViewDataManager.tableView, let indexPath = self.indexPath else {
return
}
changeHandler(section: self.section, item: self.sliderItem, tableView: tableView, indexPath: indexPath)
}
}
|
d2e54bd117dc7be1108ca613c0fa75ef
| 36.548387 | 155 | 0.713058 | false | false | false | false |
Keymochi/Keymochi
|
refs/heads/master
|
Keyboard/Shapes.swift
|
bsd-3-clause
|
2
|
//
// Shapes.swift
// TastyImitationKeyboard
//
// Created by Alexei Baboulevitch on 10/5/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
import UIKit
// TODO: these shapes were traced and as such are erratic and inaccurate; should redo as SVG or PDF
///////////////////
// SHAPE OBJECTS //
///////////////////
class BackspaceShape: Shape {
override func drawCall(_ color: UIColor) {
drawBackspace(self.bounds, color: color)
}
}
class ShiftShape: Shape {
var withLock: Bool = false {
didSet {
self.overflowCanvas.setNeedsDisplay()
}
}
override func drawCall(_ color: UIColor) {
drawShift(self.bounds, color: color, withRect: self.withLock)
}
}
class GlobeShape: Shape {
override func drawCall(_ color: UIColor) {
drawGlobe(self.bounds, color: color)
}
}
class Shape: UIView {
var color: UIColor? {
didSet {
if let _ = self.color {
self.overflowCanvas.setNeedsDisplay()
}
}
}
// in case shapes draw out of bounds, we still want them to show
var overflowCanvas: OverflowCanvas!
convenience init() {
self.init(frame: CGRect.zero)
}
override required init(frame: CGRect) {
super.init(frame: frame)
self.isOpaque = false
self.clipsToBounds = false
self.overflowCanvas = OverflowCanvas(shape: self)
self.addSubview(self.overflowCanvas)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && self.bounds.equalTo(oldBounds!) {
return
}
oldBounds = self.bounds
super.layoutSubviews()
let overflowCanvasSizeRatio = CGFloat(1.25)
let overflowCanvasSize = CGSize(width: self.bounds.width * overflowCanvasSizeRatio, height: self.bounds.height * overflowCanvasSizeRatio)
self.overflowCanvas.frame = CGRect(
x: CGFloat((self.bounds.width - overflowCanvasSize.width) / 2.0),
y: CGFloat((self.bounds.height - overflowCanvasSize.height) / 2.0),
width: overflowCanvasSize.width,
height: overflowCanvasSize.height)
self.overflowCanvas.setNeedsDisplay()
}
func drawCall(_ color: UIColor) { /* override me! */ }
class OverflowCanvas: UIView {
unowned var shape: Shape
init(shape: Shape) {
self.shape = shape
super.init(frame: CGRect.zero)
self.isOpaque = false
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
CGColorSpaceCreateDeviceRGB()
ctx?.saveGState()
let xOffset = (self.bounds.width - self.shape.bounds.width) / CGFloat(2)
let yOffset = (self.bounds.height - self.shape.bounds.height) / CGFloat(2)
ctx?.translateBy(x: xOffset, y: yOffset)
self.shape.drawCall(shape.color != nil ? shape.color! : UIColor.black)
ctx?.restoreGState()
}
}
}
/////////////////////
// SHAPE FUNCTIONS //
/////////////////////
func getFactors(_ fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) {
let xSize = { () -> CGFloat in
let scaledSize = (fromSize.width / CGFloat(2))
if scaledSize > toRect.width {
return (toRect.width / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let ySize = { () -> CGFloat in
let scaledSize = (fromSize.height / CGFloat(2))
if scaledSize > toRect.height {
return (toRect.height / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let actualSize = min(xSize, ySize)
return (actualSize, actualSize, actualSize, false, 0)
}
func centerShape(_ fromSize: CGSize, toRect: CGRect) {
let xOffset = (toRect.width - fromSize.width) / CGFloat(2)
let yOffset = (toRect.height - fromSize.height) / CGFloat(2)
let ctx = UIGraphicsGetCurrentContext()
ctx?.saveGState()
ctx?.translateBy(x: xOffset, y: yOffset)
}
func endCenter() {
let ctx = UIGraphicsGetCurrentContext()
ctx?.restoreGState()
}
func drawBackspace(_ bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSize(width: 44, height: 32), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSize(width: 44 * xScalingFactor, height: 32 * yScalingFactor), toRect: bounds)
//// Color Declarations
let color = color
let color2 = UIColor.gray // TODO:
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 26 * yScalingFactor), controlPoint1: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 22 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 36 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 32 * xScalingFactor, y: 0 * yScalingFactor), controlPoint2: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.close()
color.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 22 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor))
bezier2Path.close()
UIColor.gray.setFill()
bezier2Path.fill()
color2.setStroke()
bezier2Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor))
bezier3Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 10 * yScalingFactor))
bezier3Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor))
bezier3Path.close()
UIColor.red.setFill()
bezier3Path.fill()
color2.setStroke()
bezier3Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier3Path.stroke()
endCenter()
}
func drawShift(_ bounds: CGRect, color: UIColor, withRect: Bool) {
let factors = getFactors(CGSize(width: 38, height: (withRect ? 34 + 4 : 32)), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
_ = factors.lineWidthScalingFactor
centerShape(CGSize(width: 38 * xScalingFactor, height: (withRect ? 34 + 4 : 32) * yScalingFactor), toRect: bounds)
//// Color Declarations
let color2 = color
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 19 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 14 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor), controlPoint2: CGPoint(x: 10 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 28 * yScalingFactor), controlPoint1: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor), controlPoint1: CGPoint(x: 28 * xScalingFactor, y: 26 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.close()
color2.setFill()
bezierPath.fill()
if withRect {
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRect(x: 10 * xScalingFactor, y: 34 * yScalingFactor, width: 18 * xScalingFactor, height: 4 * yScalingFactor))
color2.setFill()
rectanglePath.fill()
}
endCenter()
}
func drawGlobe(_ bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSize(width: 41, height: 40), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSize(width: 41 * xScalingFactor, height: 40 * yScalingFactor), toRect: bounds)
//// Color Declarations
let color = color
//// Oval Drawing
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0 * xScalingFactor, y: 0 * yScalingFactor, width: 40 * xScalingFactor, height: 40 * yScalingFactor))
color.setStroke()
ovalPath.lineWidth = 1 * lineWidthScalingFactor
ovalPath.stroke()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 40 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor))
bezierPath.close()
color.setStroke()
bezierPath.lineWidth = 1 * lineWidthScalingFactor
bezierPath.stroke()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 39.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.close()
color.setStroke()
bezier2Path.lineWidth = 1 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor))
bezier3Path.addCurve(to: CGPoint(x: 21.63 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor), controlPoint2: CGPoint(x: 41 * xScalingFactor, y: 19 * yScalingFactor))
bezier3Path.lineCapStyle = .round;
color.setStroke()
bezier3Path.lineWidth = 1 * lineWidthScalingFactor
bezier3Path.stroke()
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor))
bezier4Path.addCurve(to: CGPoint(x: 18.72 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor), controlPoint2: CGPoint(x: -2.5 * xScalingFactor, y: 19.04 * yScalingFactor))
bezier4Path.lineCapStyle = .round;
color.setStroke()
bezier4Path.lineWidth = 1 * lineWidthScalingFactor
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor))
bezier5Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 7 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 21 * yScalingFactor))
bezier5Path.lineCapStyle = .round;
color.setStroke()
bezier5Path.lineWidth = 1 * lineWidthScalingFactor
bezier5Path.stroke()
//// Bezier 6 Drawing
let bezier6Path = UIBezierPath()
bezier6Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor))
bezier6Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 33 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 22 * yScalingFactor))
bezier6Path.lineCapStyle = .round;
color.setStroke()
bezier6Path.lineWidth = 1 * lineWidthScalingFactor
bezier6Path.stroke()
endCenter()
}
|
cebbd4170444272657fe5e2e86a46ef9
| 38.633803 | 244 | 0.653945 | false | false | false | false |
SPECURE/rmbt-ios-client
|
refs/heads/main
|
Sources/RMBTSettings.swift
|
apache-2.0
|
1
|
/*****************************************************************************************************
* Copyright 2013 appscape gmbh
* Copyright 2014-2016 SPECURE GmbH
*
* 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
///
open class RMBTSettings: NSObject {
public enum NerdModeQosMode: Int {
case manually
case newNetwork
case always
}
///
public static let sharedSettings = RMBTSettings()
// MARK: Temporary app state (global variables)
///
@objc open dynamic var mapOptionsSelection: RMBTMapOptionsSelection
// MARK: Persisted app state
///
@objc open dynamic var testCounter: UInt = 0
///
@objc open dynamic var previousTestStatus: String?
// MARK: User configurable properties
///
@objc open dynamic var publishPublicData = false // only for akos
@objc open dynamic var submitZeroTesting = true
/// anonymous mode
@objc open dynamic var anonymousModeEnabled = false
// MARK: Nerd mode
///
@objc open dynamic var nerdModeEnabled = false
///
@objc open dynamic var nerdModeForceIPv4 = false
///
@objc open dynamic var nerdModeForceIPv6 = false
@objc open dynamic var isDarkMode = false
///
@objc open dynamic var nerdModeQosEnabled = NerdModeQosMode.newNetwork.rawValue // Enable QoS
// MARK: Debug properties
///
@objc open dynamic var debugUnlocked = false
// loop mode
///
@objc open dynamic var debugLoopMode = false
///
@objc open dynamic var debugLoopModeMaxTests: UInt = 0
///
@objc open dynamic var debugLoopModeMinDelay: UInt = 0
@objc open dynamic var debugLoopModeSkipQOS: Bool = false
@objc open dynamic var debugLoopModeDistance: UInt = 0
@objc open dynamic var debugLoopModeIsStartImmedatelly: Bool = true
// control server
///
@objc open dynamic var debugControlServerCustomizationEnabled = false
///
@objc open dynamic var debugControlServerHostname: String?
///
@objc open dynamic var debugControlServerPort: UInt = 0
///
@objc open dynamic var debugControlServerUseSSL = false
// map server
///
@objc open dynamic var debugMapServerCustomizationEnabled = false
///
@objc open dynamic var debugMapServerHostname: String?
///
@objc open dynamic var debugMapServerPort: UInt = 0
///
@objc open dynamic var debugMapServerUseSSL = false
// logging
///
@objc open dynamic var debugLoggingEnabled = false
@objc open dynamic var previousNetworkName: String?
@objc open dynamic var isAdsRemoved: Bool = false
@objc open dynamic var lastSurveyTimestamp: Double = 0.0
@objc open dynamic var isClientPersistent: Bool = true
@objc open dynamic var isAnalyticsEnabled: Bool = true
@objc open dynamic var countMeasurements: Int = 0
@objc open dynamic var isDevModeEnabled: Bool = false
@objc open dynamic var serverIdentifier: String?
@objc open dynamic var isOverrideServer: Bool = false
///
private override init() {
mapOptionsSelection = RMBTMapOptionsSelection()
super.init()
bindKeyPaths([
"testCounter",
"previousTestStatus",
"debugUnlocked",
"developerModeEnabled", // TODO: this should replace debug unlocked
///////////
// USER SETTINGS
// general
"publishPublicData",
"submitZeroTesting",
// anonymous mode
"anonymousModeEnabled",
///////////
// NERD MODE
// nerd mode
"nerdModeEnabled",
"nerdModeForceIPv4",
"nerdModeForceIPv6",
// nerd mode, advanced settings, qos
"nerdModeQosEnabled",
///////////
// DEVELOPER MODE
// developer mode, advanced settings, loop mode
"developerModeLoopMode",
"developerModeLoopModeMaxTests",
"developerModeLoopModeMinDelay",
// control server
"debugControlServerCustomizationEnabled",
"debugControlServerHostname",
"debugControlServerPort",
"debugControlServerUseSSL",
// map server
"debugMapServerCustomizationEnabled",
"debugMapServerHostname",
"debugMapServerPort",
"debugMapServerUseSSL",
// logging
"debugLoggingEnabled",
"previousNetworkName",
"isAdsRemoved",
"lastSurveyTimestamp",
//Loop mode
"debugLoopMode",
"debugLoopModeMaxTests",
"debugLoopModeMinDelay",
"debugLoopModeSkipQOS",
"debugLoopModeDistance",
"debugLoopModeIsStartImmedatelly",
"isDarkMode",
"isClientPersistent",
"isAnalyticsEnabled",
"countMeasurements",
"isDevModeEnabled",
"serverIdentifier",
"isOverrideServer"
])
}
///
private func bindKeyPaths(_ keyPaths: [String]) {
for keyPath in keyPaths {
if let value = UserDefaults.getDataFor(key: keyPath) {
setValue(value, forKey: keyPath)
}
// Start observing
// addObserver(self, forKeyPath: keyPath, options: .new, context: nil)
self.addObserver(self, forKeyPath: keyPath, options: [.new], context: nil)
}
}
///
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let newValue = change?[NSKeyValueChangeKey.newKey], let kp = keyPath {
Log.logger.debugExec() {
let oldValue = UserDefaults.getDataFor(key: kp)
Log.logger.debug("Settings changed for keyPath '\(String(describing: keyPath))' from '\(String(describing: oldValue))' to '\(newValue)'")
}
UserDefaults.storeDataFor(key: kp, obj: newValue)
}
}
}
|
a7d600a12e5411732c3825bead19f58d
| 26.861224 | 156 | 0.596982 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/CryptoAssets/Sources/BitcoinChainKit/Transactions/NativeBitcoin/TransactionCreation/MultiAddressRepository.swift
|
lgpl-3.0
|
1
|
// Copyright ยฉ Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import Foundation
import MoneyKit
import ToolKit
public struct BitcoinChainMultiAddressData {
public let addresses: [BitcoinChainAddressResponse]
public let latestBlockHeight: Int
public init(addresses: [BitcoinChainAddressResponse], latestBlockHeight: Int) {
self.addresses = addresses
self.latestBlockHeight = latestBlockHeight
}
}
public typealias FetchMultiAddressFor = ([XPub]) -> AnyPublisher<BitcoinChainMultiAddressData, NetworkError>
public final class MultiAddressRepository<T: BitcoinChainHistoricalTransactionResponse> {
private let client: APIClientAPI
private let cachedValue: CachedValueNew<
Set<XPub>,
BitcoinChainMultiAddressResponse<T>,
NetworkError
>
public init(client: APIClientAPI) {
self.client = client
let cache: AnyCache<Set<XPub>, BitcoinChainMultiAddressResponse<T>> = InMemoryCache(
configuration: .onLoginLogoutTransaction(),
refreshControl: PeriodicCacheRefreshControl(refreshInterval: 60)
).eraseToAnyCache()
cachedValue = CachedValueNew(
cache: cache,
fetch: { key in
client.multiAddress(for: key.map(\.self))
}
)
}
public func multiAddress(
for wallets: [XPub]
) -> AnyPublisher<BitcoinChainMultiAddressResponse<T>, NetworkError> {
multiAddress(for: wallets, forceFetch: false)
}
public func multiAddress(
for wallets: [XPub],
forceFetch: Bool
) -> AnyPublisher<BitcoinChainMultiAddressResponse<T>, NetworkError> {
cachedValue.get(key: Set(wallets), forceFetch: forceFetch)
}
public func invalidateCache() {
cachedValue.invalidateCache()
}
}
|
ad347514e18bcf078478d1f61c742e93
| 28.412698 | 108 | 0.688613 | false | true | false | false |
zavsby/ProjectHelpersSwift
|
refs/heads/master
|
Classes/Categories/String+Extensions.swift
|
mit
|
1
|
//
// String+Extensions.swift
// ProjectHelpers-Swift
//
// Created by Sergey on 03.11.15.
// Copyright ยฉ 2015 Sergey Plotkin. All rights reserved.
//
import Foundation
import UIKit
public extension String {
//MARK:- Properties
public var length: Int {
return self.characters.count
}
public var anyText: Bool {
return !self.isEmpty
}
// MARK:- Methods
public func md5() -> String {
var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
if let data = self.dataUsingEncoding(NSUTF8StringEncoding) {
CC_MD5(data.bytes, CC_LONG(data.length), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
// MARK:- Text dimensions methods
public func textViewHeightWithFont(font: UIFont, maxWidth: Double) -> Double {
let textView = UITextView()
textView.font = font
textView.text = self
let size = textView.sizeThatFits(CGSize(width: maxWidth, height: DBL_MAX))
return Double(size.height)
}
public func labelHeightWithFont(font: UIFont, maxWidth: Double, linebreakMode: NSLineBreakMode) -> Double {
guard self.anyText else {
return 0.0
}
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = linebreakMode
let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle]
let maximumSize = CGSize(width: maxWidth, height: DBL_MAX)
let rect = (self as NSString).boundingRectWithSize(maximumSize,
options: [.UsesLineFragmentOrigin, .UsesFontLeading],
attributes: attributes,
context: nil
)
return ceil(Double(rect.size.height))
}
}
|
4e9d7b3f4abbc3a94416afedcdfeb4a3
| 26.671233 | 111 | 0.59683 | false | false | false | false |
CoderJackyHuang/SwiftExtensionCodes
|
refs/heads/master
|
SwiftExtensionCodes/UIViewController+HYBExtension.swift
|
mit
|
1
|
//
// UIViewController+HYBExtension.swift
// SwiftExtensionCodes
//
// Created by huangyibiao on 15/9/25.
// Copyright ยฉ 2015ๅนด huangyibiao. All rights reserved.
//
import Foundation
import UIKit
/// Determine the sequence of ok button and cancel.
///
/// - OkCancel: ok button is on the left and cancel button on the right
/// - CancelOk: cancel button is on the left and ok button on the right
public enum AlertOKCancelDirection: Int {
case OkCancel
case CancelOk
}
private var sg_hyb_alert_actionsheet_controller: UIAlertController?
private var sg_default_ok_button_title = "็กฎๅฎ"
private var sg_default_cancel_button_title = "ๅๆถ"
private var sg_ok_cancel_button_direction = AlertOKCancelDirection.CancelOk
/// UIViewController extension for AlertView and ActionSheet
///
/// Author: ้ปไปชๆ
/// Blog: http://www.hybblog.com/
/// Github: http://github.com/CoderJackyHuang/
/// Email: [email protected]
/// Weibo: JackyHuang๏ผๆ ๅฅ๏ผ
public extension UIViewController {
/// Get/Set the default ok button title
public var hyb_defaultOkTitle: String {
get { return sg_default_ok_button_title }
set { sg_default_ok_button_title = newValue }
}
/// Get/Set the default cance button title
public var hyb_defaultCancelTitle: String {
get { return sg_default_cancel_button_title }
set { sg_default_cancel_button_title = newValue }
}
/// Get/Set the defaul direction between ok button and cancel button. Default is CacelOk.
public var hyb_okCancelDirection: AlertOKCancelDirection {
get { return sg_ok_cancel_button_direction }
set { sg_ok_cancel_button_direction = newValue }
}
// MARK: Ok Alert
/// Only Show Alert View in current controller
///
/// - parameter title: title
public func hyb_showOkAlert(title: String?) {
self.hyb_showOkAlert(title, message: nil)
}
/// Show Alert view in current controller with a ok button
///
/// - parameter title: alert view's title
/// - parameter message: show the message
public func hyb_showOkAlert(title: String?, message: String?) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultOkTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
})])
}
/// Show title and an ok button of Alert
///
/// - parameter title: alert's title
/// - parameter ok: ok button call back
public func hyb_showOkAlert(title: String?, ok: () ->Void) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultOkTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
ok()
})])
}
/// Show title, message and an ok button of Alert
///
/// - parameter title: title
/// - parameter message: message
/// - parameter ok: ok button call back
public func hyb_showOkAlert(title: String?, message: String?, ok: () ->Void) {
self.hyb_showAlertActionSheet(title, message: message, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultOkTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
ok()
})])
}
// MARK: Cancel Alert
/// Only Show Alert View in current controller
///
/// - parameter title: title
public func hyb_showCancelAlert(title: String?) {
self.hyb_showCancelAlert(title, message: nil)
}
/// Show Alert view in current controller with a cancel button
///
/// - parameter title: alert view's title
/// - parameter message: show the message
public func hyb_showCancelAlert(title: String?, message: String?) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultCancelTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
})])
}
/// Show title and an ok button of Alert
///
/// - parameter title: alert's title
/// - parameter cancel: cancel button call back
public func hyb_showCancelAlert(title: String?, cancel: () ->Void) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultCancelTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
cancel()
})])
}
/// Show title, message and an ok button of Alert
///
/// - parameter title: title
/// - parameter message: message
/// - parameter cancel: cancel button call back
public func hyb_showCancelAlert(title: String?, message: String?, cancel: () ->Void) {
self.hyb_showAlertActionSheet(title, message: message, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultCancelTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
cancel()
})])
}
// MARK: Ok And Cancel Alert
/// Show Ok and cancel alert view
///
/// - parameter title: title
public func hyb_showAlert(title: String?) {
self.hyb_showAlert(title, message: nil)
}
/// Show Ok and cancel alert view with title and message
///
/// - parameter title: title
/// - parameter message: message
public func hyb_showAlert(title: String?, message: String?) {
var buttonTitles: [String]!
if self.hyb_okCancelDirection == .OkCancel {
buttonTitles = [self.hyb_defaultOkTitle, self.hyb_defaultCancelTitle]
} else {
buttonTitles = [self.hyb_defaultCancelTitle, self.hyb_defaultOkTitle]
}
self.hyb_showAlert(title, message: message, buttonTitles: buttonTitles) { (index) -> Void in
sg_hyb_alert_actionsheet_controller = nil
}
}
/// Show alert view with title, message and custom button titles.
///
/// - parameter title: title
/// - parameter message: message
/// - parameter buttonTitles: custom button titles
/// - parameter buttonClosure: call back
public func hyb_showAlert(title: String?, message: String?,
buttonTitles: [String]?, buttonClosure: ((index: Int) ->Void)?) {
var buttonArray: [UIAlertAction]?
if let titles = buttonTitles {
buttonArray = []
for (index, item) in titles.enumerate() {
buttonArray?.append(UIAlertAction(title: item, style: .Default, handler: { (e) -> Void in
if let callback = buttonClosure {
sg_hyb_alert_actionsheet_controller = nil
callback(index: index)
}
}))
}
}
self.hyb_showAlertActionSheet(title, message: message, preferredStyle: .Alert, alertActions: buttonArray)
}
// MARK: ActionSheet
/// Show action sheet
///
/// - parameter title: title
/// - parameter message: message
/// - parameter cancel: cancel button title
/// - parameter otherTitles: other button titles
/// - parameter closure: call back for button responds
public func hyb_showActionSheet(title: String?, message: String?, cancel: String?,
otherTitles: String..., closure: ((index: Int) ->Void)?) {
self._hyb_showActionSheet(title, message: message, cancel: cancel,
destructive: nil,
otherTitles: otherTitles, closure: closure)
}
/// Show action sheet in current controller.
///
/// - parameter title: title
/// - parameter message: message
/// - parameter cancel: cancel button title
/// - parameter destructive: destructive button title
/// - parameter otherTitles: other button titles
/// - parameter closure: callback with index start with zero
public func hyb_showActionSheet(title: String?, message: String?, cancel: String?,
destructive: String?, otherTitles: String..., closure: ((index: Int) ->Void)?) {
self._hyb_showActionSheet(title, message: message, cancel: cancel,
destructive: destructive, otherTitles: otherTitles, closure: closure)
}
// MARK: Private
private func hyb_showAlertActionSheet(title: String?, message: String?,
preferredStyle: UIAlertControllerStyle, alertActions: [UIAlertAction]?) {
// prevent show too many times
guard sg_hyb_alert_actionsheet_controller == nil else {
return
}
let alertController = UIAlertController(title: title,
message: message, preferredStyle: preferredStyle)
if let actions = alertActions {
for alertAction in actions {
alertController.addAction(alertAction)
}
}
sg_hyb_alert_actionsheet_controller = alertController
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.presentViewController(alertController, animated: true, completion: nil)
}
}
private func _hyb_showActionSheet(title: String?, message: String?, cancel: String?,
destructive: String?, otherTitles: [String]?, closure: ((index: Int) ->Void)?) {
let actionsheet = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet)
var index: Int = 0
if cancel != nil {
actionsheet.addAction(UIAlertAction(title: cancel, style: .Cancel, handler: { (e) -> Void in
if let callback = closure {
callback(index: 0)
}
}))
index++
}
if otherTitles != nil {
for item in otherTitles! {
let itemIndex = index
actionsheet.addAction(UIAlertAction(title: item, style: .Default, handler: { (e) -> Void in
if let callback = closure {
callback(index: itemIndex)
}
}))
index++
}
}
if destructive != nil {
actionsheet.addAction(UIAlertAction(title: destructive, style: .Destructive, handler: { (e) -> Void in
}))
}
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.presentViewController(actionsheet, animated: true, completion: nil)
}
}
}
|
ff8d80ce4deee5dfb5ca604b563f6bf2
| 34.882143 | 190 | 0.657973 | false | false | false | false |
ManuelAurora/RxQuickbooksService
|
refs/heads/master
|
Carthage/Checkouts/OAuthSwift/Sources/SHA1.swift
|
mit
|
4
|
//
// SHA1.swift
// OAuthSwift
//
// Created by Dongri Jin on 1/28/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
class SHA1 {
private var message: [UInt8]
fileprivate let h: [UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
init(_ message: Data) {
self.message = message.bytes
}
init(_ message: [UInt8]) {
self.message = message
}
/** Common part for hash calculation. Prepare header data. */
func prepare(_ message: [UInt8], _ blockSize: Int, _ allowance: Int) -> [UInt8] {
var tmpMessage = message
// Step 1. Append Padding Bits
tmpMessage.append(0x80) // append one bit (Byte with one bit) to message
// append "0" bit until message length in bits โก 448 (mod 512)
var msgLength = tmpMessage.count
var counter = 0
while msgLength % blockSize != (blockSize - allowance) {
counter += 1
msgLength += 1
}
tmpMessage += [UInt8](repeating: 0, count: counter)
return tmpMessage
}
func calculate() -> [UInt8] {
var tmpMessage = self.prepare(self.message, 64, 64 / 8)
// hash values
var hh = h
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage += (self.message.count * 8).bytes(64 / 8)
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(data: tmpMessage, chunkSize: chunkSizeBytes) {
// break chunk into sixteen 32-bit words M[j], 0 โค j โค 15, big-endian
// Extend the sixteen 32-bit words into eighty 32-bit words:
var M: [UInt32] = [UInt32](repeating: 0, count: 80)
for x in 0..<M.count {
switch x {
case 0...15:
let memorySize = MemoryLayout<UInt32>.size
let start = chunk.startIndex + (x * memorySize)
let end = start + memorySize
let le = chunk[start..<end].toUInt32
M[x] = le.bigEndian
break
default:
M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], n: 1)
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
// Main loop
for j in 0...79 {
var f: UInt32 = 0
var k: UInt32 = 0
switch j {
case 0...19:
f = (B & C) | ((~B) & D)
k = 0x5A827999
break
case 20...39:
f = B ^ C ^ D
k = 0x6ED9EBA1
break
case 40...59:
f = (B & C) | (B & D) | (C & D)
k = 0x8F1BBCDC
break
case 60...79:
f = B ^ C ^ D
k = 0xCA62C1D6
break
default:
break
}
let temp = (rotateLeft(A, n: 5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff
E = D
D = C
C = rotateLeft(B, n: 30)
B = A
A = temp
}
hh[0] = (hh[0] &+ A) & 0xffffffff
hh[1] = (hh[1] &+ B) & 0xffffffff
hh[2] = (hh[2] &+ C) & 0xffffffff
hh[3] = (hh[3] &+ D) & 0xffffffff
hh[4] = (hh[4] &+ E) & 0xffffffff
}
// Produce the final hash value (big-endian) as a 160 bit number:
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
hh.forEach {
let item = $0.bigEndian
result += [UInt8(item & 0xff), UInt8((item >> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)]
}
return result
}
private func rotateLeft(_ v: UInt32, n: UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
}
fileprivate struct BytesSequence<D: RandomAccessCollection>: Sequence where D.Iterator.Element == UInt8, D.IndexDistance == Int, D.SubSequence.IndexDistance == Int, D.Index == Int {
let data: D
let chunkSize: D.IndexDistance
func makeIterator() -> AnyIterator<D.SubSequence> {
var offset = data.startIndex
return AnyIterator {
let end = Swift.min(self.chunkSize, self.data.count - offset)
let result = self.data[offset..<offset + end]
offset = offset.advanced(by: result.count)
if !result.isEmpty {
return result
}
return nil
}
}
}
|
6cb61bf14dce3730084972783f154982
| 29.893082 | 181 | 0.471091 | false | false | false | false |
phatblat/realm-cocoa
|
refs/heads/master
|
RealmSwift/Tests/ModernTestObjects.swift
|
apache-2.0
|
1
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import RealmSwift
import Realm
class ModernAllTypesObject: Object {
@Persisted(primaryKey: true) var pk: ObjectId
var ignored: Int = 1
@Persisted var boolCol: Bool
@Persisted var intCol: Int
@Persisted var int8Col: Int8 = 1
@Persisted var int16Col: Int16 = 2
@Persisted var int32Col: Int32 = 3
@Persisted var int64Col: Int64 = 4
@Persisted var floatCol: Float = 5
@Persisted var doubleCol: Double = 6
@Persisted var stringCol: String
@Persisted var binaryCol: Data
@Persisted var dateCol: Date
@Persisted var decimalCol: Decimal128
@Persisted var objectIdCol: ObjectId
@Persisted var objectCol: ModernAllTypesObject?
@Persisted var arrayCol: List<ModernAllTypesObject>
@Persisted var setCol: MutableSet<ModernAllTypesObject>
@Persisted var anyCol: AnyRealmValue
@Persisted var uuidCol: UUID
@Persisted var intEnumCol: ModernIntEnum
@Persisted var stringEnumCol: ModernStringEnum
@Persisted var optIntCol: Int?
@Persisted var optInt8Col: Int8?
@Persisted var optInt16Col: Int16?
@Persisted var optInt32Col: Int32?
@Persisted var optInt64Col: Int64?
@Persisted var optFloatCol: Float?
@Persisted var optDoubleCol: Double?
@Persisted var optBoolCol: Bool?
@Persisted var optStringCol: String?
@Persisted var optBinaryCol: Data?
@Persisted var optDateCol: Date?
@Persisted var optDecimalCol: Decimal128?
@Persisted var optObjectIdCol: ObjectId?
@Persisted var optUuidCol: UUID?
@Persisted var optIntEnumCol: ModernIntEnum?
@Persisted var optStringEnumCol: ModernStringEnum?
@Persisted var arrayBool: List<Bool>
@Persisted var arrayInt: List<Int>
@Persisted var arrayInt8: List<Int8>
@Persisted var arrayInt16: List<Int16>
@Persisted var arrayInt32: List<Int32>
@Persisted var arrayInt64: List<Int64>
@Persisted var arrayFloat: List<Float>
@Persisted var arrayDouble: List<Double>
@Persisted var arrayString: List<String>
@Persisted var arrayBinary: List<Data>
@Persisted var arrayDate: List<Date>
@Persisted var arrayDecimal: List<Decimal128>
@Persisted var arrayObjectId: List<ObjectId>
@Persisted var arrayAny: List<AnyRealmValue>
@Persisted var arrayUuid: List<UUID>
@Persisted var arrayOptBool: List<Bool?>
@Persisted var arrayOptInt: List<Int?>
@Persisted var arrayOptInt8: List<Int8?>
@Persisted var arrayOptInt16: List<Int16?>
@Persisted var arrayOptInt32: List<Int32?>
@Persisted var arrayOptInt64: List<Int64?>
@Persisted var arrayOptFloat: List<Float?>
@Persisted var arrayOptDouble: List<Double?>
@Persisted var arrayOptString: List<String?>
@Persisted var arrayOptBinary: List<Data?>
@Persisted var arrayOptDate: List<Date?>
@Persisted var arrayOptDecimal: List<Decimal128?>
@Persisted var arrayOptObjectId: List<ObjectId?>
@Persisted var arrayOptUuid: List<UUID?>
@Persisted var setBool: MutableSet<Bool>
@Persisted var setInt: MutableSet<Int>
@Persisted var setInt8: MutableSet<Int8>
@Persisted var setInt16: MutableSet<Int16>
@Persisted var setInt32: MutableSet<Int32>
@Persisted var setInt64: MutableSet<Int64>
@Persisted var setFloat: MutableSet<Float>
@Persisted var setDouble: MutableSet<Double>
@Persisted var setString: MutableSet<String>
@Persisted var setBinary: MutableSet<Data>
@Persisted var setDate: MutableSet<Date>
@Persisted var setDecimal: MutableSet<Decimal128>
@Persisted var setObjectId: MutableSet<ObjectId>
@Persisted var setAny: MutableSet<AnyRealmValue>
@Persisted var setUuid: MutableSet<UUID>
@Persisted var setOptBool: MutableSet<Bool?>
@Persisted var setOptInt: MutableSet<Int?>
@Persisted var setOptInt8: MutableSet<Int8?>
@Persisted var setOptInt16: MutableSet<Int16?>
@Persisted var setOptInt32: MutableSet<Int32?>
@Persisted var setOptInt64: MutableSet<Int64?>
@Persisted var setOptFloat: MutableSet<Float?>
@Persisted var setOptDouble: MutableSet<Double?>
@Persisted var setOptString: MutableSet<String?>
@Persisted var setOptBinary: MutableSet<Data?>
@Persisted var setOptDate: MutableSet<Date?>
@Persisted var setOptDecimal: MutableSet<Decimal128?>
@Persisted var setOptObjectId: MutableSet<ObjectId?>
@Persisted var setOptUuid: MutableSet<UUID?>
@Persisted var mapBool: Map<String, Bool>
@Persisted var mapInt: Map<String, Int>
@Persisted var mapInt8: Map<String, Int8>
@Persisted var mapInt16: Map<String, Int16>
@Persisted var mapInt32: Map<String, Int32>
@Persisted var mapInt64: Map<String, Int64>
@Persisted var mapFloat: Map<String, Float>
@Persisted var mapDouble: Map<String, Double>
@Persisted var mapString: Map<String, String>
@Persisted var mapBinary: Map<String, Data>
@Persisted var mapDate: Map<String, Date>
@Persisted var mapDecimal: Map<String, Decimal128>
@Persisted var mapObjectId: Map<String, ObjectId>
@Persisted var mapAny: Map<String, AnyRealmValue>
@Persisted var mapUuid: Map<String, UUID>
@Persisted var mapOptBool: Map<String, Bool?>
@Persisted var mapOptInt: Map<String, Int?>
@Persisted var mapOptInt8: Map<String, Int8?>
@Persisted var mapOptInt16: Map<String, Int16?>
@Persisted var mapOptInt32: Map<String, Int32?>
@Persisted var mapOptInt64: Map<String, Int64?>
@Persisted var mapOptFloat: Map<String, Float?>
@Persisted var mapOptDouble: Map<String, Double?>
@Persisted var mapOptString: Map<String, String?>
@Persisted var mapOptBinary: Map<String, Data?>
@Persisted var mapOptDate: Map<String, Date?>
@Persisted var mapOptDecimal: Map<String, Decimal128?>
@Persisted var mapOptObjectId: Map<String, ObjectId?>
@Persisted var mapOptUuid: Map<String, UUID?>
@Persisted(originProperty: "objectCol")
var linkingObjects: LinkingObjects<ModernAllTypesObject>
}
enum ModernIntEnum: Int, Codable, PersistableEnum {
case value1 = 1
case value2 = 3
case value3 = 5
}
enum ModernStringEnum: String, Codable, PersistableEnum {
case value1 = "a"
case value2 = "c"
case value3 = "e"
}
class ModernImplicitlyUnwrappedOptionalObject: Object {
@Persisted var optStringCol: String!
@Persisted var optBinaryCol: Data!
@Persisted var optDateCol: Date!
@Persisted var optDecimalCol: Decimal128!
@Persisted var optObjectIdCol: ObjectId!
@Persisted var optObjectCol: ModernImplicitlyUnwrappedOptionalObject!
@Persisted var optUuidCol: UUID!
}
class ModernLinkToPrimaryStringObject: Object {
@Persisted var pk = ""
@Persisted var object: ModernPrimaryStringObject?
@Persisted var objects: List<ModernPrimaryStringObject>
override class func primaryKey() -> String? {
return "pk"
}
}
class ModernUTF8Object: Object {
// swiftlint:disable:next identifier_name
@Persisted var ๆฑะบะพะปะพรฉะฝวขะบฦฑะฐู
๐ = "ๅผะทะฝะฐัะตะฝโข๐โโ โฑเฏนโฃ๏ธโโผโโโจโงญะธะตู
ุฑุญุจุง"
}
protocol ModernPrimaryKeyObject: Object {
associatedtype PrimaryKey: Equatable
var pk: PrimaryKey { get set }
}
class ModernPrimaryStringObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: String
}
class ModernPrimaryOptionalStringObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: String?
}
class ModernPrimaryIntObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int
}
class ModernPrimaryOptionalIntObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int?
}
class ModernPrimaryInt8Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int8
}
class ModernPrimaryOptionalInt8Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int8?
}
class ModernPrimaryInt16Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int16
}
class ModernPrimaryOptionalInt16Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int16?
}
class ModernPrimaryInt32Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int32
}
class ModernPrimaryOptionalInt32Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int32?
}
class ModernPrimaryInt64Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int64
}
class ModernPrimaryOptionalInt64Object: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: Int64?
}
class ModernPrimaryUUIDObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: UUID
}
class ModernPrimaryOptionalUUIDObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: UUID?
}
class ModernPrimaryObjectIdObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: ObjectId
}
class ModernPrimaryOptionalObjectIdObject: Object, ModernPrimaryKeyObject {
@Persisted(primaryKey: true) var pk: ObjectId?
}
class ModernCustomInitializerObject: Object {
@Persisted var stringCol: String
init(stringVal: String) {
stringCol = stringVal
super.init()
}
required override init() {
stringCol = ""
super.init()
}
}
class ModernConvenienceInitializerObject: Object {
@Persisted var stringCol = ""
convenience init(stringCol: String) {
self.init()
self.stringCol = stringCol
}
}
@objc(ModernObjcRenamedObject)
class ModernObjcRenamedObject: Object {
@Persisted var stringCol = ""
}
@objc(ModernObjcRenamedObjectWithTotallyDifferentName)
class ModernObjcArbitrarilyRenamedObject: Object {
@Persisted var boolCol = false
}
class ModernIntAndStringObject: Object {
@Persisted var intCol: Int
@Persisted var optIntCol: Int?
@Persisted var stringCol: String
@Persisted var optStringCol: String?
}
class ModernCollectionObject: Object {
@Persisted var list: List<ModernAllTypesObject>
@Persisted var set: MutableSet<ModernAllTypesObject>
@Persisted var map: Map<String, ModernAllTypesObject?>
}
class ModernCircleObject: Object {
@Persisted var obj: ModernCircleObject?
@Persisted var array: List<ModernCircleObject>
}
class ModernEmbeddedParentObject: Object {
@Persisted var object: ModernEmbeddedTreeObject1?
@Persisted var array: List<ModernEmbeddedTreeObject1>
}
class ModernEmbeddedPrimaryParentObject: Object {
@Persisted(primaryKey: true) var pk: Int = 0
@Persisted var object: ModernEmbeddedTreeObject1?
@Persisted var array: List<ModernEmbeddedTreeObject1>
}
protocol ModernEmbeddedTreeObject: EmbeddedObject {
var value: Int { get set }
}
class ModernEmbeddedTreeObject1: EmbeddedObject, ModernEmbeddedTreeObject {
@Persisted var value = 0
@Persisted var child: ModernEmbeddedTreeObject2?
@Persisted var children: List<ModernEmbeddedTreeObject2>
@Persisted(originProperty: "object")
var parent1: LinkingObjects<ModernEmbeddedParentObject>
@Persisted(originProperty: "array")
var parent2: LinkingObjects<ModernEmbeddedParentObject>
}
class ModernEmbeddedTreeObject2: EmbeddedObject, ModernEmbeddedTreeObject {
@Persisted var value = 0
@Persisted var child: ModernEmbeddedTreeObject3?
@Persisted var children: List<ModernEmbeddedTreeObject3>
@Persisted(originProperty: "child")
var parent3: LinkingObjects<ModernEmbeddedTreeObject1>
@Persisted(originProperty: "children")
var parent4: LinkingObjects<ModernEmbeddedTreeObject1>
}
class ModernEmbeddedTreeObject3: EmbeddedObject, ModernEmbeddedTreeObject {
@Persisted var value = 0
@Persisted(originProperty: "child")
var parent3: LinkingObjects<ModernEmbeddedTreeObject2>
@Persisted(originProperty: "children")
var parent4: LinkingObjects<ModernEmbeddedTreeObject2>
}
class SetterObservers: Object {
@Persisted var value: Int {
willSet {
willSetCallback?()
}
didSet {
didSetCallback?()
}
}
var willSetCallback: (() -> Void)?
var didSetCallback: (() -> Void)?
}
class ObjectWithArcMethodCategoryNames: Object {
// @objc properties with these names would crash with asan (and unreliably
// without it) because they would not have the correct behavior for the
// inferred ARC method family.
@Persisted var newValue: String
@Persisted var allocValue: String
@Persisted var copyValue: String
@Persisted var mutableCopyValue: String
@Persisted var initValue: String
}
|
a7424452caf056927429c4f045cf4dbd
| 33.459948 | 78 | 0.729229 | false | false | false | false |
DuostecDalian/Meijiabang
|
refs/heads/master
|
HiChongSwift/ZXYImageBrowser/ZXY_SheetViewCell.swift
|
apache-2.0
|
4
|
//
// ZXY_SheetViewCell.swift
// ZXYPrettysHealth
//
// Created by ๅฎๅจ on 15/1/16.
// Copyright (c) 2015ๅนด ๅฎๅจ. All rights reserved.
//
import UIKit
protocol SheetViewCellDelegate : class
{
func clickButtonWithIndex(index : Int) -> Void
}
let ZXY_SheetViewCellID = "ZXY_SheetViewCellID"
class ZXY_SheetViewCell: UITableViewCell {
private var btnString : String!
private var btnBack : UIColor = UIColor.whiteColor()
private var txtColor : UIColor = UIColor.blackColor()
private var txtBtn : UIButton?
private var currentIndex : Int?
weak var delegate : SheetViewCellDelegate?
func setBtnString(btnString: String!)
{
self.btnString = btnString
}
func setBackColor(btnColor: UIColor)
{
self.btnBack = btnColor
}
func setTxTColor(txtColor: UIColor)
{
self.txtColor = txtColor
}
func setCurrentIndex(index : Int)
{
self.currentIndex = index
}
func drawCurrentRect() -> Void
{
if let isNil = txtBtn
{
}
else
{
txtBtn = UIButton(frame: CGRectMake(15, 5, self.frame.size.width-30, self.frame.size.height-10))
//txtBtn?.frame =
txtBtn?.setTitle(btnString, forState: UIControlState.Normal)
txtBtn?.setTitleColor(txtColor, forState: UIControlState.Normal)
txtBtn?.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
txtBtn?.backgroundColor = self.btnBack
txtBtn?.layer.cornerRadius = 5
txtBtn?.layer.masksToBounds = true
txtBtn?.layer.borderWidth = 1/(UIScreen.mainScreen().scale)
txtBtn?.addTarget(self, action: Selector("clickBtn"), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(txtBtn!)
}
}
func clickBtn() -> Void
{
if(self.delegate != nil)
{
self.delegate?.clickButtonWithIndex(self.currentIndex!)
}
}
override func drawRect(rect: CGRect) {
self.selectionStyle = UITableViewCellSelectionStyle.None
super.drawRect(CGRectMake(0, 0, self.window!.bounds.width, 50))
//self.backgroundColor = UIColor(red: 236/255.0, green: 236/255.0, blue: 236/255.0, alpha: 1)
self.drawCurrentRect()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func drawLayer(layer: CALayer!, inContext ctx: CGContext!) {
super.drawLayer(layer, inContext: ctx)
}
}
|
8d66b7b49c634a87e2630db5e1b77865
| 28.208333 | 114 | 0.620542 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application
|
refs/heads/master
|
Chula Expo 2017/Chula Expo 2017/CoreData/RoundData+CoreDataProperties.swift
|
mit
|
1
|
//
// RoundData+CoreDataProperties.swift
// Chula Expo 2017
//
// Created by NOT on 1/23/2560 BE.
// Copyright ยฉ 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import Foundation
import CoreData
extension RoundData {
@nonobjc public class func fetchRequest() -> NSFetchRequest<RoundData> {
return NSFetchRequest<RoundData>(entityName: "RoundData");
}
@NSManaged public var activityId: String?
@NSManaged public var endTime: Date?
@NSManaged public var fullCapacity: Int16
@NSManaged public var id: String?
@NSManaged public var reserved: Int16
@NSManaged public var seatAvaliable: Int16
@NSManaged public var startTime: Date?
@NSManaged public var toActivity: ActivityData?
var dateSection: String
{
get
{
if self.startTime!.isToday()
{
return "TODAY"
}
else if self.startTime!.isTomorrow()
{
return "TOMORROW"
}
else if self.startTime!.isYesterday()
{
return "YESTERDAY"
}
else
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, EEE H m"
return dateFormatter.string(from: startTime! as Date)
}
}
}
var dateText: String
{
get
{
if self.startTime!.isToday()
{
return "Today"
}
else if self.startTime!.isTomorrow()
{
return "Tomorrow"
}
else if self.startTime!.isYesterday()
{
return "Yesterday"
}
else
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, EEE"
return dateFormatter.string(from: startTime! as Date)
}
}
}
}
extension Date {
static var day1 = Date.from(year: 2017, month: 3, day: 15)
static var day2 = Date.from(year: 2017, month: 3, day: 16)
static var day3 = Date.from(year: 2017, month: 3, day: 17)
static var day4 = Date.from(year: 2017, month: 3, day: 18)
static var day5 = Date.from(year: 2017, month: 3, day: 19)
static var day6 = Date.from(year: 2017, month: 3, day: 20)
static func from(year: Int, month: Int, day: Int) -> Date {
let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!
gregorianCalendar.timeZone = TimeZone(secondsFromGMT: 25200)!
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
let date = gregorianCalendar.date(from: dateComponents)!
return date
}
static func from(year: Int, month: Int, day: Int, hour: Int, minuite: Int) -> Date {
let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!
gregorianCalendar.timeZone = TimeZone(secondsFromGMT: 25200)!
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minuite
let date = gregorianCalendar.date(from: dateComponents)!
return date
}
func toThaiText() -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let day = calendar.component(.day, from: self)
let month = calendar.component(.month, from: self)
let year = calendar.component(.year, from: self)
let hour = calendar.component(.hour, from: self)
let minuite = calendar.component(.minute, from: self)
var minuiteText = "\(minuite)"
if minuite < 10{
minuiteText = "0\(minuite)"
}
var monthText = ""
switch month {
case 1:
monthText = "เธกเธเธฃเธฒเธเธก"
case 2:
monthText = "เธเธธเธกเธ เธฒเธเธฑเธเธเน"
case 3:
monthText = "March"
case 4:
monthText = "เนเธกเธฉเธฒเธขเธ"
case 5:
monthText = "เธกเธดเธเธธเธเธฒเธขเธ"
default:
monthText = "เธเธฑเธเธงเธฒเธเธก"
}
return ("\(day) \(monthText) \(year) โข \(hour):\(minuiteText)")
}
func toThaiText(withEnd end: Date) -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let day = calendar.component(.day, from: self)
let month = calendar.component(.month, from: self)
let hour = calendar.component(.hour, from: self)
let minuite = calendar.component(.minute, from: self)
let endDay = calendar.component(.day, from: end)
let endHour = calendar.component(.hour, from: end)
let endMin = calendar.component(.minute, from: end)
var minuiteText = "\(minuite)"
if minuite < 10{
minuiteText = "0\(minuite)"
}
var endMinuiteText = "\(endMin)"
if endMin < 10{
endMinuiteText = "0\(endMin)"
}
var monthText = ""
switch month {
case 1:
monthText = "เธกเธเธฃเธฒเธเธก"
case 2:
monthText = "เธเธธเธกเธ เธฒเธเธฑเธเธเน"
case 3:
monthText = "March"
case 4:
monthText = "เนเธกเธฉเธฒเธขเธ"
case 5:
monthText = "เธกเธดเธเธธเธเธฒเธขเธ"
default:
monthText = "เธเธฑเธเธงเธฒเธเธก"
}
var dayText = "\(day)"
if endDay != day {
dayText = ("\(dayText)-\(endDay)")
}
return ("\(dayText) \(monthText) โข \(hour):\(minuiteText)-\(endHour):\(endMinuiteText)")
}
func toThaiTextOnlyDate(withEnd end: Date) -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let day = calendar.component(.day, from: self)
let month = calendar.component(.month, from: self)
let endDay = calendar.component(.day, from: end)
var monthText = ""
switch month {
case 1:
monthText = "เธกเธเธฃเธฒเธเธก"
case 2:
monthText = "เธเธธเธกเธ เธฒเธเธฑเธเธเน"
case 3:
monthText = "March"
case 4:
monthText = "เนเธกเธฉเธฒเธขเธ"
case 5:
monthText = "เธกเธดเธเธธเธเธฒเธขเธ"
default:
monthText = "เธเธฑเธเธงเธฒเธเธก"
}
var dayText = "\(day)"
if endDay != day {
dayText = ("\(dayText)-\(endDay)")
}
return ("\(dayText) \(monthText)")
}
func toTimeText() -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let hour = calendar.component(.hour, from: self)
let minuite = calendar.component(.minute, from: self)
var minuiteText = "\(minuite)"
if minuite < 10{
minuiteText = "0\(minuite)"
}
return ("\(hour):\(minuiteText)")
}
func isGreaterThanDate(_ dateToCompare: Date) -> Bool {
//Declare Variables
var isGreater = false
//Compare Values
if self.compare(dateToCompare) == ComparisonResult.orderedDescending {
isGreater = true
}
//Return Result
return isGreater
}
func isLessThanDate(_ dateToCompare: Date) -> Bool {
//Declare Variables
var isLess = false
//Compare Values
if self.compare(dateToCompare) == ComparisonResult.orderedAscending {
isLess = true
}
//Return Result
return isLess
}
func equalToDate(_ dateToCompare: Date) -> Bool {
//Declare Variables
var isEqualTo = false
//Compare Values
if self.compare(dateToCompare) == ComparisonResult.orderedSame {
isEqualTo = true
}
//Return Result
return isEqualTo
}
func addDays(daysToAdd: Int) -> Date {
let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24
let dateWithDaysAdded: Date = self.addingTimeInterval(secondsInDays)
//Return Result
return dateWithDaysAdded
}
func addHours(hoursToAdd: Int) -> Date {
let secondsInHours: TimeInterval = Double(hoursToAdd) * 60 * 60
let dateWithHoursAdded: Date = self.addingTimeInterval(secondsInHours)
//Return Result
return dateWithHoursAdded
}
func isToday() -> Bool{
var isToday = false
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let today = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 0, to: Date())!)
let tomorrow = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 1, to: Date())!)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, EEE H m"
// print("TODAY == \(dateFormatter.string(from: today))")
// print("TOMORROW == \(dateFormatter.string(from: tomorrow))")
if(self.isLessThanDate(tomorrow)){
print("PASS1")
if(self.isGreaterThanDate(today) || self.equalToDate(today)){
isToday = true
// print("PASS2")
}
// print("MISS2")
}
// print("MISS1")
return isToday
}
func isTomorrow() -> Bool{
var isTomorrow = false
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let twoDayAfter = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 2, to: Date())!)
let tomorrow = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 1, to: Date())!)
if(self.isLessThanDate(twoDayAfter)){
if(self.isGreaterThanDate(tomorrow) || self.equalToDate(tomorrow)){
isTomorrow = true
}
}
return isTomorrow
}
func isYesterday() -> Bool{
var isYesterday = false
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let today = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 0, to: Date())!)
let yesterday = calendar.startOfDay(for: calendar.date(byAdding: .day, value: -1, to: Date())!)
if(self.isLessThanDate(today)){
// print("PASS1")
if(self.isGreaterThanDate(yesterday) || self.equalToDate( yesterday)){
isYesterday = true
// print("PASS2")
}
}
return isYesterday
}
func isInRangeOf(start: Date?, end: Date?) -> Bool{
if (start == nil || end == nil){
return false
}
// print("condition \(start!.toThaiText()) - \(end!.toThaiText()) compareto \(self.toThaiText()))")
return self.isLessThanDate(end!) && (self.isGreaterThanDate(start!) || self.equalToDate(start!))
}
func checkInday() -> Int{
if self.isInRangeOf(start: Date.day1, end: Date.day2){
return 1
}
else if self.isInRangeOf(start: Date.day2, end: Date.day3){
return 2
}
else if self.isInRangeOf(start: Date.day3, end: Date.day4){
return 3
}
else if self.isInRangeOf(start: Date.day4, end: Date.day5){
return 4
}
else if self.isInRangeOf(start: Date.day5, end: Date.day6){
return 5
}
return 0
}
}
|
f6af674bfc03d8c72759cb99164a5892
| 29.042394 | 106 | 0.538889 | false | false | false | false |
NachoSoto/Carthage
|
refs/heads/master
|
Source/carthage/Build.swift
|
mit
|
1
|
//
// Build.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-10-11.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import CarthageKit
import Commandant
import Foundation
import LlamaKit
import ReactiveCocoa
public struct BuildCommand: CommandType {
public let verb = "build"
public let function = "Build the project's dependencies"
public func run(mode: CommandMode) -> Result<()> {
return ColdSignal.fromResult(BuildOptions.evaluate(mode))
.map { self.buildWithOptions($0) }
.merge(identity)
.wait()
}
/// Builds a project with the given options.
public func buildWithOptions(options: BuildOptions) -> ColdSignal<()> {
return self.openTemporaryLogFile(options)
.map { (stdoutHandle, temporaryURL) -> ColdSignal<()> in
let directoryURL = NSURL.fileURLWithPath(options.directoryPath, isDirectory: true)!
let (stdoutSignal, schemeSignals) = self.buildProjectInDirectoryURL(directoryURL, options: options)
stdoutSignal.observe { data in
stdoutHandle.writeData(data)
stdoutHandle.synchronizeFile()
}
let formatting = options.colorOptions.formatting
return schemeSignals
.concat(identity)
.on(started: {
if let temporaryURL = temporaryURL {
carthage.println(formatting.bullets + "xcodebuild output can be found in " + formatting.path(string: temporaryURL.path!))
}
}, next: { (project, scheme) in
carthage.println(formatting.bullets + "Building scheme " + formatting.quote(scheme) + " in " + formatting.projectName(string: project.description))
})
.then(.empty())
}
.merge(identity)
}
/// Builds the project in the given directory, using the given options.
///
/// Returns a hot signal of `stdout` from `xcodebuild`, and a cold signal of
/// cold signals representing each scheme being built.
private func buildProjectInDirectoryURL(directoryURL: NSURL, options: BuildOptions) -> (HotSignal<NSData>, ColdSignal<BuildSchemeSignal>) {
let (stdoutSignal, stdoutSink) = HotSignal<NSData>.pipe()
let project = Project(directoryURL: directoryURL)
var buildSignal = project.loadCombinedCartfile()
.map { _ in project }
.catch { error in
if options.skipCurrent {
return .error(error)
} else {
// Ignore Cartfile loading failures. Assume the user just
// wants to build the enclosing project.
return .empty()
}
}
.mergeMap { project in
return project
.migrateIfNecessary(options.colorOptions)
.on(next: carthage.println)
.then(.single(project))
}
.mergeMap { (project: Project) -> ColdSignal<BuildSchemeSignal> in
let (dependenciesOutput, dependenciesSignals) = project.buildCheckedOutDependenciesWithConfiguration(options.configuration, forPlatform: options.buildPlatform.platform)
dependenciesOutput.observe(stdoutSink)
return dependenciesSignals
}
if !options.skipCurrent {
let (currentOutput, currentSignals) = buildInDirectory(directoryURL, withConfiguration: options.configuration, platform: options.buildPlatform.platform)
currentOutput.observe(stdoutSink)
buildSignal = buildSignal.concat(currentSignals)
}
return (stdoutSignal, buildSignal)
}
/// Opens a temporary file for logging, returning the handle and the URL to
/// the file on disk.
private func openTemporaryLogFile(options: BuildOptions) -> ColdSignal<(NSFileHandle, NSURL?)> {
if options.verbose {
let out: (NSFileHandle, NSURL?) = (NSFileHandle.fileHandleWithStandardOutput(), nil)
return .single(out)
}
return ColdSignal.lazy {
var temporaryDirectoryTemplate: ContiguousArray<CChar> = NSTemporaryDirectory().stringByAppendingPathComponent("carthage-xcodebuild.XXXXXX.log").nulTerminatedUTF8.map { CChar($0) }
let logFD = temporaryDirectoryTemplate.withUnsafeMutableBufferPointer { (inout template: UnsafeMutableBufferPointer<CChar>) -> Int32 in
return mkstemps(template.baseAddress, 4)
}
if logFD < 0 {
return .error(NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil))
}
let temporaryPath = temporaryDirectoryTemplate.withUnsafeBufferPointer { (ptr: UnsafeBufferPointer<CChar>) -> String in
return String.fromCString(ptr.baseAddress)!
}
let stdoutHandle = NSFileHandle(fileDescriptor: logFD, closeOnDealloc: true)
let temporaryURL = NSURL.fileURLWithPath(temporaryPath, isDirectory: false)!
let out: (NSFileHandle, NSURL?) = (stdoutHandle, temporaryURL)
return .single(out)
}
}
}
public struct BuildOptions: OptionsType {
public let configuration: String
public let buildPlatform: BuildPlatform
public let skipCurrent: Bool
public let colorOptions: ColorOptions
public let verbose: Bool
public let directoryPath: String
public static func create(configuration: String)(buildPlatform: BuildPlatform)(skipCurrent: Bool)(colorOptions: ColorOptions)(verbose: Bool)(directoryPath: String) -> BuildOptions {
return self(configuration: configuration, buildPlatform: buildPlatform, skipCurrent: skipCurrent, colorOptions: colorOptions, verbose: verbose, directoryPath: directoryPath)
}
public static func evaluate(m: CommandMode) -> Result<BuildOptions> {
return create
<*> m <| Option(key: "configuration", defaultValue: "Release", usage: "the Xcode configuration to build")
<*> m <| Option(key: "platform", defaultValue: .All, usage: "the platform to build for (one of โallโ, โMacโ, or โiOSโ)")
<*> m <| Option(key: "skip-current", defaultValue: true, usage: "don't skip building the Carthage project (in addition to its dependencies)")
<*> ColorOptions.evaluate(m)
<*> m <| Option(key: "verbose", defaultValue: false, usage: "print xcodebuild output inline")
<*> m <| Option(defaultValue: NSFileManager.defaultManager().currentDirectoryPath, usage: "the directory containing the Carthage project")
}
}
/// Represents the userโs chosen platform to build for.
public enum BuildPlatform: Equatable {
/// Build for all available platforms.
case All
/// Build only for iOS.
case iOS
/// Build only for OS X.
case Mac
/// The `Platform` corresponding to this setting.
public var platform: Platform? {
switch self {
case .All:
return nil
case .iOS:
return .iOS
case .Mac:
return .Mac
}
}
}
public func == (lhs: BuildPlatform, rhs: BuildPlatform) -> Bool {
switch (lhs, rhs) {
case (.All, .All):
return true
case (.iOS, .iOS):
return true
case (.Mac, .Mac):
return true
default:
return false
}
}
extension BuildPlatform: Printable {
public var description: String {
switch self {
case .All:
return "all"
case .iOS:
return "iOS"
case .Mac:
return "Mac"
}
}
}
extension BuildPlatform: ArgumentType {
public static let name = "platform"
private static let acceptedStrings: [String: BuildPlatform] = [
"Mac": .Mac, "macosx": .Mac,
"iOS": .iOS, "iphoneos": .iOS, "iphonesimulator": .iOS,
"all": .All
]
public static func fromString(string: String) -> BuildPlatform? {
for (key, platform) in acceptedStrings {
if string.caseInsensitiveCompare(key) == NSComparisonResult.OrderedSame {
return platform
}
}
return nil
}
}
|
ef3d3e850b401ef7d9fe7023dcb7d331
| 30.795556 | 183 | 0.721694 | false | false | false | false |
AccessLite/BYT-Golden
|
refs/heads/master
|
BYT/Models/FoaasTemplate.swift
|
mit
|
1
|
//
// FoaasTemplate.swift
// AC3.2-BiteYourThumb
//
// Created by Louis Tur on 11/17/16.
// Copyright ยฉ 2016 C4Q. All rights reserved.
//
import Foundation
internal struct FoaasKey {
internal static let from: String = "from"
internal static let company: String = "company"
internal static let tool: String = "tool"
internal static let name: String = "name"
internal static let doAction: String = "do"
internal static let something: String = "something"
internal static let thing: String = "thing"
internal static let behavior: String = "behavior"
internal static let language: String = "language"
internal static let reaction: String = "reaction"
internal static let noun: String = "noun"
internal static let reference: String = "reference"
}
internal struct FoaasTemplate {
let from: String
let company: String?
let tool: String?
let name: String?
let doAction: String?
let something: String?
let thing: String?
let behavior: String?
let language: String?
let reaction: String?
let noun: String?
let reference: String?
}
extension FoaasTemplate: JSONConvertible {
init?(json: [String : AnyObject]) {
guard let jFrom = json[FoaasKey.from] as? String else {
return nil
}
self.from = jFrom
self.company = json[FoaasKey.company] as? String
self.tool = json[FoaasKey.tool] as? String
self.name = json[FoaasKey.name] as? String
self.doAction = json[FoaasKey.doAction] as? String
self.something = json[FoaasKey.something] as? String
self.thing = json[FoaasKey.thing] as? String
self.behavior = json[FoaasKey.behavior] as? String
self.language = json[FoaasKey.language] as? String
self.reaction = json[FoaasKey.reaction] as? String
self.noun = json[FoaasKey.noun] as? String
self.reference = json[FoaasKey.reference] as? String
}
func toJson() -> [String : AnyObject] {
return [:]
}
}
|
338c427492d2bf5f17b8690f6b2a0791
| 28.553846 | 59 | 0.695471 | false | false | false | false |
JaSpa/swift
|
refs/heads/master
|
stdlib/public/core/LifetimeManager.swift
|
apache-2.0
|
6
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluate `f()` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluate `f(x)` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
extension String {
/// Invokes the given closure on the contents of the string, represented as a
/// pointer to a null-terminated sequence of UTF-8 code units.
///
/// The `withCString(_:)` method ensures that the sequence's lifetime extends
/// through the execution of `body`. The pointer argument to `body` is only
/// valid for the lifetime of the closure. Do not escape it from the closure
/// for later use.
///
/// - Parameter body: A closure that takes a pointer to the string's UTF-8
/// code unit sequence as its sole argument. If the closure has a return
/// value, it is used as the return value of the `withCString(_:)` method.
/// The pointer argument is valid only for the duration of the closure's
/// execution.
/// - Returns: The return value of the `body` closure, if any.
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.utf8CString.withUnsafeBufferPointer {
try body($0.baseAddress!)
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Invokes the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a mutable pointer to `arg` as its sole
/// argument. If the closure has a return value, it is used as the return
/// value of the `withUnsafeMutablePointer(to:_:)` function. The pointer
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafePointer(to:_:)`
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in/out parameters (and default-constructible out
/// parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `arg` as its sole argument. If
/// the closure has a return value, it is used as the return value of the
/// `withUnsafePointer(to:_:)` function. The pointer argument is valid
/// only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafeMutablePointer(to:_:)`
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
@available(*, unavailable, renamed: "withUnsafeMutablePointer(to:_:)")
public func withUnsafeMutablePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, renamed: "withUnsafePointer(to:_:)")
public func withUnsafePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
|
e11f013d8bd1ae22ed6143e99f4f1198
| 34.134831 | 88 | 0.676847 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
refs/heads/master
|
Pods/HXPHPicker/Sources/HXPHPicker/Core/Config/SelectBoxConfiguration.swift
|
mit
|
1
|
//
// SelectBoxConfiguration.swift
// HXPHPickerExample
//
// Created by Slience on 2020/12/29.
// Copyright ยฉ 2020 Silence. All rights reserved.
//
import UIKit
// MARK: ้ๆฉๆก้
็ฝฎ็ฑป
public struct SelectBoxConfiguration {
/// ้ๆฉๆก็ๅคงๅฐ
public var size: CGSize = CGSize(width: 25, height: 25)
/// ้ๆฉๆก็ๆ ทๅผ
public var style: SelectBoxView.Style = .number
/// ๆ ้ข็ๆๅญๅคงๅฐ
public var titleFontSize: CGFloat = 16
/// ้ไธญไนๅ็ ๆ ้ข ้ข่ฒ
public var titleColor: UIColor = .white
/// ๆ้ป้ฃๆ ผไธ้ไธญไนๅ็ ๆ ้ข ้ข่ฒ
public var titleDarkColor: UIColor = .white
/// ้ไธญ็ถๆไธๅพๅพ็ๅฎฝๅบฆ
public var tickWidth: CGFloat = 1.5
/// ้ไธญไนๅ็ ๅพๅพ ้ข่ฒ
public var tickColor: UIColor = .white
/// ๆ้ป้ฃๆ ผไธ้ไธญไนๅ็ ๅพๅพ ้ข่ฒ
public var tickDarkColor: UIColor = .black
/// ๆช้ไธญๆถๆกๆกไธญ้ด็้ข่ฒ
public var backgroundColor: UIColor = .black.withAlphaComponent(0.4)
/// ๆ้ป้ฃๆ ผไธๆช้ไธญๆถๆกๆกไธญ้ด็้ข่ฒ
public var darkBackgroundColor: UIColor = .black.withAlphaComponent(0.2)
/// ้ไธญไนๅ็่ๆฏ้ข่ฒ
public var selectedBackgroundColor: UIColor = .systemTintColor
/// ๆ้ป้ฃๆ ผไธ้ไธญไนๅ็่ๆฏ้ข่ฒ
public var selectedBackgroudDarkColor: UIColor = .systemTintColor
/// ๆช้ไธญๆถ็่พนๆกๅฎฝๅบฆ
public var borderWidth: CGFloat = 1.5
/// ๆช้ไธญๆถ็่พนๆก้ข่ฒ
public var borderColor: UIColor = .white
/// ๆ้ป้ฃๆ ผไธๆช้ไธญๆถ็่พนๆก้ข่ฒ
public var borderDarkColor: UIColor = .white
public init() { }
}
|
9931a1e6ea2a4a2ad907e6d9a8cd9297
| 22.783333 | 76 | 0.644008 | false | false | false | false |
zhou9734/Warm
|
refs/heads/master
|
Warm/Classes/Home/Model/WTeacher.swift
|
mit
|
1
|
//
// WTeacher.swift
// Warm
//
// Created by zhoucj on 16/9/25.
// Copyright ยฉ 2016ๅนด zhoucj. All rights reserved.
//
import UIKit
class WTeacher: NSObject {
//id
var id: Int64 = -1
//็ฑปๅ
var type: Int64 = -1
//็ถๆ
var status: Int64 = -1
//ๅๅปบๆถ้ด
var ctime: Int64 = -1
//ๆดๆฐๆถ้ด
var utime: Int64 = -1
//็ปๅฝๆถ้ด
var logintime: Int64 = -1
//ๆๆบๅท็
var mobile: String = ""
//้ฎไปถ
var email: String = ""
//ๆต็งฐ
var nickname: String = ""
//ๆงๅซ
var gender: Int64 = 1
//็ๆฅ
var birthday: Int64 = -2209017600
//ไธชๆง็ญพๅ
var signature: String = ""
//ๅคดๅๅฐๅ
var avatar: String?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
//้ฒๆฒปๆฒกๆๅน้
ๅฐ็keyๆฅ้
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
|
f0aae0a80a64f2e23936761272954cb3
| 18.311111 | 76 | 0.561565 | false | false | false | false |
DrabWeb/Komikan
|
refs/heads/master
|
Komikan/Komikan/KMEHLoginViewController.swift
|
gpl-3.0
|
1
|
//
// KMEHLoginViewController.swift
// Komikan
//
// Created by Seth on 2016-02-13.
//
import Cocoa
import WebKit
class KMEHLoginViewController: NSViewController, WebFrameLoadDelegate {
/// The main window of the login view controller
var loginWindow : NSWindow!;
/// The web view that is used to login to E-Hentai
@IBOutlet weak var webView: WebView!
/// The label in the titlebar to show the URL
@IBOutlet weak var urlLabel: NSTextField!
/// Have we already opened ExHentai?
var openedExhentai : Bool = false;
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
// Style the window
styleWindow();
// Load the web view
loadWebView();
// Set the WebView's frame load delegate
webView.frameLoadDelegate = self;
/// The webviews cookie storage
let storage : HTTPCookieStorage = HTTPCookieStorage.shared;
// For every cookie in the cookie storage...
for(_, currentCookie) in (storage.cookies?.enumerated())! {
// Delete the cookie
storage.deleteCookie(currentCookie);
}
// Reload the user defaults
UserDefaults.standard.synchronize();
}
func webView(_ sender: WebView!, didStartProvisionalLoadFor frame: WebFrame!) {
// Update the webview
updateWebView();
}
/// Updates the window title to match the webviews URL, if we are on exhentai it stores the cookies and closes the webview, and if we are on sadpanda it opens the guide to get past it
func updateWebView() {
// Set the URL labels string value to the current URL in the webview
urlLabel.stringValue = webView.mainFrameURL;
// If the cookies contains a "ipb_member_id" and we arent already on ExHentai...
if(webView.stringByEvaluatingJavaScript(from: "document.cookie").contains("ipb_member_id") && !openedExhentai) {
/// The URL request to open ExHentai
let exLoadRequest : URLRequest = URLRequest(url: URL(string: "http://exhentai.org")!);
// Load the EX request
webView.mainFrame.load(exLoadRequest);
// Say we have already opened ExHentai
openedExhentai = true;
}
// If we have opened ExHentai and the URL is not just http://exhentai.org...
if(openedExhentai && !(webView.mainFrameURL == "http://exhentai.org")) {
// Write the cookies into the Application Supports excookies file
do {
// Try to write the cookies
try webView.stringByEvaluatingJavaScript(from: "document.cookie").write(toFile: NSHomeDirectory() + "/Library/Application Support/Komikan/excookies", atomically: true, encoding: String.Encoding.utf8);
}
// If there is an error...
catch _ as NSError {
// Do nothing
}
// Close the window
loginWindow.close();
}
// If we are just on http://exhentai.org (Meaning the user is on a sad panda...)
else if(webView.mainFrameURL == "http://exhentai.org") {
// Close the window
loginWindow.close();
// Open https://a.pomf.cat/lkyaft.png . It is a small flow graph posted on /h/ that tells users how to get past sad panda(Though they really shouldnt need this, im just being kind)
NSWorkspace.shared().open(URL(string: "https://a.pomf.cat/lkyaft.png")!);
}
}
/// Loads the web view
func loadWebView() {
/// The URL request to open E-Hentai
let ehLoadRequest : URLRequest = URLRequest(url: URL(string: "http://g.e-hentai.org/home.php")!);
// Load the EH request
webView.mainFrame.load(ehLoadRequest);
// Do the initial webview update
updateWebView();
}
/// Styles the window
func styleWindow() {
// Set the window to the last application window
loginWindow = NSApplication.shared().windows.last!;
// Set the window to have a full size content view
loginWindow.styleMask.insert(NSFullSizeContentViewWindowMask);
// Hide the titlebar
loginWindow.titlebarAppearsTransparent = true;
// Hide the title of the window
loginWindow.titleVisibility = NSWindowTitleVisibility.hidden;
// Center the window
loginWindow.setFrame(NSRect(x: (NSScreen.main()!.frame.width / 2) - (480 / 2), y: (NSScreen.main()!.frame.height / 2) - (500 / 2), width: 480, height: 500), display: false);
}
}
|
f07514c9b9b64a4c01f7ef3ca963639d
| 37.047619 | 216 | 0.600125 | false | false | false | false |
LittoCats/coffee-mobile
|
refs/heads/master
|
CoffeeMobile/Base/Utils/NSFundationExtension/CMNSDataExtension.swift
|
apache-2.0
|
1
|
//
// CMNSDataExtension.swift
// CoffeeMobile
//
// Created by ็จๅทๅท on 5/22/15.
// Copyright (c) 2015 Littocats. All rights reserved.
//
import Foundation
import MiniZip
extension NSData {
/**
MARK: ๅ็ผฉ๏ผๅฐพ้จ 8 byte ่กจ็คบๅ็ผฉๅ็้ฟๅบฆ (UInt64)
*/
func deflate() -> NSData! {
var compressedLength = compressBound(uLong(self.length))
var buffer = UnsafeMutablePointer<Bytef>.alloc(Int(compressedLength))
var ret: NSMutableData?
if Z_OK == compress(buffer, &compressedLength, UnsafePointer<Bytef>(self.bytes), uLong(self.length)) {
var inflatedLength = UInt64(self.length)
ret = NSMutableData(bytes: buffer, length: Int(compressedLength))
ret?.appendBytes(&inflatedLength, length: sizeof(UInt64))
}
buffer.dealloc(1)
return ret
}
/**
MARK: ่งฃๅ็ผฉ
*/
func inflate() -> NSData!{
var sourceLength: UInt64 = 0
self.getBytes(&sourceLength, range: NSMakeRange(self.length - sizeof(UInt64), sizeof(UInt64)))
var buffer = UnsafeMutablePointer<Bytef>.alloc(Int(sourceLength))
var bufferLength = uLong(sourceLength)
var ret: NSData?
if Z_OK == uncompress(buffer, &bufferLength, UnsafePointer<Bytef>(self.bytes), uLong(self.length - sizeof(UInt64))){
ret = NSData(bytes: buffer, length: Int(bufferLength))
}
buffer.dealloc(1)
return ret
}
}
|
dce6966e53f0b386e87d1b7e1984be68
| 28.58 | 125 | 0.6119 | false | false | false | false |
peterdruska/GPSwift
|
refs/heads/master
|
GPSwift/SwifTime.swift
|
gpl-2.0
|
1
|
//
// SwifTime.swift
// GPSwift
//
// Created by Peter Druska on 11.3.2015.
// Copyright (c) 2015 Become.sk. All rights reserved.
//
import Foundation
struct DateAndTime {
var date = String()
var time = String()
var rawValue = NSDate()
}
class SwifTime {
var timeStamp = NSDate()
var dateAndTime = DateAndTime()
init (timeStamp: NSDate) {
self.timeStamp = timeStamp
}
func readTime(dateFormat: String, timeFormat: String) {
let formatter = NSDateFormatter()
formatter.dateFormat = dateFormat
dateAndTime.date = formatter.stringFromDate(timeStamp)
formatter.dateFormat = timeFormat
dateAndTime.time = formatter.stringFromDate(timeStamp)
dateAndTime.rawValue = timeStamp
}
}
|
67f128a33ecdd4a18fd6de8ef0c46806
| 21.361111 | 62 | 0.636816 | false | false | false | false |
1170197998/Swift-DEMO
|
refs/heads/master
|
AddressBook/Pods/SnapKit/Source/Typealiases.swift
|
apache-2.0
|
51
|
//
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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
#if os(iOS) || os(tvOS)
import UIKit
typealias LayoutRelation = NSLayoutRelation
typealias LayoutAttribute = NSLayoutAttribute
typealias LayoutPriority = UILayoutPriority
#else
import AppKit
typealias LayoutRelation = NSLayoutConstraint.Relation
typealias LayoutAttribute = NSLayoutConstraint.Attribute
typealias LayoutPriority = NSLayoutConstraint.Priority
#endif
|
c040af257b160b5289e4ea5b9bbd0d6f
| 42.216216 | 81 | 0.75985 | false | false | false | false |
apple/swift-driver
|
refs/heads/main
|
Sources/SwiftDriver/IncrementalCompilation/Bitcode/Bits.swift
|
apache-2.0
|
1
|
//===--------------- Bits.swift - Bitstream helpers ----------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import struct TSCBasic.ByteString
struct Bits: RandomAccessCollection {
var buffer: ByteString
var startIndex: Int { return 0 }
var endIndex: Int { return buffer.count * 8 }
subscript(index: Int) -> UInt8 {
let byte = buffer.contents[index / 8]
return (byte >> UInt8(index % 8)) & 1
}
func readBits(atOffset offset: Int, count: Int) -> UInt64 {
precondition(count >= 0 && count <= 64)
precondition(offset >= 0)
precondition(offset &+ count >= offset)
precondition(offset &+ count <= self.endIndex)
return buffer.contents.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
let upperBound = offset &+ count
let topByteIndex = upperBound >> 3
var result: UInt64 = 0
if upperBound & 7 != 0 {
let mask: UInt8 = (1 << UInt8(upperBound & 7)) &- 1
result = UInt64(bytes[topByteIndex] & mask)
}
for i in ((offset >> 3)..<(upperBound >> 3)).reversed() {
result <<= 8
result |= UInt64(bytes[i])
}
if offset & 7 != 0 {
result >>= UInt64(offset & 7)
}
return result
}
}
}
extension Bits {
struct Cursor {
enum Error: Swift.Error { case bufferOverflow }
let buffer: Bits
private var offset: Int = 0
init(buffer: Bits) {
self.buffer = buffer
}
init(buffer: ByteString) {
self.init(buffer: Bits(buffer: buffer))
}
var isAtStart: Bool {
return offset == buffer.startIndex
}
var isAtEnd: Bool {
return offset == buffer.count
}
func peek(_ count: Int) throws -> UInt64 {
if buffer.count - offset < count { throw Error.bufferOverflow }
return buffer.readBits(atOffset: offset, count: count)
}
mutating func read(_ count: Int) throws -> UInt64 {
defer { offset += count }
return try peek(count)
}
mutating func read(bytes count: Int) throws -> ArraySlice<UInt8> {
precondition(count >= 0)
precondition(offset & 0b111 == 0)
let newOffset = offset &+ (count << 3)
precondition(newOffset >= offset)
if newOffset > buffer.count { throw Error.bufferOverflow }
defer { offset = newOffset }
return buffer.buffer.contents.dropFirst(offset >> 3).prefix((newOffset - offset) >> 3)
}
mutating func skip(bytes count: Int) throws {
precondition(count >= 0)
precondition(offset & 0b111 == 0)
let newOffset = offset &+ (count << 3)
precondition(newOffset >= offset)
if newOffset > buffer.count { throw Error.bufferOverflow }
offset = newOffset
}
mutating func advance(toBitAlignment align: Int) throws {
precondition(align > 0)
precondition(offset &+ (align&-1) >= offset)
precondition(align & (align &- 1) == 0)
if offset % align == 0 { return }
offset = (offset &+ align) & ~(align &- 1)
if offset > buffer.count { throw Error.bufferOverflow }
}
}
}
|
c31c1c64b253416ae857b73488ece8d2
| 29.557522 | 92 | 0.59861 | false | false | false | false |
bingFly/weibo
|
refs/heads/master
|
weibo/weibo/Classes/UI/Home/HBHomeCell.swift
|
mit
|
1
|
//
// HBHomeCell.swift
// weibo
//
// Created by hanbing on 15/3/9.
// Copyright (c) 2015ๅนด fly. All rights reserved.
//
import UIKit
class HBHomeCell: UITableViewCell {
/// ๅคดๅ
@IBOutlet weak var iconImage: UIImageView!
/// ๅงๅ
@IBOutlet weak var nameLabel: UILabel!
/// ไผๅๅพๆ
@IBOutlet weak var memberIcon: UIImageView!
/// ่ฎค่ฏๅพๆ
@IBOutlet weak var vipIcon: UIImageView!
/// ๆถ้ด
@IBOutlet weak var timeLabel: UILabel!
/// ๆฅๆบ
@IBOutlet weak var sourceLabel: UILabel!
/// ๅพฎๅๆญฃๆ
@IBOutlet weak var contextLabel: UILabel!
/// ้
ๅพ
@IBOutlet weak var pictureView: UICollectionView!
/// ๆดไฝ้ซๅบฆ
@IBOutlet weak var pictureHeight: NSLayoutConstraint!
/// ๆดไฝๅฎฝๅบฆ
@IBOutlet weak var pictureWidth: NSLayoutConstraint!
@IBOutlet weak var pictureLayout: UICollectionViewFlowLayout!
/// ่ฝฌๅๅพฎๅๆๆฌ
@IBOutlet weak var forwordLabel: UILabel!
/// ๅบ้จๅทฅๅ
ทๆก
@IBOutlet weak var bottomView: UIView!
/// ๅฎไน้ญๅ
var photoDidSelected: ((status: HBStatus, photoIndex: Int) -> ())?
var status: HBStatus? {
didSet {
nameLabel.text = status!.user!.name
timeLabel.text = status!.created_at
sourceLabel.text = status!.formatSource
contextLabel.text = status!.text
vipIcon.image = status!.user!.verifiedImage
// ็ญ็บงๅพๆ
memberIcon.image = status!.user!.mkImage
if let url = status?.user?.profile_image_url {
NetworkManager.sharedManager.requestImage(url, { (result, error) -> () in
if let img = result as? UIImage {
self.iconImage.image = img
}
})
}
// ่ฎพ็ฝฎๅพ็ๅคงๅฐ
let resultSize = calcPictureViewSize()
pictureHeight.constant = resultSize.viewSize.height
pictureWidth.constant = resultSize.viewSize.width
pictureLayout.itemSize = resultSize.itemSize
if status?.retweeted_status != nil {
forwordLabel.text = "@"+status!.retweeted_status!.user!.name! + ":" + status!.retweeted_status!.text!
}
// ๅทๆฐ้
ๅพ่งๅพ
pictureView.reloadData()
}
}
// ๅคๆญcell็็ฑปๅ
class func switchCellType(status: HBStatus) -> String {
if status.retweeted_status != nil {
return "forwordCell"
} else {
return "homeCell"
}
}
func calcPictureViewSize() -> (itemSize: CGSize, viewSize: CGSize){
let s: CGFloat = 90
// ๅพ็ๅคงๅฐ
var itemSize = CGSizeMake(s, s)
// ่งๅพๅคงๅฐ
var viewSize = CGSizeZero
let count = status?.forword_urls?.count ?? 0
if count == 0 {
return (itemSize, viewSize)
}
if count == 1 {
let url = status!.forword_urls?[0].thumbnail_pic
let path = NetworkManager.sharedManager.fullImageCachePath(url!)
if let img = UIImage(contentsOfFile: path) {
return (img.size, img.size)
} else {
return (itemSize, viewSize)
}
}
// ้ด่ท
let m: CGFloat = 10
if count == 4 {
viewSize = CGSizeMake(s * 2 + m, s * 2 + m)
} else {
let row = (count - 1) / 3
var col = 3
if count == 2 {
col = 2
}
viewSize = CGSizeMake(CGFloat(col) * s + 2 * m, (CGFloat(row) + 1) * s + CGFloat(row) * m)
}
return (itemSize, viewSize)
}
func cellHeight(status: HBStatus) -> CGFloat {
self.status = status
layoutIfNeeded()
return CGRectGetMaxY(bottomView.frame)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func awakeFromNib() {
super.awakeFromNib()
contextLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 20
forwordLabel?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 20
}
}
extension HBHomeCell: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return status?.forword_urls?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! HBPictureCell
cell.urlString = status!.forword_urls![indexPath.item].thumbnail_pic
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// ไบไปถๅค็ไบค็ปๆงๅถๅจ๏ผ่ฟ้ๅชๆฏ่ด่ดฃๆไบไปถไผ ้ๅๅป ----- ็จ้ญๅ
if self.photoDidSelected != nil {
self.photoDidSelected!(status: self.status!, photoIndex: indexPath.item)
}
}
}
public class HBPictureCell: UICollectionViewCell {
@IBOutlet weak var pictureImage: UIImageView!
var urlString: String? {
didSet {
let path = NetworkManager.sharedManager.fullImageCachePath(urlString!)
pictureImage.image = UIImage(contentsOfFile: path)
}
}
}
|
35b892a7e136d7947c1f085b41938f30
| 29.938889 | 130 | 0.572455 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Models/Notifications/NotificationBlockGroup.swift
|
gpl-2.0
|
1
|
import Foundation
// MARK: - NotificationBlockGroup: Adapter to match 1 View <> 1 BlockGroup
//
class NotificationBlockGroup {
/// Grouped Blocks
///
let blocks: [NotificationBlock]
/// Kind of the current Group
///
let kind: Kind
/// Designated Initializer
///
init(blocks: [NotificationBlock], kind: Kind) {
self.blocks = blocks
self.kind = kind
}
}
// MARK: - Helpers Methods
//
extension NotificationBlockGroup {
/// Returns the First Block of a specified kind
///
func blockOfKind(_ kind: NotificationBlock.Kind) -> NotificationBlock? {
return type(of: self).blockOfKind(kind, from: blocks)
}
/// Extracts all of the imageUrl's for the blocks of the specified kinds
///
func imageUrlsFromBlocksInKindSet(_ kindSet: Set<NotificationBlock.Kind>) -> Set<URL> {
let filtered = blocks.filter { kindSet.contains($0.kind) }
let imageUrls = filtered.flatMap { $0.imageUrls }
return Set(imageUrls) as Set<URL>
}
}
// MARK: - Parsers
//
extension NotificationBlockGroup {
/// Subject: Contains a User + Text Block
///
class func groupFromSubject(_ subject: [[String: AnyObject]], parent: Notification) -> NotificationBlockGroup {
let blocks = NotificationBlock.blocksFromArray(subject, parent: parent)
return NotificationBlockGroup(blocks: blocks, kind: .subject)
}
/// Header: Contains a User + Text Block
///
class func groupFromHeader(_ header: [[String: AnyObject]], parent: Notification) -> NotificationBlockGroup {
let blocks = NotificationBlock.blocksFromArray(header, parent: parent)
return NotificationBlockGroup(blocks: blocks, kind: .header)
}
/// Body: May contain different kinds of Groups!
///
class func groupsFromBody(_ body: [[String: AnyObject]], parent: Notification) -> [NotificationBlockGroup] {
let blocks = NotificationBlock.blocksFromArray(body, parent: parent)
switch parent.kind {
case .comment:
return groupsForCommentBodyBlocks(blocks, parent: parent)
default:
return groupsForNonCommentBodyBlocks(blocks, parent: parent)
}
}
}
// MARK: - Private Parsing Helpers
//
private extension NotificationBlockGroup {
/// Non-Comment Body Groups: 1-1 Mapping between Blocks <> BlockGroups
///
/// - Notifications of the kind [Follow, Like, CommentLike] may contain a Footer block.
/// - We can assume that whenever the last block is of the type .Text, we're dealing with a footer.
/// - Whenever we detect such a block, we'll map the NotificationBlock into a .Footer group.
/// - Footers are visually represented as `View All Followers` / `View All Likers`
///
class func groupsForNonCommentBodyBlocks(_ blocks: [NotificationBlock], parent: Notification) -> [NotificationBlockGroup] {
let parentKindsWithFooters: [NotificationKind] = [.follow, .like, .commentLike]
let parentMayContainFooter = parentKindsWithFooters.contains(parent.kind)
return blocks.map { block in
let isFooter = parentMayContainFooter && block.kind == .text && blocks.last == block
let kind = isFooter ? .footer : Kind.fromBlockKind(block.kind)
return NotificationBlockGroup(blocks: [block], kind: kind)
}
}
/// Comment Body Blocks:
/// - Required to always render the Actions at the very bottom.
/// - Adapter: a single NotificationBlockGroup can be easily mapped against a single UI entity.
///
class func groupsForCommentBodyBlocks(_ blocks: [NotificationBlock], parent: Notification) -> [NotificationBlockGroup] {
guard let comment = blockOfKind(.comment, from: blocks), let user = blockOfKind(.user, from: blocks) else {
return []
}
var groups = [NotificationBlockGroup]()
let commentGroupBlocks = [comment, user]
let middleGroupBlocks = blocks.filter { return commentGroupBlocks.contains($0) == false }
let actionGroupBlocks = [comment]
// Comment Group: Comment + User Blocks
groups.append(NotificationBlockGroup(blocks: commentGroupBlocks, kind: .comment))
// Middle Group(s): Anything
for block in middleGroupBlocks {
// Duck Typing Again:
// If the block contains a range that matches with the metaReplyID field, we'll need to render this
// with a custom style. Translates into the `You replied to this comment` footer.
//
var kind = Kind.fromBlockKind(block.kind)
if let parentReplyID = parent.metaReplyID, block.notificationRangeWithCommentId(parentReplyID) != nil {
kind = .footer
}
groups.append(NotificationBlockGroup(blocks: [block], kind: kind))
}
// Whenever Possible *REMOVE* this workaround. Pingback Notifications require a locally generated block.
//
if parent.isPingback, let homeURL = user.metaLinksHome {
let blockGroup = pingbackReadMoreGroup(for: homeURL)
groups.append(blockGroup)
}
// Actions Group: A copy of the Comment Block (Actions)
groups.append(NotificationBlockGroup(blocks: actionGroupBlocks, kind: .actions))
return groups
}
/// Returns the First Block of a specified kind.
///
class func blockOfKind(_ kind: NotificationBlock.Kind, from blocks: [NotificationBlock]) -> NotificationBlock? {
for block in blocks where block.kind == kind {
return block
}
return nil
}
}
// MARK: - Private Parsing Helpers
//
private extension NotificationBlockGroup {
/// Returns a BlockGroup containing a single Text Block, which links to the specified URL.
///
class func pingbackReadMoreGroup(for url: URL) -> NotificationBlockGroup {
let text = NSLocalizedString("Read the source post", comment: "Displayed at the footer of a Pingback Notification.")
let textRange = NSRange(location: 0, length: text.count)
let zeroRange = NSRange(location: 0, length: 0)
let ranges = [
NotificationRange(kind: .Noticon, range: zeroRange, value: "\u{f442}"),
NotificationRange(kind: .Link, range: textRange, url: url)
]
let block = NotificationBlock(text: text, ranges: ranges)
return NotificationBlockGroup(blocks: [block], kind: .footer)
}
}
// MARK: - NotificationBlockGroup Types
//
extension NotificationBlockGroup {
/// Known Kinds of Block Groups
///
enum Kind {
case text
case image
case user
case comment
case actions
case subject
case header
case footer
static func fromBlockKind(_ blockKind: NotificationBlock.Kind) -> Kind {
switch blockKind {
case .text: return .text
case .image: return .image
case .user: return .user
case .comment: return .comment
}
}
}
}
|
2c54722289e562648927e92929f72b5b
| 35.186869 | 127 | 0.642847 | false | false | false | false |
drewag/Swiftlier
|
refs/heads/master
|
Tests/SwiftlierTests/JSONTests.swift
|
mit
|
1
|
//
// JSONTests.swift
// SwiftlierTests
//
// Created by Andrew J Wagner on 10/2/17.
// Copyright ยฉ 2017 Drewag. All rights reserved.
//
import XCTest
import Swiftlier
final class JSONTests: XCTestCase {
func testInitFromData() throws {
let jsonString = """
{
"array": ["value1","value2","value3"],
"dict": {"key":"value"},
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": null
}
"""
let data = jsonString.data(using: .utf8)!
let json = try JSON(data: data)
XCTAssertEqual(json["array"]?.array?.count, 3)
XCTAssertEqual(json["array"]?[0]?.string, "value1")
XCTAssertEqual(json["array"]?[1]?.string, "value2")
XCTAssertEqual(json["array"]?[2]?.string, "value3")
XCTAssertEqual(json["dict"]?.dictionary?.count, 1)
XCTAssertEqual(json["dict"]?["key"]?.string, "value")
XCTAssertEqual(json["integer"]?.int, 20)
XCTAssertEqual(json["decimal"]?.double, 0.3)
XCTAssertEqual(json["boolean"]?.bool, true)
XCTAssertTrue(json["null"]?.object is NSNull)
}
func testInitFromObject() throws {
let json = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
XCTAssertEqual(json["array"]?.array?.count, 3)
XCTAssertEqual(json["array"]?[0]?.string, "value1")
XCTAssertEqual(json["array"]?[1]?.string, "value2")
XCTAssertEqual(json["array"]?[2]?.string, "value3")
XCTAssertEqual(json["dict"]?.dictionary?.count, 1)
XCTAssertEqual(json["dict"]?["key"]?.string, "value")
XCTAssertEqual(json["integer"]?.int, 20)
XCTAssertEqual(json["decimal"]?.double, 0.3)
XCTAssertEqual(json["boolean"]?.bool, true)
XCTAssertTrue(json["null"]?.object is NSNull)
}
func testData() throws {
let original = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let data = try original.data()
let json = try JSON(data: data)
XCTAssertEqual(json["array"]?.array?.count, 3)
XCTAssertEqual(json["array"]?[0]?.string, "value1")
XCTAssertEqual(json["array"]?[1]?.string, "value2")
XCTAssertEqual(json["array"]?[2]?.string, "value3")
XCTAssertEqual(json["dict"]?.dictionary?.count, 1)
XCTAssertEqual(json["dict"]?["key"]?.string, "value")
XCTAssertEqual(json["integer"]?.int, 20)
XCTAssertEqual(json["decimal"]?.double, 0.3)
XCTAssertEqual(json["boolean"]?.bool, true)
XCTAssertTrue(json["null"]?.object is NSNull)
}
func testDecode() throws {
let jsonString = """
{
"string": "some",
"int": 4
}
"""
let data = jsonString.data(using: .utf8)!
let json = try JSON(data: data)
let codable: TestCodable = try json.decode()
XCTAssertEqual(codable.string, "some")
XCTAssertEqual(codable.int, 4)
}
func testEncode() throws {
let codable = TestCodable(string: "some", int: 4)
let json = try JSON(encodable: codable)
XCTAssertEqual(json["string"]?.string, "some")
XCTAssertEqual(json["int"]?.int, 4)
}
func testEquatable() throws {
let one = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let two = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentArray = JSON(object: [
"array": ["value1","different","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentDictValue = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"different"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentDictKey = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["different":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentString = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "different",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentInteger = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 21,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentDecimal = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.31,
"boolean": true,
"null": NSNull(),
])
let differentBool = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": false,
"null": NSNull(),
])
XCTAssertEqual(one, two)
XCTAssertNotEqual(one, differentArray)
XCTAssertNotEqual(one, differentDictValue)
XCTAssertNotEqual(one, differentDictKey)
XCTAssertNotEqual(one, differentString)
XCTAssertNotEqual(one, differentInteger)
XCTAssertNotEqual(one, differentDecimal)
XCTAssertNotEqual(one, differentBool)
}
}
|
d56a0b016311c10ea156e9307b7b16c8
| 32.884422 | 61 | 0.489545 | false | true | false | false |
jum/Charts
|
refs/heads/master
|
Pods/Charts/Source/Charts/Renderers/PieChartRenderer.swift
|
apache-2.0
|
2
|
//
// PieChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class PieChartRenderer: DataRenderer
{
@objc open weak var chart: PieChartView?
@objc public init(chart: PieChartView, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
open override func drawData(context: CGContext)
{
guard let chart = chart else { return }
let pieData = chart.data
if pieData != nil
{
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
accessibleChartElements.removeAll()
for set in pieData!.dataSets as! [IPieChartDataSet]
where set.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set)
}
}
}
@objc open func calculateMinimumRadiusForSpacedSlice(
center: CGPoint,
radius: CGFloat,
angle: CGFloat,
arcStartPointX: CGFloat,
arcStartPointY: CGFloat,
startAngle: CGFloat,
sweepAngle: CGFloat) -> CGFloat
{
let angleMiddle = startAngle + sweepAngle / 2.0
// Other point of the arc
let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle).DEG2RAD)
let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle).DEG2RAD)
// Middle point on the arc
let arcMidPointX = center.x + radius * cos(angleMiddle.DEG2RAD)
let arcMidPointY = center.y + radius * sin(angleMiddle.DEG2RAD)
// This is the base of the contained triangle
let basePointsDistance = sqrt(
pow(arcEndPointX - arcStartPointX, 2) +
pow(arcEndPointY - arcStartPointY, 2))
// After reducing space from both sides of the "slice",
// the angle of the contained triangle should stay the same.
// So let's find out the height of that triangle.
let containedTriangleHeight = (basePointsDistance / 2.0 *
tan((180.0 - angle).DEG2RAD / 2.0))
// Now we subtract that from the radius
var spacedRadius = radius - containedTriangleHeight
// And now subtract the height of the arc that's between the triangle and the outer circle
spacedRadius -= sqrt(
pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) +
pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2))
return spacedRadius
}
/// Calculates the sliceSpace to use based on visible values and their size compared to the set sliceSpace.
@objc open func getSliceSpace(dataSet: IPieChartDataSet) -> CGFloat
{
guard
dataSet.automaticallyDisableSliceSpacing,
let data = chart?.data as? PieChartData
else { return dataSet.sliceSpace }
let spaceSizeRatio = dataSet.sliceSpace / min(viewPortHandler.contentWidth, viewPortHandler.contentHeight)
let minValueRatio = dataSet.yMin / data.yValueSum * 2.0
let sliceSpace = spaceSizeRatio > CGFloat(minValueRatio)
? 0.0
: dataSet.sliceSpace
return sliceSpace
}
@objc open func drawDataSet(context: CGContext, dataSet: IPieChartDataSet)
{
guard let chart = chart else {return }
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
var drawAngles = chart.drawAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
if ((abs(e.y) > Double.ulpOfOne))
{
visibleAngleCount += 1
}
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : getSliceSpace(dataSet: dataSet)
context.saveGState()
// Make the chart header the first element in the accessible elements array
// We can do this in drawDataSet, since we know PieChartView can have only 1 dataSet
// Also since there's only 1 dataset, we don't use the typical createAccessibleHeader() here.
// NOTE: - Since we want to summarize the total count of slices/portions/elements, use a default string here
// This is unlike when we are naming individual slices, wherein it's alright to not use a prefix as descriptor.
// i.e. We want to VO to say "3 Elements" even if the developer didn't specify an accessibility prefix
// If prefix is unspecified it is safe to assume they did not want to use "Element 1", so that uses a default empty string
let prefix: String = chart.data?.accessibilityEntryLabelPrefix ?? "Element"
let description = chart.chartDescription?.text ?? dataSet.label ?? chart.centerText ?? "Pie Chart"
let
element = NSUIAccessibilityElement(accessibilityContainer: chart)
element.accessibilityLabel = description + ". \(entryCount) \(prefix + (entryCount == 1 ? "" : "s"))"
element.accessibilityFrame = chart.bounds
element.isHeader = true
accessibleChartElements.append(element)
for j in 0 ..< entryCount
{
let sliceAngle = drawAngles[j]
var innerRadius = userInnerRadius
guard let e = dataSet.entryForIndex(j) else { continue }
// draw only if the value is greater than zero
if (abs(e.y) > Double.ulpOfOne)
{
if !chart.needsHighlight(index: j)
{
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
context.setFillColor(dataSet.color(atIndex: j).cgColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / radius.DEG2RAD
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * CGFloat(phaseY)
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * CGFloat(phaseY)
if sweepAngleOuter < 0.0
{
sweepAngleOuter = 0.0
}
let arcStartPointX = center.x + radius * cos(startAngleOuter.DEG2RAD)
let arcStartPointY = center.y + radius * sin(startAngleOuter.DEG2RAD)
let path = CGMutablePath()
path.move(to: CGPoint(x: arcStartPointX,
y: arcStartPointY))
path.addRelativeArc(center: center, radius: radius, startAngle: startAngleOuter.DEG2RAD, delta: sweepAngleOuter.DEG2RAD)
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * CGFloat(phaseY),
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / innerRadius.DEG2RAD
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * CGFloat(phaseY)
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * CGFloat(phaseY)
if sweepAngleInner < 0.0
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
path.addLine(
to: CGPoint(
x: center.x + innerRadius * cos(endAngleInner.DEG2RAD),
y: center.y + innerRadius * sin(endAngleInner.DEG2RAD)))
path.addRelativeArc(center: center, radius: innerRadius, startAngle: endAngleInner.DEG2RAD, delta: -sweepAngleInner.DEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let sliceSpaceOffset =
calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * CGFloat(phaseY),
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle.DEG2RAD)
let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle.DEG2RAD)
path.addLine(
to: CGPoint(
x: arcEndPointX,
y: arcEndPointY))
}
else
{
path.addLine(to: center)
}
}
path.closeSubpath()
context.beginPath()
context.addPath(path)
context.fillPath(using: .evenOdd)
let axElement = createAccessibleElement(withIndex: j,
container: chart,
dataSet: dataSet)
{ (element) in
element.accessibilityFrame = path.boundingBoxOfPath
}
accessibleChartElements.append(axElement)
}
}
angle += sliceAngle * CGFloat(phaseX)
}
// Post this notification to let VoiceOver account for the redrawn frames
accessibilityPostLayoutChangedNotification()
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard
let chart = chart,
let data = chart.data
else { return }
let center = chart.centerCircleBox
// get whole the radius
let radius = chart.radius
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var labelRadiusOffset = radius / 10.0 * 3.0
if chart.drawHoleEnabled
{
labelRadiusOffset = (radius - (radius * chart.holeRadiusPercent)) / 2.0
}
let labelRadius = radius - labelRadiusOffset
var dataSets = data.dataSets
let yValueSum = (data as! PieChartData).yValueSum
let drawEntryLabels = chart.isDrawEntryLabelsEnabled
let usePercentValuesEnabled = chart.usePercentValuesEnabled
let entryLabelColor = chart.entryLabelColor
let entryLabelFont = chart.entryLabelFont
var angle: CGFloat = 0.0
var xIndex = 0
context.saveGState()
defer { context.restoreGState() }
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue }
let drawValues = dataSet.isDrawValuesEnabled
if !drawValues && !drawEntryLabels && !dataSet.isDrawIconsEnabled
{
continue
}
let iconsOffset = dataSet.iconsOffset
let xValuePosition = dataSet.xValuePosition
let yValuePosition = dataSet.yValuePosition
let valueFont = dataSet.valueFont
let entryLabelFont = dataSet.entryLabelFont
let lineHeight = valueFont.lineHeight
guard let formatter = dataSet.valueFormatter else { continue }
for j in 0 ..< dataSet.entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
let pe = e as? PieChartDataEntry
if xIndex == 0
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * CGFloat(phaseX)
}
let sliceAngle = drawAngles[xIndex]
let sliceSpace = getSliceSpace(dataSet: dataSet)
let sliceSpaceMiddleAngle = sliceSpace / labelRadius.DEG2RAD
// offset needed to center the drawn text in the slice
let angleOffset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0
angle = angle + angleOffset
let transformedAngle = rotationAngle + angle * CGFloat(phaseY)
let value = usePercentValuesEnabled ? e.y / yValueSum * 100.0 : e.y
let valueText = formatter.stringForValue(
value,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler)
let sliceXBase = cos(transformedAngle.DEG2RAD)
let sliceYBase = sin(transformedAngle.DEG2RAD)
let drawXOutside = drawEntryLabels && xValuePosition == .outsideSlice
let drawYOutside = drawValues && yValuePosition == .outsideSlice
let drawXInside = drawEntryLabels && xValuePosition == .insideSlice
let drawYInside = drawValues && yValuePosition == .insideSlice
let valueTextColor = dataSet.valueTextColorAt(j)
let entryLabelColor = dataSet.entryLabelColor
if drawXOutside || drawYOutside
{
let valueLineLength1 = dataSet.valueLinePart1Length
let valueLineLength2 = dataSet.valueLinePart2Length
let valueLinePart1OffsetPercentage = dataSet.valueLinePart1OffsetPercentage
var pt2: CGPoint
var labelPoint: CGPoint
var align: NSTextAlignment
var line1Radius: CGFloat
if chart.drawHoleEnabled
{
line1Radius = (radius - (radius * chart.holeRadiusPercent)) * valueLinePart1OffsetPercentage + (radius * chart.holeRadiusPercent)
}
else
{
line1Radius = radius * valueLinePart1OffsetPercentage
}
let polyline2Length = dataSet.valueLineVariableLength
? labelRadius * valueLineLength2 * abs(sin(transformedAngle.DEG2RAD))
: labelRadius * valueLineLength2
let pt0 = CGPoint(
x: line1Radius * sliceXBase + center.x,
y: line1Radius * sliceYBase + center.y)
let pt1 = CGPoint(
x: labelRadius * (1 + valueLineLength1) * sliceXBase + center.x,
y: labelRadius * (1 + valueLineLength1) * sliceYBase + center.y)
if transformedAngle.truncatingRemainder(dividingBy: 360.0) >= 90.0 && transformedAngle.truncatingRemainder(dividingBy: 360.0) <= 270.0
{
pt2 = CGPoint(x: pt1.x - polyline2Length, y: pt1.y)
align = .right
labelPoint = CGPoint(x: pt2.x - 5, y: pt2.y - lineHeight)
}
else
{
pt2 = CGPoint(x: pt1.x + polyline2Length, y: pt1.y)
align = .left
labelPoint = CGPoint(x: pt2.x + 5, y: pt2.y - lineHeight)
}
DrawLine: do
{
if dataSet.useValueColorForLine
{
context.setStrokeColor(dataSet.color(atIndex: j).cgColor)
}
else if let valueLineColor = dataSet.valueLineColor
{
context.setStrokeColor(valueLineColor.cgColor)
}
else
{
return
}
context.setLineWidth(dataSet.valueLineWidth)
context.move(to: CGPoint(x: pt0.x, y: pt0.y))
context.addLine(to: CGPoint(x: pt1.x, y: pt1.y))
context.addLine(to: CGPoint(x: pt2.x, y: pt2.y))
context.drawPath(using: CGPathDrawingMode.stroke)
}
if drawXOutside && drawYOutside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: labelPoint,
align: align,
attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor]
)
if j < data.entryCount && pe?.label != nil
{
ChartUtils.drawText(
context: context,
text: pe!.label!,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight),
align: align,
attributes: [
NSAttributedString.Key.font: entryLabelFont ?? valueFont,
NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor]
)
}
}
else if drawXOutside
{
if j < data.entryCount && pe?.label != nil
{
ChartUtils.drawText(
context: context,
text: pe!.label!,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0),
align: align,
attributes: [
NSAttributedString.Key.font: entryLabelFont ?? valueFont,
NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor]
)
}
}
else if drawYOutside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0),
align: align,
attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor]
)
}
}
if drawXInside || drawYInside
{
// calculate the text position
let x = labelRadius * sliceXBase + center.x
let y = labelRadius * sliceYBase + center.y - lineHeight
if drawXInside && drawYInside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: x, y: y),
align: .center,
attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor]
)
if j < data.entryCount && pe?.label != nil
{
ChartUtils.drawText(
context: context,
text: pe!.label!,
point: CGPoint(x: x, y: y + lineHeight),
align: .center,
attributes: [
NSAttributedString.Key.font: entryLabelFont ?? valueFont,
NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor]
)
}
}
else if drawXInside
{
if j < data.entryCount && pe?.label != nil
{
ChartUtils.drawText(
context: context,
text: pe!.label!,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .center,
attributes: [
NSAttributedString.Key.font: entryLabelFont ?? valueFont,
NSAttributedString.Key.foregroundColor: entryLabelColor ?? valueTextColor]
)
}
}
else if drawYInside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .center,
attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: valueTextColor]
)
}
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
// calculate the icon's position
let x = (labelRadius + iconsOffset.y) * sliceXBase + center.x
var y = (labelRadius + iconsOffset.y) * sliceYBase + center.y
y += iconsOffset.x
ChartUtils.drawImage(context: context,
image: icon,
x: x,
y: y,
size: icon.size)
}
xIndex += 1
}
}
}
open override func drawExtras(context: CGContext)
{
drawHole(context: context)
drawCenterText(context: context)
}
/// draws the hole in the center of the chart and the transparent circle / hole
private func drawHole(context: CGContext)
{
guard let chart = chart else { return }
if chart.drawHoleEnabled
{
context.saveGState()
let radius = chart.radius
let holeRadius = radius * chart.holeRadiusPercent
let center = chart.centerCircleBox
if let holeColor = chart.holeColor
{
if holeColor != NSUIColor.clear
{
// draw the hole-circle
context.setFillColor(chart.holeColor!.cgColor)
context.fillEllipse(in: CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0))
}
}
// only draw the circle if it can be seen (not covered by the hole)
if let transparentCircleColor = chart.transparentCircleColor
{
if transparentCircleColor != NSUIColor.clear &&
chart.transparentCircleRadiusPercent > chart.holeRadiusPercent
{
let alpha = animator.phaseX * animator.phaseY
let secondHoleRadius = radius * chart.transparentCircleRadiusPercent
// make transparent
context.setAlpha(CGFloat(alpha))
context.setFillColor(transparentCircleColor.cgColor)
// draw the transparent-circle
context.beginPath()
context.addEllipse(in: CGRect(
x: center.x - secondHoleRadius,
y: center.y - secondHoleRadius,
width: secondHoleRadius * 2.0,
height: secondHoleRadius * 2.0))
context.addEllipse(in: CGRect(
x: center.x - holeRadius,
y: center.y - holeRadius,
width: holeRadius * 2.0,
height: holeRadius * 2.0))
context.fillPath(using: .evenOdd)
}
}
context.restoreGState()
}
}
/// draws the description text in the center of the pie chart makes most sense when center-hole is enabled
private func drawCenterText(context: CGContext)
{
guard
let chart = chart,
let centerAttributedText = chart.centerAttributedText
else { return }
if chart.drawCenterTextEnabled && centerAttributedText.length > 0
{
let center = chart.centerCircleBox
let offset = chart.centerTextOffset
let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius
let x = center.x + offset.x
let y = center.y + offset.y
let holeRect = CGRect(
x: x - innerRadius,
y: y - innerRadius,
width: innerRadius * 2.0,
height: innerRadius * 2.0)
var boundingRect = holeRect
if chart.centerTextRadiusPercent > 0.0
{
boundingRect = boundingRect.insetBy(dx: (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, dy: (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0)
}
let textBounds = centerAttributedText.boundingRect(with: boundingRect.size, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil)
var drawingRect = boundingRect
drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0
drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0
drawingRect.size = textBounds.size
context.saveGState()
let clippingPath = CGPath(ellipseIn: holeRect, transform: nil)
context.beginPath()
context.addPath(clippingPath)
context.clip()
centerAttributedText.draw(with: drawingRect, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil)
context.restoreGState()
}
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let chart = chart,
let data = chart.data
else { return }
context.saveGState()
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
// Append highlighted accessibility slices into this array, so we can prioritize them over unselected slices
var highlightedAccessibleElements: [NSUIAccessibilityElement] = []
for i in 0 ..< indices.count
{
// get the index to highlight
let index = Int(indices[i].x)
if index >= drawAngles.count
{
continue
}
guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue }
if !set.isHighlightEnabled
{
continue
}
let entryCount = set.entryCount
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = set.entryForIndex(j) else { continue }
if ((abs(e.y) > Double.ulpOfOne))
{
visibleAngleCount += 1
}
}
if index == 0
{
angle = 0.0
}
else
{
angle = absoluteAngles[index - 1] * CGFloat(phaseX)
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace
let sliceAngle = drawAngles[index]
var innerRadius = userInnerRadius
let shift = set.selectionShift
let highlightedRadius = radius + shift
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
context.setFillColor(set.highlightColor?.cgColor ?? set.color(atIndex: index).cgColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / radius.DEG2RAD
let sliceSpaceAngleShifted = visibleAngleCount == 1 ?
0.0 :
sliceSpace / highlightedRadius.DEG2RAD
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * CGFloat(phaseY)
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * CGFloat(phaseY)
if sweepAngleOuter < 0.0
{
sweepAngleOuter = 0.0
}
let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * CGFloat(phaseY)
var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * CGFloat(phaseY)
if sweepAngleShifted < 0.0
{
sweepAngleShifted = 0.0
}
let path = CGMutablePath()
path.move(to: CGPoint(x: center.x + highlightedRadius * cos(startAngleShifted.DEG2RAD),
y: center.y + highlightedRadius * sin(startAngleShifted.DEG2RAD)))
path.addRelativeArc(center: center, radius: highlightedRadius, startAngle: startAngleShifted.DEG2RAD,
delta: sweepAngleShifted.DEG2RAD)
var sliceSpaceRadius: CGFloat = 0.0
if accountForSliceSpacing
{
sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * CGFloat(phaseY),
arcStartPointX: center.x + radius * cos(startAngleOuter.DEG2RAD),
arcStartPointY: center.y + radius * sin(startAngleOuter.DEG2RAD),
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
}
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = sliceSpaceRadius
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / innerRadius.DEG2RAD
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * CGFloat(phaseY)
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * CGFloat(phaseY)
if sweepAngleInner < 0.0
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
path.addLine(
to: CGPoint(
x: center.x + innerRadius * cos(endAngleInner.DEG2RAD),
y: center.y + innerRadius * sin(endAngleInner.DEG2RAD)))
path.addRelativeArc(center: center, radius: innerRadius,
startAngle: endAngleInner.DEG2RAD,
delta: -sweepAngleInner.DEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle.DEG2RAD)
let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle.DEG2RAD)
path.addLine(
to: CGPoint(
x: arcEndPointX,
y: arcEndPointY))
}
else
{
path.addLine(to: center)
}
}
path.closeSubpath()
context.beginPath()
context.addPath(path)
context.fillPath(using: .evenOdd)
let axElement = createAccessibleElement(withIndex: index,
container: chart,
dataSet: set)
{ (element) in
element.accessibilityFrame = path.boundingBoxOfPath
element.isSelected = true
}
highlightedAccessibleElements.append(axElement)
}
// Prepend selected slices before the already rendered unselected ones.
// NOTE: - This relies on drawDataSet() being called before drawHighlighted in PieChartView.
accessibleChartElements.insert(contentsOf: highlightedAccessibleElements, at: 1)
context.restoreGState()
}
/// Creates an NSUIAccessibilityElement representing a slice of the PieChart.
/// The element only has it's container and label set based on the chart and dataSet. Use the modifier to alter traits and frame.
private func createAccessibleElement(withIndex idx: Int,
container: PieChartView,
dataSet: IPieChartDataSet,
modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement {
let element = NSUIAccessibilityElement(accessibilityContainer: container)
guard let e = dataSet.entryForIndex(idx) else { return element }
guard let formatter = dataSet.valueFormatter else { return element }
guard let data = container.data as? PieChartData else { return element }
var elementValueText = formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: idx,
viewPortHandler: viewPortHandler)
if container.usePercentValuesEnabled {
let value = e.y / data.yValueSum * 100.0
let valueText = formatter.stringForValue(
value,
entry: e,
dataSetIndex: idx,
viewPortHandler: viewPortHandler)
elementValueText = valueText
}
let pieChartDataEntry = (dataSet.entryForIndex(idx) as? PieChartDataEntry)
let isCount = data.accessibilityEntryLabelSuffixIsCount
let prefix = data.accessibilityEntryLabelPrefix?.appending("\(idx + 1)") ?? pieChartDataEntry?.label ?? ""
let suffix = data.accessibilityEntryLabelSuffix ?? ""
element.accessibilityLabel = "\(prefix) : \(elementValueText) \(suffix + (isCount ? (e.y == 1.0 ? "" : "s") : "") )"
// The modifier allows changing of traits and frame depending on highlight, rotation, etc
modifier(element)
return element
}
}
|
4505ff0235594d8d98cba1ac689d15d4
| 39.948332 | 223 | 0.512973 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges
|
refs/heads/main
|
WhiteBoardCodingChallenges/Challenges/CrackingTheCodingInterview/StackOfPlates/StackOfPlates.swift
|
mit
|
1
|
//
// StackOfPlates.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 01/06/2016.
// Copyright ยฉ 2016 Boles. All rights reserved.
//
import UIKit
//CtCI 3.3
class StackOfPlates: NSObject {
// MARK: Properties
private let stackCapacity = 2
lazy var stacks: [StackOfPlatesStack] = {
return [StackOfPlatesStack]()
}()
// MARK: Actions
func push(value: Int) {
var pushStack: StackOfPlatesStack
if let stack = stacks.last {
if stack.isFull() {
pushStack = StackOfPlatesStack.init(capacity: stackCapacity)
stacks.append(pushStack)
}
else {
pushStack = stack
}
}
else {
pushStack = StackOfPlatesStack.init(capacity: stackCapacity)
stacks.append(pushStack)
}
pushStack.push(value: value)
}
func pop() -> StackOfPlatesNode? {
if let stack = stacks.last {
let node = stack.pop()!
if stack.isEmpty() {
stacks.removeLast()
}
return node
}
return nil
}
}
|
e9c9d71128f7fd9bce8976db3f073b1c
| 19.651515 | 76 | 0.465884 | false | false | false | false |
songzhw/2iOS
|
refs/heads/master
|
iOS_Swift/iOS_Swift/ui/UILayoutViewController.swift
|
apache-2.0
|
1
|
import UIKit
class UILayoutViewController: UIViewController {
let parent1 = UIView(frame: CGRect(x: 30, y: 120, width: 100, height: 100))
let child2 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20)) // ้กถ้จ
let child3 = UIView(frame: CGRect(x: 70, y: 70, width: 26, height: 26)) // ๅณไธ่ง
let viewB1 = UIView(frame: CGRect(x: 230, y: 250, width: 100, height: 100))
let viewB2 = UIView()
override func viewDidLoad() {
super.viewDidLoad()
autoResizing()
autoLayout()
}
func autoLayout() {
viewB1.backgroundColor = .black
viewB2.backgroundColor = .systemPink
viewB2.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(viewB1)
self.view.addSubview(viewB2)
NSLayoutConstraint.activate([
viewB2.bottomAnchor.constraint(equalTo: viewB1.topAnchor, constant: 20),
viewB2.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20),
viewB2.widthAnchor.constraint(equalToConstant: 30),
viewB2.heightAnchor.constraint(equalToConstant: 30)
])
}
func autoResizing() {
parent1.backgroundColor = UIColor(hex:"#ffe700ff")
child2.backgroundColor = UIColor(hex: "#6200eaff")
child3.backgroundColor = UIColor(hex: "#4caf50ff")
parent1.addSubview(child2)
parent1.addSubview(child3)
self.view.addSubview(parent1)
}
@IBAction func parentResize1(_ sender: UIButton) {
parent1.bounds.size.width += 40
parent1.bounds.size.height += 40
}
@IBAction func parentResize2(_ sender: UIButton) {
child2.autoresizingMask = .flexibleWidth //ๅณwidthๆฏ็ตๆดป็, ๅฏไปฅauto resize
child3.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin] //ๅณๅทฆไธmarginๆฏ็ตๆดป็; ๆขๅฅ่ฏๅฐฑๆฏๅณ/ไธmarginๆฏๅบๅฎ็
parent1.bounds.size.width += 40
parent1.bounds.size.height += 40
}
}
|
3230e7d6110b7f80f9ebf8396381d007
| 31.517857 | 107 | 0.697419 | false | false | false | false |
CodeMozart/MHzSinaWeibo-Swift-
|
refs/heads/master
|
SinaWeibo๏ผstroyboard๏ผ/SinaWeibo/Classes/Tools/NSDate+Extension.swift
|
mit
|
1
|
//
// NSDate+Extension.swift
// SinaWeibo
//
// Created by Minghe on 15/11/16.
// Copyright ยฉ 2015ๅนด Stanford swift. All rights reserved.
//
import UIKit
extension NSDate {
/// ๆ นๆฎๆๅฎๅญ็ฌฆไธฒ่ฝฌๆขNSDate
class func dataWithString(str: String) -> NSDate? {
// 1.ๅฐๅๅธๅพฎๅ็ๆถ้ด่ฝฌๆขไธบNSDate
// 1.1ๅๅปบๆถ้ดๆ ผๅผๅๅฏน่ฑก
let formatter = NSDateFormatter()
// 1.2ๅๅงๅๆถ้ดๆ ผๅผๅฏน่ฑก
formatter.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
formatter.locale = NSLocale(localeIdentifier: "en")
// 1.3ๅฐๅๅธๅพฎๅ็ๆถ้ดๅญ็ฌฆไธฒ่ฝฌๆขไธบNSDate
return formatter.dateFromString(str)
}
/// ่ฟๅๆ ผๅผๅไนๅ็ๆถ้ดๅญ็ฌฆไธฒ
var desc: String {
// 1.1ๅๅปบๆถ้ดๆ ผๅผๅๅฏน่ฑก
let formatter = NSDateFormatter()
// 1.2ๅๅงๅๆถ้ดๆ ผๅผๅฏน่ฑก
formatter.locale = NSLocale(localeIdentifier: "en")
// ๆฅๅ
let calendar = NSCalendar.currentCalendar()
// ไปๅคฉ
if calendar.isDateInToday(self) {
let timeInterval = Int(NSDate().timeIntervalSinceDate(self))
if timeInterval < 60
{
return "ๅๅ"
} else if timeInterval < 60 * 60 {
return "\(timeInterval / 60)ๅ้ไปฅๅ"
} else if timeInterval < 60 * 60 * 24 {
return "\(timeInterval / (60 * 60))ๅฐๆถๅ"
}
}
// ๆจๅคฉ
var formatterStr = "HH:mm"
let comps = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
if calendar.isDateInYesterday(self) {
formatterStr = "ๆจๅคฉ " + formatterStr
} else if comps.year < 1 {
// ไธๅนดไปฅๅ
formatterStr = "MM-dd " + formatterStr
} else {
// ๆดๆฉๆถ้ด
formatterStr = "yyyy-MM-dd " + formatterStr
}
formatter.dateFormat = formatterStr
return formatter.stringFromDate(self)
}
}
|
6da51ea63b6b059217c7ab1cac234c9f
| 27.514286 | 135 | 0.529058 | false | false | false | false |
artsy/eigen
|
refs/heads/main
|
ios/Artsy/View_Controllers/Auction/RefinementOptionsViewController.swift
|
mit
|
1
|
import UIKit
protocol RefinementOptionsViewControllerDelegate: AnyObject {
associatedtype R: RefinableType
func userDidCancel(_ controller: RefinementOptionsViewController<R>)
func userDidApply(_ settings: R, controller: RefinementOptionsViewController<R>)
}
// TODO: Move into a navigation
class RefinementOptionsViewController<R: RefinableType>: UIViewController {
var tableView: UITableView?
var minLabel: UILabel?
var maxLabel: UILabel?
var slider: MARKRangeSlider?
var applyButton: UIButton?
var resetButton: UIButton?
var userDidCancelClosure: ((RefinementOptionsViewController) -> Void)?
var userDidApplyClosure: ((R) -> Void)?
// this is semantically "private" to guarantee it doesn't outlive this instance of RefinementOptionsViewController
var tableViewHandler: RefinementOptionsViewControllerTableViewHandler?
var sortTableView: UITableView?
var viewDidAppearAnalyticsOption: RefinementAnalyticsOption?
var applyButtonPressedAnalyticsOption: RefinementAnalyticsOption?
let currencySymbol: String
// defaultSettings also implies min/max price ranges
var defaultSettings: R
var initialSettings: R
var currentSettings: R {
didSet {
updateButtonEnabledStates()
updatePriceLabels()
}
}
var statusBarHidden = false
init(defaultSettings: R, initialSettings: R, currencySymbol: String, userDidCancelClosure: ((RefinementOptionsViewController) -> Void)?, userDidApplyClosure: ((R) -> Void)?) {
self.defaultSettings = defaultSettings
self.initialSettings = initialSettings
self.currentSettings = initialSettings
self.currencySymbol = currencySymbol
self.userDidCancelClosure = userDidCancelClosure
self.userDidApplyClosure = userDidApplyClosure
super.init(nibName: nil, bundle: nil)
}
@objc func sliderValueDidChange(_ slider: MARKRangeSlider) {
let range = (min: Int(slider.leftValue), max: Int(slider.rightValue))
currentSettings = currentSettings.refineSettingsWithPriceRange(range)
}
@objc func userDidPressApply() {
applyButtonPressedAnalyticsOption?.sendAsEvent()
userDidApplyClosure?(currentSettings)
}
@objc func userDidCancel() {
userDidCancelClosure?(self)
}
@objc func userDidPressReset() {
// Reset all UI back to its default settings, including a hard reload on the table view.
currentSettings = defaultSettings
sortTableView?.reloadData()
if let range = self.defaultSettings.priceRange {
slider?.setLeftValue(CGFloat(range.min), rightValue: CGFloat(range.max))
}
updatePriceLabels()
updateButtonEnabledStates()
}
// Required by Swift compiler, sadly.
required init?(coder aDecoder: NSCoder) {
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Removes our rounded corners
presentationController?.presentedView?.layer.cornerRadius = 0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewDidAppearAnalyticsOption?.sendAsPageView()
}
override var prefersStatusBarHidden: Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return traitDependentSupportedInterfaceOrientations
}
override var shouldAutorotate : Bool {
return traitDependentAutorotateSupport
}
}
class RefinementAnalyticsOption: NSObject {
let name: String
let properties: [AnyHashable: Any]
init(name: String, properties: [AnyHashable: Any]) {
self.name = name
self.properties = properties
super.init()
}
func sendAsEvent() {
AREmission.sharedInstance().sendEvent(name, traits: properties)
}
func sendAsPageView() {
AREmission.sharedInstance().sendScreenEvent(name, traits: properties)
}
}
|
4b87d7521cd319461699063a1f7a5f03
| 29.282609 | 179 | 0.700646 | false | false | false | false |
mercadopago/sdk-ios
|
refs/heads/master
|
MercadoPagoSDKExamples/MercadoPagoSDKExamples/CardViewController.swift
|
mit
|
1
|
//
// CardViewController.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 28/1/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import UIKit
import MercadoPagoSDK
class CardViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, KeyboardDelegate {
var publicKey : String?
@IBOutlet weak var tableView : UITableView!
var cardNumberCell : MPCardNumberTableViewCell!
var expirationDateCell : MPExpirationDateTableViewCell!
var cardholderNameCell : MPCardholderNameTableViewCell!
var userIdCell : MPUserIdTableViewCell!
var securityCodeCell : SimpleSecurityCodeTableViewCell!
var paymentMethod : PaymentMethod!
var hasError : Bool = false
var loadingView : UILoadingView!
var identificationType : IdentificationType?
var identificationTypes : [IdentificationType]?
var callback : ((token : Token?) -> Void)?
var isKeyboardVisible : Bool?
var inputsCells : NSMutableArray!
init(merchantPublicKey: String, paymentMethod: PaymentMethod, callback: (token: Token?) -> Void) {
super.init(nibName: "CardViewController", bundle: nil)
self.publicKey = merchantPublicKey
self.paymentMethod = paymentMethod
self.callback = callback
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized)
self.view.addSubview(self.loadingView)
self.title = "Datos de tu tarjeta".localized
self.navigationItem.backBarButtonItem?.title = "Atrรกs"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Continuar".localized, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CardViewController.submitForm))
let mercadoPago = MercadoPago(publicKey: self.publicKey!)
mercadoPago.getIdentificationTypes({(identificationTypes: [IdentificationType]?) -> Void in
self.identificationTypes = identificationTypes
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}, failure: { (error: NSError?) -> Void in
self.prepareTableView()
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
self.userIdCell.hidden = true
}
)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CardViewController.willShowKeyboard(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CardViewController.willHideKeyboard(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func willHideKeyboard(notification: NSNotification) {
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, 0.0, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
func willShowKeyboard(notification: NSNotification) {
let s:NSValue? = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)
let keyboardBounds :CGRect = s!.CGRectValue()
// resize content insets.
let contentInsets = UIEdgeInsetsMake(64, 0.0, keyboardBounds.size.height, 0)
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
}
@IBAction func submitForm() {
self.view.addSubview(self.loadingView)
let cardToken = CardToken(cardNumber: self.cardNumberCell.getCardNumber(), expirationMonth: self.expirationDateCell.getExpirationMonth(), expirationYear: self.expirationDateCell.getExpirationYear(), securityCode: self.securityCodeCell.getSecurityCode(), cardholderName: self.cardholderNameCell.getCardholderName(), docType: self.userIdCell.getUserIdType(), docNumber: self.userIdCell.getUserIdValue())
if validateForm(cardToken) {
createToken(cardToken)
} else {
self.loadingView.removeFromSuperview()
self.hasError = true
self.tableView.reloadData()
}
}
func getIndexForObject(object: AnyObject) -> Int {
var i = 0
for arr in self.inputsCells {
if let input = object as? UITextField {
if let arrTextField = (arr as! NSArray)[0] as? UITextField {
if input == arrTextField {
return i
}
}
}
i = i + 1
}
return -1
}
func scrollToRow(indexPath: NSIndexPath) {
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
func focusAndScrollForIndex(index: Int) {
var i = 0
for arr in self.inputsCells {
if i == index {
if let textField = (arr as! NSArray)[0] as? UITextField {
if let cell = (arr as! NSArray)[1] as? ErrorTableViewCell {
if !textField.isFirstResponder() {
textField.becomeFirstResponder()
}
let indexPath = self.tableView.indexPathForCell(cell)
if indexPath != nil {
scrollToRow(indexPath!)
}
}
}
}
i = i + 1
}
}
func prev(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index >= 1 {
focusAndScrollForIndex(index-1)
}
}
}
func next(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index < self.inputsCells.count - 1 {
focusAndScrollForIndex(index+1)
}
}
}
func done(object: AnyObject?) {
if object != nil {
let index = getIndexForObject(object!)
if index < self.inputsCells.count {
var i = 0
for arr in self.inputsCells {
if i == index {
if let textField = (arr as! NSArray)[0] as? UITextField {
textField.resignFirstResponder()
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
scrollToRow(indexPath)
}
}
i = i + 1
}
}
}
}
func prepareTableView() {
self.inputsCells = NSMutableArray()
let cardNumberNib = UINib(nibName: "MPCardNumberTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardNumberNib, forCellReuseIdentifier: "cardNumberCell")
self.cardNumberCell = self.tableView.dequeueReusableCellWithIdentifier("cardNumberCell") as! MPCardNumberTableViewCell
self.cardNumberCell.height = 55.0
self.cardNumberCell.setIcon(self.paymentMethod._id)
self.cardNumberCell._setSetting(self.paymentMethod.settings[0])
self.cardNumberCell.cardNumberTextField.inputAccessoryView = MPToolbar(prevEnabled: false, nextEnabled: true, delegate: self, textFieldContainer: self.cardNumberCell.cardNumberTextField)
self.inputsCells.addObject([self.cardNumberCell.cardNumberTextField, self.cardNumberCell])
let expirationDateNib = UINib(nibName: "MPExpirationDateTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(expirationDateNib, forCellReuseIdentifier: "expirationDateCell")
self.expirationDateCell = self.tableView.dequeueReusableCellWithIdentifier("expirationDateCell") as! MPExpirationDateTableViewCell
self.expirationDateCell.height = 55.0
self.expirationDateCell.expirationDateTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.expirationDateCell.expirationDateTextField)
self.inputsCells.addObject([self.expirationDateCell.expirationDateTextField, self.expirationDateCell])
let cardholderNameNib = UINib(nibName: "MPCardholderNameTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(cardholderNameNib, forCellReuseIdentifier: "cardholderNameCell")
self.cardholderNameCell = self.tableView.dequeueReusableCellWithIdentifier("cardholderNameCell") as! MPCardholderNameTableViewCell
self.cardholderNameCell.height = 55.0
self.cardholderNameCell.cardholderNameTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.cardholderNameCell.cardholderNameTextField)
self.inputsCells.addObject([self.cardholderNameCell.cardholderNameTextField, self.cardholderNameCell])
let userIdNib = UINib(nibName: "MPUserIdTableViewCell", bundle: MercadoPago.getBundle())
self.tableView.registerNib(userIdNib, forCellReuseIdentifier: "userIdCell")
self.userIdCell = self.tableView.dequeueReusableCellWithIdentifier("userIdCell") as! MPUserIdTableViewCell
self.userIdCell._setIdentificationTypes(self.identificationTypes)
self.userIdCell.height = 55.0
self.userIdCell.userIdTypeTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdTypeTextField)
self.userIdCell.userIdValueTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: true, delegate: self, textFieldContainer: self.userIdCell.userIdValueTextField)
self.inputsCells.addObject([self.userIdCell.userIdTypeTextField, self.userIdCell])
self.inputsCells.addObject([self.userIdCell.userIdValueTextField, self.userIdCell])
let securityCodeNib = UINib(nibName: "SimpleSecurityCodeTableViewCell", bundle: nil)
self.tableView.registerNib(securityCodeNib, forCellReuseIdentifier: "securityCodeCell")
self.securityCodeCell = self.tableView.dequeueReusableCellWithIdentifier("securityCodeCell") as! SimpleSecurityCodeTableViewCell
self.securityCodeCell.height = 55.0
self.securityCodeCell.securityCodeTextField.inputAccessoryView = MPToolbar(prevEnabled: true, nextEnabled: false, delegate: self, textFieldContainer: self.securityCodeCell.securityCodeTextField)
self.inputsCells.addObject([self.securityCodeCell.securityCodeTextField, self.securityCodeCell])
self.tableView.delegate = self
self.tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 2 ? 1 : 2
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell
} else if indexPath.row == 1 {
return self.expirationDateCell
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell
} else if indexPath.row == 1 {
return self.userIdCell
}
} else if indexPath.section == 2 {
return self.securityCodeCell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if indexPath.row == 0 {
return self.cardNumberCell.getHeight()
} else if indexPath.row == 1 {
return self.expirationDateCell.getHeight()
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
return self.cardholderNameCell.getHeight()
} else if indexPath.row == 1 {
return self.userIdCell.getHeight()
}
} else if indexPath.section == 2 {
return self.securityCodeCell.getHeight()
}
return 55
}
override func viewDidLayoutSubviews() {
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
self.tableView.separatorInset = UIEdgeInsetsZero
}
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
if #available(iOS 8.0, *) {
self.tableView.layoutMargins = UIEdgeInsetsZero
} else {
}
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
if #available(iOS 8.0, *) {
cell.layoutMargins = UIEdgeInsetsZero
} else {
}
}
}
func validateForm(cardToken : CardToken) -> Bool {
var result : Bool = true
// Validate card number
let errorCardNumber = cardToken.validateCardNumber(paymentMethod!)
if errorCardNumber != nil {
self.cardNumberCell.setError(errorCardNumber!.userInfo["cardNumber"] as? String)
result = false
} else {
self.cardNumberCell.setError(nil)
}
// Validate expiry date
let errorExpiryDate = cardToken.validateExpiryDate()
if errorExpiryDate != nil {
self.expirationDateCell.setError(errorExpiryDate!.userInfo["expiryDate"] as? String)
result = false
} else {
self.expirationDateCell.setError(nil)
}
// Validate card holder name
let errorCardholder = cardToken.validateCardholderName()
if errorCardholder != nil {
self.cardholderNameCell.setError(errorCardholder!.userInfo["cardholder"] as? String)
result = false
} else {
self.cardholderNameCell.setError(nil)
}
// Validate identification number
let errorIdentificationType = cardToken.validateIdentificationType()
var errorIdentificationNumber : NSError? = nil
if self.identificationType != nil {
errorIdentificationNumber = cardToken.validateIdentificationNumber(self.identificationType!)
} else {
errorIdentificationNumber = cardToken.validateIdentificationNumber()
}
if errorIdentificationType != nil {
self.userIdCell.setError(errorIdentificationType!.userInfo["identification"] as? String)
result = false
} else if errorIdentificationNumber != nil {
self.userIdCell.setError(errorIdentificationNumber!.userInfo["identification"] as? String)
result = false
} else {
self.userIdCell.setError(nil)
}
let errorSecurityCode = cardToken.validateSecurityCode()
if errorSecurityCode != nil {
self.securityCodeCell.setError(errorSecurityCode!.userInfo["securityCode"] as? String)
result = false
} else {
self.securityCodeCell.setError(nil)
}
return result
}
func textFieldDidBeginEditing(textField: UITextField) {
let cell = textField.superview?.superview as! UITableViewCell?
self.tableView.scrollToRowAtIndexPath(self.tableView.indexPathForCell(cell!)!, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func createToken(cardToken: CardToken) {
let mercadoPago = MercadoPago(publicKey: self.publicKey!)
mercadoPago.createNewCardToken(cardToken, success: { (token) -> Void in
self.loadingView.removeFromSuperview()
self.callback?(token: token)
}, failure: nil)
}
}
|
c5bb1a86f76f3be1bc566de77990cf43
| 35.763682 | 403 | 0.756817 | false | false | false | false |
0x51/PrettyText
|
refs/heads/master
|
Example/Tests/Tests.swift
|
mit
|
1
|
// https://github.com/Quick/Quick
import Quick
import Nimble
import PrettyText
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("๐ฎ") == "๐ฎ"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
|
3748f13b9cd84aec62331ebe57c2fa70
| 22.42 | 63 | 0.363792 | false | false | false | false |
huonw/swift
|
refs/heads/master
|
test/SILOptimizer/diagnostic_constant_propagation_int_arch32.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
//
// REQUIRES: PTRSIZE=32
//
// This file tests diagnostics for arithmetic and bitwise operations on
// `Int` and `UInt` types for 32 bit architectures.
//
// FIXME: This test should be merged back into
// diagnostic_constant_propagation.swift when we have fixed:
// <rdar://problem/19434979> -verify does not respect #if
//
// FIXME: <rdar://problem/29937936> False negatives when using integer initializers
//
// FIXME: <rdar://problem/39193272> A false negative that happens only in REPL
func testArithmeticOverflow_Int_32bit() {
do {
// Literals.
var _: Int = 0x7fff_ffff // OK
var _: Int = 0x8000_0000 // expected-error {{integer literal '2147483648' overflows when stored into 'Int'}}
var _: Int = -0x8000_0000 // OK
var _: Int = -0x8000_0001 // expected-error {{integer literal '-2147483649' overflows when stored into 'Int'}}
}
do {
// Negation.
var _: Int = -(-0x7fff_ffff) // OK
var _: Int = -(-0x8000_0000) // expected-error {{arithmetic operation '0 - -2147483648' (on signed 32-bit integer type) results in an overflow}}
// FIXME: Missing diagnostic in REPL:
// <rdar://problem/39193272> Overflow in arithmetic negation is not detected
// at compile time when running in REPL
}
do {
// Addition.
var _: Int = 0x7fff_fffe + 1 // OK
var _: Int = 0x7fff_fffe + 2 // expected-error {{arithmetic operation '2147483646 + 2' (on type 'Int') results in an overflow}}
var _: Int = -0x7fff_ffff + (-1) // OK
var _: Int = -0x7fff_ffff + (-2) // expected-error {{arithmetic operation '-2147483647 + -2' (on type 'Int') results in an overflow}}
}
do {
// Subtraction.
var _: Int = 0x7fff_fffe - (-1) // OK
var _: Int = 0x7fff_fffe - (-2) // expected-error {{arithmetic operation '2147483646 - -2' (on type 'Int') results in an overflow}}
var _: Int = -0x7fff_ffff - 1 // OK
var _: Int = -0x7fff_ffff - 2 // expected-error {{arithmetic operation '-2147483647 - 2' (on type 'Int') results in an overflow}}
}
do {
// Multiplication.
var _: Int = 0x7fff_fffe * 1 // OK
var _: Int = 0x7fff_fffe * 2 // expected-error {{arithmetic operation '2147483646 * 2' (on type 'Int') results in an overflow}}
var _: Int = -0x7fff_ffff * 1 // OK
var _: Int = -0x7fff_ffff * 2 // expected-error {{arithmetic operation '-2147483647 * 2' (on type 'Int') results in an overflow}}
}
do {
// Division.
var _: Int = 0x7fff_fffe / 2 // OK
var _: Int = 0x7fff_fffe / 0 // expected-error {{division by zero}}
var _: Int = -0x7fff_ffff / 2 // OK
var _: Int = -0x7fff_ffff / 0 // expected-error {{division by zero}}
var _: Int = -0x8000_0000 / -1 // expected-error {{division '-2147483648 / -1' results in an overflow}}
}
do {
// Remainder.
var _: Int = 0x7fff_fffe % 2 // OK
var _: Int = 0x7fff_fffe % 0 // expected-error {{division by zero}}
var _: Int = -0x7fff_ffff % 2 // OK
var _: Int = -0x7fff_ffff % 0 // expected-error {{division by zero}}
var _: Int = -0x8000_0000 % -1 // expected-error {{division '-2147483648 % -1' results in an overflow}}
}
do {
// Right shift.
// Due to "smart shift" introduction, there can be no overflows errors
// during shift operations
var _: Int = 0 >> 0
var _: Int = 0 >> 1
var _: Int = 0 >> (-1)
var _: Int = 123 >> 0
var _: Int = 123 >> 1
var _: Int = 123 >> (-1)
var _: Int = (-1) >> 0
var _: Int = (-1) >> 1
var _: Int = 0x7fff_ffff >> 31
var _: Int = 0x7fff_ffff >> 32
var _: Int = 0x7fff_ffff >> 33
}
do {
// Left shift.
var _: Int = 0 << 0
var _: Int = 0 << 1
var _: Int = 0 << (-1)
var _: Int = 123 << 0
var _: Int = 123 << 1
var _: Int = 123 << (-1)
var _: Int = (-1) << 0
var _: Int = (-1) << 1
var _: Int = 0x7fff_ffff << 31
var _: Int = 0x7fff_ffff << 32
var _: Int = 0x7fff_ffff << 33
}
do {
var _ : Int = ~0
var _ : Int = (0x7fff_ffff) | (0x4000_0000 << 1)
var _ : Int = (0x7fff_ffff) | 0x8000_0000 // expected-error {{integer literal '2147483648' overflows when stored into 'Int'}}
}
}
func testArithmeticOverflow_UInt_32bit() {
do {
// Literals.
var _: UInt = 0x7fff_ffff // OK
var _: UInt = 0x8000_0000
var _: UInt = 0xffff_ffff
var _: UInt = -1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = -0xffff_ffff // expected-error {{negative integer '-4294967295' overflows when stored into unsigned type 'UInt'}}
}
do {
// Addition.
var _: UInt = 0 + 0 // OK
var _: UInt = 0xffff_ffff + 0 // OK
var _: UInt = 0xffff_ffff + 1 // expected-error {{arithmetic operation '4294967295 + 1' (on type 'UInt') results in an overflow}}
var _: UInt = 0xffff_fffe + 1 // OK
var _: UInt = 0xffff_fffe + 2 // expected-error {{arithmetic operation '4294967294 + 2' (on type 'UInt') results in an overflow}}
}
do {
// Subtraction.
var _: UInt = 0xffff_fffe - 1 // OK
var _: UInt = 0xffff_fffe - 0xffff_ffff // expected-error {{arithmetic operation '4294967294 - 4294967295' (on type 'UInt') results in an overflow}}
var _: UInt = 0 - 0 // OK
var _: UInt = 0 - 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt') results in an overflow}}
}
do {
// Multiplication.
var _: UInt = 0xffff_ffff * 0 // OK
var _: UInt = 0xffff_ffff * 1 // OK
var _: UInt = 0xffff_ffff * 2 // expected-error {{arithmetic operation '4294967295 * 2' (on type 'UInt') results in an overflow}}
var _: UInt = 0xffff_ffff * 0xffff_ffff // expected-error {{arithmetic operation '4294967295 * 4294967295' (on type 'UInt') results in an overflow}}
var _: UInt = 0x7fff_fffe * 0 // OK
var _: UInt = 0x7fff_fffe * 1 // OK
var _: UInt = 0x7fff_fffe * 2 // OK
var _: UInt = 0x7fff_fffe * 3 // expected-error {{arithmetic operation '2147483646 * 3' (on type 'UInt') results in an overflow}}
}
do {
// Division.
var _: UInt = 0x7fff_fffe / 2 // OK
var _: UInt = 0x7fff_fffe / 0 // expected-error {{division by zero}}
var _: UInt = 0xffff_ffff / 2 // OK
var _: UInt = 0xffff_ffff / 0 // expected-error {{division by zero}}
}
do {
// Remainder.
var _: UInt = 0x7fff_fffe % 2 // OK
var _: UInt = 0x7fff_fffe % 0 // expected-error {{division by zero}}
var _: UInt = 0xffff_ffff % 2 // OK
var _: UInt = 0xffff_ffff % 0 // expected-error {{division by zero}}
}
do {
// Shift operations don't result in overflow errors but note that
// one cannot use negative values while initializing of an unsigned value
var _: UInt = 0 >> 0
var _: UInt = 0 >> 1
var _: UInt = 123 >> 0
var _: UInt = 123 >> 1
var _: UInt = (-1) >> 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = (-1) >> 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = 0x7fff_ffff >> 31
var _: UInt = 0x7fff_ffff >> 32
var _: UInt = 0x7fff_ffff >> 33
}
do {
// Shift operations don't result in overflow errors but note that
// one cannot use negative values while initializing of an unsigned value
var _: UInt = 0 << 0
var _: UInt = 0 << 1
var _: UInt = 123 << 0
var _: UInt = 123 << 1
var _: UInt = (-1) << 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = (-1) << 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}}
var _: UInt = 0x7fff_ffff << 31
var _: UInt = 0x7fff_ffff << 32
var _: UInt = 0x7fff_ffff << 33
}
do {
// bitwise operations. No overflows happen during these operations
var _ : UInt = ~0
var _ : UInt = (0x7fff_ffff) | (0x4000_0000 << 1)
var _ : UInt = (0x7fff_ffff) | 0x8000_0000
}
}
|
49922124c51e83dfef58085c96cac7b0
| 33.599138 | 152 | 0.58951 | false | false | false | false |
carabina/AmazonS3RequestManager
|
refs/heads/master
|
AmazonS3RequestManagerTests/AmazonS3ACLTests.swift
|
mit
|
1
|
//
// AmazonS3ACLTests.swift
// AmazonS3RequestManager
//
// Created by Anthony Miller on 6/9/15.
// Copyright (c) 2015 Anthony Miller. All rights reserved.
//
import Quick
import Nimble
import AmazonS3RequestManager
class AmazonS3ACLSpec: QuickSpec {
override func spec() {
describe("PredefinedACL") {
context(".Private") {
let acl = AmazonS3PredefinedACL.Private
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] as? String
expect(aclHeader).to(equal("private"))
}
}
context(".Public") {
let acl = AmazonS3PredefinedACL.Public
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] as? String
expect(aclHeader).to(equal("public-read-write"))
}
}
context(".PublicReadOnly") {
let acl = AmazonS3PredefinedACL.PublicReadOnly
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] as? String
expect(aclHeader).to(equal("public-read"))
}
}
context(".AuthenticatedReadOnly") {
let acl = AmazonS3PredefinedACL.AuthenticatedReadOnly
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] as? String
expect(aclHeader).to(equal("authenticated-read"))
}
}
context(".BucketOwnerReadOnly") {
let acl = AmazonS3PredefinedACL.BucketOwnerReadOnly
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] as? String
expect(aclHeader).to(equal("bucket-owner-read"))
}
}
context(".BucketOwnerFullControl") {
let acl = AmazonS3PredefinedACL.BucketOwnerFullControl
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] as? String
expect(aclHeader).to(equal("bucket-owner-full-control"))
}
}
context(".LogDeliveryWrite") {
let acl = AmazonS3PredefinedACL.LogDeliveryWrite
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] as? String
expect(aclHeader).to(equal("log-delivery-write"))
}
}
}
describe("ACL Permission Grant") {
describe("With Permission") {
func aclWithPermission(permission: AmazonS3ACLPermission) -> AmazonS3ACLPermissionGrant {
let grantee = AmazonS3ACLGrantee.AuthenticatedUsers
return AmazonS3ACLPermissionGrant(permission: permission, grantee: grantee)
}
describe("Read") {
let permission = AmazonS3ACLPermission.Read
let acl = aclWithPermission(permission)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] as? String
expect(aclHeader).toNot(beNil())
}
}
describe("Write") {
let permission = AmazonS3ACLPermission.Write
let acl = aclWithPermission(permission)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write"] as? String
expect(aclHeader).toNot(beNil())
}
}
describe("Read ACL") {
let permission = AmazonS3ACLPermission.ReadACL
let acl = aclWithPermission(permission)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read-acp"] as? String
expect(aclHeader).toNot(beNil())
}
}
describe("Write ACL") {
let permission = AmazonS3ACLPermission.WriteACL
let acl = aclWithPermission(permission)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write-acp"] as? String
expect(aclHeader).toNot(beNil())
}
}
describe("Full Control") {
let permission = AmazonS3ACLPermission.FullControl
let acl = aclWithPermission(permission)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-full-control"] as? String
expect(aclHeader).toNot(beNil())
}
}
}
describe("With Grantee") {
func aclWithGrantee(grantee: AmazonS3ACLGrantee) -> AmazonS3ACLPermissionGrant {
let permission = AmazonS3ACLPermission.Read
return AmazonS3ACLPermissionGrant(permission: permission, grantee: grantee)
}
describe("Grantee: Authenticated Users") {
let grantee = AmazonS3ACLGrantee.AuthenticatedUsers
let acl = aclWithGrantee(grantee)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] as? String
expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AuthenticatedUsers\""))
}
}
describe("Grantee: All Users") {
let grantee = AmazonS3ACLGrantee.AllUsers
let acl = aclWithGrantee(grantee)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] as? String
expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AllUsers\""))
}
}
describe("Grantee: Log Delivery Group") {
let grantee = AmazonS3ACLGrantee.LogDeliveryGroup
let acl = aclWithGrantee(grantee)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] as? String
expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/s3/LogDelivery\""))
}
}
describe("Grantee: Email") {
let grantee = AmazonS3ACLGrantee.EmailAddress("[email protected]")
let acl = aclWithGrantee(grantee)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] as? String
expect(aclHeader).to(equal("emailAddress=\"[email protected]\""))
}
}
describe("Grantee: User ID") {
let grantee = AmazonS3ACLGrantee.UserID("123456")
let acl = aclWithGrantee(grantee)
it("sets ACL request headers") {
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] as? String
expect(aclHeader).to(equal("id=\"123456\""))
}
}
}
describe("With Multiple Grantees") {
func aclWithGrantees(grantees: Set<AmazonS3ACLGrantee>) -> AmazonS3ACLPermissionGrant {
let permission = AmazonS3ACLPermission.Read
return AmazonS3ACLPermissionGrant(permission: permission, grantees: grantees)
}
it("sets ACL request headers") {
let acl = aclWithGrantees([
AmazonS3ACLGrantee.EmailAddress("[email protected]"),
AmazonS3ACLGrantee.UserID("123456")])
var request = NSMutableURLRequest()
acl.setACLHeaders(forRequest: &request)
let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] as? String
expect(aclHeader).to(equal("emailAddress=\"[email protected]\", id=\"123456\""))
}
}
}
}
}
|
222cf8f09e63bdffa6c72967935ed314
| 34.126812 | 108 | 0.578649 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/00194-swift-parser-parseexprsequence.swift
|
apache-2.0
|
12
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
typealias E
}
struct B<T : A> {
let h -> g {
d j d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}
class d: f{ class func i {}
struct d<f : e,e where g.h == f.h> {
}
protocolias h
}
func some<S: SequenceType, T where Optional<T> == S.Generator.Element>(xs : S) -> T? {
for (mx : T?) in xs {
if let x = mx {
return x
}
}
return nil
}
let xs : [Int?] = [nil, 4, nil]
print(some(xs))
fuotocol A {
typealias B
}return []
}
func i(c: () -> ()) {
}
cnc c<d {
enum c {
func e
var _ = e
}
}
class A<T : A> {
}
func some<C -> b = b
}
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
var x1 = 1
var f1: Int -> Int = {
return $0
}
let su a(2, 3)))
|
9122ecb16a321c23753d174a0e456015
| 15.094595 | 87 | 0.518892 | false | false | false | false |
warren-gavin/OBehave
|
refs/heads/master
|
OBehave/Classes/Effects/BlurImage/OBBlurImageBehaviorEffect.swift
|
mit
|
1
|
//
// OBBlurImageBehaviorEffect.swift
// OBehave
//
// Created by Warren Gavin on 02/11/15.
// Copyright ยฉ 2015 Apokrupto. All rights reserved.
//
import UIKit
import Accelerate
public final class OBBlurImageBehaviorEffect: OBBehaviorEffect {
@IBInspectable public var maxRadius: CGFloat = .maxRadius
@IBInspectable public var saturation: CGFloat = .saturation
@IBInspectable public var tintColor: UIColor?
override public func performEffect(on object: AnyObject?, percentage percent: CGFloat) -> AnyObject? {
guard let image = object as? UIImage, percent > 0 else {
return super.performEffect(on: object, percentage: percent)
}
return image.applyBlur(withRadius: percent * maxRadius,
tintColor: tintColor?.withAlphaComponent(percent / 2.0),
saturationDeltaFactor: .saturation + (percent * (saturation - .saturation)),
maskImage:nil)
}
}
private extension CGFloat {
static let maxRadius: CGFloat = 40.0
static let saturation: CGFloat = 1.0
static let effectSaturation: CGFloat = 1.8
static let effectColorAlpha: CGFloat = 0.6
static let saturationDivisor: CGFloat = 256.0
static let floatEpsilon = CGFloat(Float.ulpOfOne)
}
extension UIBlurEffect.Style {
func color() -> UIColor {
switch self {
case .extraLight:
return UIColor(white: 0.97, alpha: 0.82)
case .dark, .extraDark:
return UIColor(white: 0.11, alpha: 0.73)
case .light, .prominent, .regular:
return UIColor(white: 1.0, alpha: 0.3)
default:
return UIColor(white: 1.0, alpha: 0.3)
}
}
func radius() -> CGFloat {
switch self {
case .light, .prominent, .regular:
return 30.0
case .extraLight, .dark, .extraDark:
return 20.0
default:
return 30.0
}
}
}
extension UIImage {
private func createEffectBuffer(context: CGContext) -> vImage_Buffer {
return vImage_Buffer(data: context.data,
height: vImagePixelCount(context.height),
width: vImagePixelCount(context.width),
rowBytes: context.bytesPerRow)
}
private func applyBlur(inputRadius: CGFloat,
effectInContext: CGContext,
effectOutContext: CGContext) -> (vImage_Buffer, vImage_Buffer) {
var effectInBuffer = createEffectBuffer(context: effectInContext)
var effectOutBuffer = createEffectBuffer(context: effectOutContext)
if inputRadius > .floatEpsilon {
let tmp = floor(inputRadius * 3.0 * CGFloat(sqrt(2 * .pi)) / 4 + 0.5)
var radius = UInt32(tmp)
radius += (radius % 2 == 0 ? 1 : 0)
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
return (effectInBuffer, effectOutBuffer)
}
private func blurAndSaturate(blurRadius: CGFloat,
saturationDeltaFactor: CGFloat,
hasSaturationChange: Bool,
imageRect: CGRect,
screenScale: CGFloat) -> UIImage? {
var effectImage = self
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
defer {
UIGraphicsEndImageContext()
}
guard let effectInContext = UIGraphicsGetCurrentContext(), let image = cgImage else {
return nil
}
effectInContext.scaleBy(x: 1.0, y: -1.0)
effectInContext.translateBy(x: 0, y: -size.height)
effectInContext.draw(image, in: imageRect)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
guard let effectOutContext = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
let (effectInBuffer, effectOutBuffer) = applyBlur(inputRadius: blurRadius * screenScale,
effectInContext: effectInContext,
effectOutContext: effectOutContext)
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s = saturationDeltaFactor
let saturationMatrix: [Int16] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
].map { (value: CGFloat) -> Int16 in
Int16(round(value * .saturationDivisor))
}
var srcBuffer = effectInBuffer
var dstBuffer = effectOutBuffer
if blurRadius > .floatEpsilon {
srcBuffer = effectOutBuffer
dstBuffer = effectInBuffer
effectImageBuffersAreSwapped = (blurRadius > .floatEpsilon)
}
vImageMatrixMultiply_ARGB8888(&srcBuffer,
&dstBuffer,
saturationMatrix,
Int32(.saturationDivisor),
nil,
nil,
vImage_Flags(kvImageNoFlags))
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
else {
UIGraphicsEndImageContext()
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
return effectImage
}
private func outputImage(image: UIImage,
maskImage: UIImage?,
hasBlur: Bool,
tintColor: UIColor?,
screenScale: CGFloat,
imageRect: CGRect) -> UIImage? {
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
defer {
UIGraphicsEndImageContext()
}
guard
let outputContext = UIGraphicsGetCurrentContext(),
let inputImage = image.cgImage
else {
return nil
}
outputContext.scaleBy(x: 1.0, y: -1.0)
outputContext.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext.draw(inputImage, in: imageRect)
// Draw effect image.
if hasBlur {
outputContext.saveGState()
if let maskImage = maskImage?.cgImage, let image = image.cgImage {
outputContext.clip(to: imageRect, mask: maskImage)
outputContext.draw(image, in: imageRect)
}
outputContext.restoreGState()
}
// Add in color tint.
if let tintColor = tintColor {
outputContext.saveGState()
outputContext.setFillColor(tintColor.cgColor)
outputContext.fill(imageRect)
outputContext.restoreGState()
}
// Output image is ready.
return UIGraphicsGetImageFromCurrentImageContext()
}
@nonobjc
internal func applyBlurEffect(effect: UIBlurEffect.Style, saturation: CGFloat = .effectSaturation) -> UIImage? {
return applyBlur(withRadius: effect.radius(), tintColor: effect.color(), saturationDeltaFactor: saturation)
}
@nonobjc
internal func applyTintEffectWithColor(tintColor: UIColor) -> UIImage? {
var effectColor = tintColor
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: .effectColorAlpha)
}
return applyBlur(withRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
@nonobjc
internal func applyBlur(withRadius blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
// Check pre-conditions.
if (size.width < 1 || size.height < 1) {
return nil
}
if cgImage == nil {
return nil
}
if let maskImage = maskImage, maskImage.cgImage == nil {
return nil
}
let hasBlur = blurRadius > .floatEpsilon
let hasSaturationChange = abs(saturationDeltaFactor - 1.0) > .floatEpsilon
let screenScale = UIScreen.main.scale
let imageRect = CGRect(origin: .zero, size: size)
var effectImage = self
if hasBlur || hasSaturationChange {
guard let blurredAndSaturatedImage = blurAndSaturate(blurRadius: blurRadius,
saturationDeltaFactor: saturationDeltaFactor,
hasSaturationChange: hasSaturationChange,
imageRect: imageRect,
screenScale: screenScale)
else {
return nil
}
effectImage = blurredAndSaturatedImage
}
return outputImage(image: effectImage,
maskImage: maskImage,
hasBlur: hasBlur,
tintColor: tintColor,
screenScale: screenScale,
imageRect: imageRect)
}
}
|
b6e38ad380fce7bcac293e4269a68df8
| 37.264286 | 153 | 0.535094 | false | false | false | false |
r4phab/ECAB
|
refs/heads/iOS9
|
ECAB/TestsTableViewController.swift
|
mit
|
1
|
//
// GamesTableViewController.swift
// ECAB
//
// Created by Boris Yurkevich on 3/9/15.
// Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import UIKit
class TestsTableViewController: UITableViewController {
let model = Model.sharedInstance
private let reuseIdentifier = "Games Table Cell"
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return model.games.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SubtestCell
cell.title.text = model.games[indexPath.row].rawValue
switch model.games[indexPath.row].rawValue {
case Game.AuditorySustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_auditory.rawValue)
cell.subtitle.text = "Touch when the animal is heared"
case Game.VisualSearch.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_visualSearch.rawValue)
cell.subtitle.text = "Touch the red apples"
case Game.VisualSustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_visualSustain.rawValue)
cell.subtitle.text = "Touch when the animal is seen"
case Game.BalloonSorting.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_balloonSorting.rawValue)
cell.subtitle.text = "Work out the balloons"
case Game.DualSustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_dualTask.rawValue)
cell.subtitle.text = "Touch when animal heard or seen"
case Game.Flanker.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_flanker.rawValue)
cell.subtitle.text = "Touch the side the fish is facing"
case Game.VerbalOpposites.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_verbalOpposites.rawValue)
cell.subtitle.text = "Speak the animal name"
case Game.Counterpointing.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_counterpointing.rawValue)
cell.subtitle.text = "Touch the side of the dog"
default:
cell.icon.image = UIImage(named: Picture.Icon_auditory.rawValue)
}
return cell
}
// Select correct test row when the view is displayed
override func viewWillAppear(animated: Bool) {
if(model.data != nil){
selectRow(model.data.selectedGame.integerValue)
}
}
// MARK: โ Table View delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
model.data.selectedGame = indexPath.row
model.save()
let navVC = splitViewController!.viewControllers.last as! UINavigationController
let detailVC = navVC.topViewController as! TestViewController
detailVC.showTheGame(model.data.selectedGame.integerValue)
}
func selectRow(index:Int) {
let rowToSelect:NSIndexPath = NSIndexPath(forRow: index, inSection: 0)
self.tableView.selectRowAtIndexPath(rowToSelect, animated: false, scrollPosition:UITableViewScrollPosition.None)
}
}
|
9e2582f6f4224078f0fb7fb92962e199
| 38.822222 | 120 | 0.657645 | false | false | false | false |
RLovelett/langserver-swift
|
refs/heads/master
|
Sources/BaseProtocol/Types/RequestBuffer.swift
|
apache-2.0
|
1
|
//
// RequestBuffer.swift
// langserver-swift
//
// Created by Ryan Lovelett on 12/8/16.
//
//
import Foundation
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import os.log
private let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "RequestBuffer")
#endif
private let terminatorPattern = Data(bytes: [0x0D, 0x0A, 0x0D, 0x0A]) // "\r\n\r\n"
public class RequestBuffer {
fileprivate var buffer: Data
public init(_ data: Data? = nil) {
buffer = data ?? Data()
}
public func append(_ data: Data) {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
os_log("Adding %{iec-bytes}d to the request buffer which has %{iec-bytes}d", log: log, type: .default, data.count, buffer.count)
#endif
buffer.append(data)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
if let new = String(bytes: data, encoding: .utf8), let buffer = String(bytes: buffer, encoding: .utf8) {
os_log("Added: %{public}@", log: log, type: .default, new)
os_log("Buffer: %{public}@", log: log, type: .default, buffer)
}
#endif
}
public func append(_ data: DispatchData) {
data.withUnsafeBytes { [count = data.count] in
buffer.append($0, count: count)
}
}
}
extension RequestBuffer : IteratorProtocol {
public func next() -> Data? {
guard !buffer.isEmpty else { return nil }
let separatorRange = buffer.range(of: terminatorPattern) ?? (buffer.endIndex..<buffer.endIndex)
let extractedData = buffer.subdata(in: buffer.startIndex..<separatorRange.lowerBound)
let distance = Header(extractedData).contentLength ?? 0
guard let index = buffer.index(separatorRange.upperBound, offsetBy: distance, limitedBy: buffer.endIndex) else {
return nil
}
defer {
buffer.removeSubrange(Range<Data.Index>(buffer.startIndex..<index))
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
let bytes = buffer.startIndex.distance(to: index)
os_log("Removing %{iec-bytes}d from the request buffer which has %{iec-bytes}d", log: log, type: .default, bytes, buffer.count)
#endif
}
return buffer.subdata(in: Range<Data.Index>(separatorRange.upperBound..<index))
}
}
extension RequestBuffer : Sequence {
public func makeIterator() -> RequestBuffer {
return self
}
}
|
3945641587cf55cebc96d8b6043306aa
| 31.973333 | 143 | 0.612212 | false | false | false | false |
amosavian/swift-corelibs-foundation
|
refs/heads/master
|
Foundation/Array.swift
|
apache-2.0
|
11
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
extension Array : _ObjectTypeBridgeable {
public typealias _ObjectType = NSArray
public func _bridgeToObjectiveC() -> _ObjectType {
return NSArray(array: map { (element: Element) -> AnyObject in
return _SwiftValue.store(element)
})
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Array?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Array?) -> Bool {
var array = [Element]()
for value in source.allObjects {
if let v = value as? Element {
array.append(v)
} else {
return false
}
}
result = array
return true
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Array {
if let object = source {
var value: Array<Element>?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return Array<Element>()
}
}
}
|
9ec096c4e94b9db82efd0f718ceef4ec
| 32.085106 | 112 | 0.620579 | false | false | false | false |
gribozavr/swift
|
refs/heads/master
|
stdlib/public/core/Codable.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// 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. The type is _*Base so that it's
/// generic on the key type.
internal var _box: _KeyedEncodingContainerBase<Key>
/// 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. The type is _*Base so that it's
/// generic on the key type.
internal var _box: _KeyedDecodingContainerBase<Key>
/// 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
}
/// 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<Key: CodingKey> {
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(forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Bool, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: String, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Double, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Float, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int8, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int16, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int32, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int64, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt8, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt16, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt32, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt64, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<T: Encodable>(_ value: T, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Bool?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: String?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Double?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Float?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int8?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int16?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int32?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int64?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder() -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder(forKey key: Key) -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedEncodingContainerBox<
Concrete: KeyedEncodingContainerProtocol
>: _KeyedEncodingContainerBase<Concrete.Key> {
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(forKey key: Key) throws {
try concrete.encodeNil(forKey: key)
}
override internal func encode(_ value: Bool, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: String, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Double, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Float, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int8, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int16, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int32, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int64, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt8, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt16, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt32, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt64, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode<T: Encodable>(
_ value: T,
forKey key: Key
) throws {
try concrete.encode(value, forKey: key)
}
override internal func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try concrete.encodeConditional(object, forKey: key)
}
override internal func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
return concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer {
return concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superEncoder() -> Encoder {
return concrete.superEncoder()
}
override internal func superEncoder(forKey key: Key) -> Encoder {
return concrete.superEncoder(forKey: key)
}
}
internal class _KeyedDecodingContainerBase<Key: CodingKey> {
internal init(){}
deinit {}
internal var codingPath: [CodingKey] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal var allKeys: [Key] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func contains(_ key: Key) -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeNil(forKey key: Key) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: String.Type,
forKey key: Key
) throws -> String {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Double.Type,
forKey key: Key
) throws -> Double {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Float.Type,
forKey key: Key
) throws -> Float {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int.Type,
forKey key: Key
) throws -> Int {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder() throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder(forKey key: Key) throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedDecodingContainerBox<
Concrete: KeyedDecodingContainerProtocol
>: _KeyedDecodingContainerBase<Concrete.Key> {
typealias Key = Concrete.Key
internal var concrete: Concrete
internal init(_ container: Concrete) {
concrete = container
}
override var codingPath: [CodingKey] {
return concrete.codingPath
}
override var allKeys: [Key] {
return concrete.allKeys
}
override internal func contains(_ key: Key) -> Bool {
return concrete.contains(key)
}
override internal func decodeNil(forKey key: Key) throws -> Bool {
return try concrete.decodeNil(forKey: key)
}
override internal func decode(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool {
return try concrete.decode(Bool.self, forKey: key)
}
override internal func decode(
_ type: String.Type,
forKey key: Key
) throws -> String {
return try concrete.decode(String.self, forKey: key)
}
override internal func decode(
_ type: Double.Type,
forKey key: Key
) throws -> Double {
return try concrete.decode(Double.self, forKey: key)
}
override internal func decode(
_ type: Float.Type,
forKey key: Key
) throws -> Float {
return try concrete.decode(Float.self, forKey: key)
}
override internal func decode(
_ type: Int.Type,
forKey key: Key
) throws -> Int {
return try concrete.decode(Int.self, forKey: key)
}
override internal func decode(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8 {
return try concrete.decode(Int8.self, forKey: key)
}
override internal func decode(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16 {
return try concrete.decode(Int16.self, forKey: key)
}
override internal func decode(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32 {
return try concrete.decode(Int32.self, forKey: key)
}
override internal func decode(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64 {
return try concrete.decode(Int64.self, forKey: key)
}
override internal func decode(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt {
return try concrete.decode(UInt.self, forKey: key)
}
override internal func decode(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8 {
return try concrete.decode(UInt8.self, forKey: key)
}
override internal func decode(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16 {
return try concrete.decode(UInt16.self, forKey: key)
}
override internal func decode(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32 {
return try concrete.decode(UInt32.self, forKey: key)
}
override internal func decode(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64 {
return try concrete.decode(UInt64.self, forKey: key)
}
override internal func decode<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T {
return try concrete.decode(T.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
return try concrete.decodeIfPresent(Bool.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
return try concrete.decodeIfPresent(String.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
return try concrete.decodeIfPresent(Double.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
return try concrete.decodeIfPresent(Float.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
return try concrete.decodeIfPresent(Int.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
return try concrete.decodeIfPresent(Int8.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
return try concrete.decodeIfPresent(Int16.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
return try concrete.decodeIfPresent(Int32.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
return try concrete.decodeIfPresent(Int64.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
return try concrete.decodeIfPresent(UInt.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
return try concrete.decodeIfPresent(UInt8.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
return try concrete.decodeIfPresent(UInt16.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
return try concrete.decodeIfPresent(UInt32.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
return try concrete.decodeIfPresent(UInt64.self, forKey: key)
}
override internal func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
return try concrete.decodeIfPresent(T.self, forKey: key)
}
override internal func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
return try concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer {
return try concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superDecoder() throws -> Decoder {
return try concrete.superDecoder()
}
override internal func superDecoder(forKey key: Key) throws -> Decoder {
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
}
}
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)
}
}
|
7068ced0422a7bfd9030902ef90ba9b8
| 36.48997 | 111 | 0.676173 | false | false | false | false |
CoderJackyHuang/ITClient-Swift
|
refs/heads/master
|
ITClient-Swift/Util/HttpURL.swift
|
mit
|
1
|
//
// HttpURL.swift
// ITClient-Swift
//
// Created by huangyibiao on 15/9/24.
// Copyright ยฉ 2015ๅนด huangyibiao. All rights reserved.
//
import UIKit
/// HTTP URL
///
/// Author: ้ปไปชๆ
/// Blog: http://www.hybblog.com/
/// Github: http://github.com/CoderJackyHuang/
/// Email: [email protected]
/// Weibo: JackyHuang๏ผๆ ๅฅ๏ผ
struct HttpURL {
/// Get log in url
///
/// - returns: The absolute url to log in
static func loginUrl() ->String {
return baseUrl + "PeopleServer/saveUser/"
}
/// Get the url of category of technology
///
/// - parameter currentPage: Current page index
/// - parameter pageSize: How many rows to load
///
/// - returns: The absolute url
static func technologyUrl(currentPage: Int, pageSize: Int) ->String {
let url = "ArticleServer/queryArticleListByCategory/2"
return baseUrl + "\(url)/\(currentPage)/\(pageSize)"
}
/// Get home url
///
/// - parameter currentPage: Current page index
/// - parameter pageSize: How many rows to load
///
/// - returns: The absolute url
static func homeUrl(currentPage: Int, pageSize: Int) ->String {
let url = "ArticleServer/queryArticleListByNew/"
return baseUrl + url + "\(currentPage)/\(pageSize)"
}
/// Get interest url
///
/// - parameter currentPage: Current page index
/// - parameter pageSize: How many rows to load
///
/// - returns: The absolute url
static func interestUrl(currentPage: Int, pageSize: Int) ->String {
let url = "ArticleServer/queryArticleListByCategory/4"
return baseUrl + "\(url)/\(currentPage)/\(pageSize)"
}
/// Get article detail url
///
/// - parameter articleId: The id of an article
/// - parameter userId: user id, if user have logined.
///
/// - returns: The absolute url of article details
static func articleUrl(articleId: String, userId: String = "") ->String {
let url = "ArticleServer/queryArticleById/\(articleId)"
if userId.isEmpty {
return baseUrl + url
}
return baseUrl + url + "?userId=\(userId)"
}
/// Get collect article url
///
/// - returns: The absolute url of collecting article
static func storeArticleUrl() ->String {
let url = "poas/userCollectionArticle"
return baseUrl + url
}
private static var baseUrl = "http://api.itjh.net/v1/"
}
|
a89e9d8086cbfbf799b2acfef441530e
| 26.321839 | 75 | 0.634259 | false | false | false | false |
Ricky-Choi/AppUIKit
|
refs/heads/master
|
AppUIKit/View/AUIViewController.swift
|
mit
|
1
|
//
// AUIViewController.swift
// AppUIKit
//
// Created by ricky on 2016. 12. 5..
// Copyright ยฉ 2016๋
appcid. All rights reserved.
//
import Cocoa
open class AUIViewController: NSViewController {
var _tabBarItem: AUITabBarItem?
public var navigationController: AUINavigationController? {
return nearestAncestor() as? AUINavigationController
}
lazy public private(set) var navigationItem: AUINavigationItem = {
return AUINavigationItem(title: self.title ?? "")
}()
open override var title: String? {
didSet {
navigationItem.title = title
}
}
public init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
open override func loadView() {
view = AUIView()
}
func setup() {
}
override open func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
extension NSViewController {
func nearestAncestor<T: NSViewController>() -> T? {
var target: NSViewController = self
while let parent = target.parent {
if let parent = parent as? T {
return parent
}
target = parent
}
return nil
}
}
|
10699cdca648c38f9c74f802f4a98e51
| 20.539683 | 70 | 0.569639 | false | false | false | false |
wireapp/wire-ios-data-model
|
refs/heads/develop
|
Tests/Source/Model/Messages/CryptoBoxTests.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
import WireCryptobox
@testable import WireDataModel
class CryptoBoxTest: OtrBaseTest {
func testThatCryptoBoxFolderIsForbiddenFromBackup() {
// when
let accountId = UUID()
let accountFolder = CoreDataStack.accountDataFolder(accountIdentifier: accountId, applicationContainer: OtrBaseTest.sharedContainerURL)
let keyStore = UserClientKeysStore(accountDirectory: accountFolder, applicationContainer: OtrBaseTest.sharedContainerURL)
// then
guard let values = try? keyStore.cryptoboxDirectory.resourceValues(forKeys: Set(arrayLiteral: .isExcludedFromBackupKey)) else {return XCTFail()}
XCTAssertTrue(values.isExcludedFromBackup!)
}
func testThatCryptoBoxFolderIsMarkedForEncryption() {
#if targetEnvironment(simulator)
// File protection API is not available on simulator
XCTAssertTrue(true)
return
#else
// when
UserClientKeysStore.setupBox()
// then
let attrs = try! NSFileManager.default.attributesOfItemAtPath(UserClientKeysStore.otrDirectoryURL.path)
let fileProtectionAttr = (attrs[NSFileProtectionKey]! as! String)
XCTAssertEqual(fileProtectionAttr, NSFileProtectionCompleteUntilFirstUserAuthentication)
#endif
}
}
|
ecda0a036b2290952d52ee6b28f446a3
| 37.603774 | 152 | 0.721408 | false | true | false | false |
Johennes/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/OpenInHelper.swift
|
mpl-2.0
|
1
|
/* 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 PassKit
import WebKit
import SnapKit
import Shared
import XCGLogger
private let log = Logger.browserLogger
struct OpenInViewUX {
static let ViewHeight: CGFloat = 40.0
static let TextFont = UIFont.systemFontOfSize(16)
static let TextColor = UIColor(red: 74.0/255.0, green: 144.0/255.0, blue: 226.0/255.0, alpha: 1.0)
static let TextOffset = -15
static let OpenInString = NSLocalizedString("Open inโฆ", comment: "String indicating that the file can be opened in another application on the device")
}
enum MimeType: String {
case PDF = "application/pdf"
case PASS = "application/vnd.apple.pkpass"
}
protocol OpenInHelper {
init?(response: NSURLResponse)
var openInView: UIView? { get set }
func open()
}
struct OpenIn {
static let helpers: [OpenInHelper.Type] = [OpenPdfInHelper.self, OpenPassBookHelper.self, ShareFileHelper.self]
static func helperForResponse(response: NSURLResponse) -> OpenInHelper? {
return helpers.flatMap { $0.init(response: response) }.first
}
}
class ShareFileHelper: NSObject, OpenInHelper {
var openInView: UIView? = nil
private var url: NSURL
var pathExtension: String?
required init?(response: NSURLResponse) {
guard let MIMEType = response.MIMEType where !(MIMEType == MimeType.PASS.rawValue || MIMEType == MimeType.PDF.rawValue),
let responseURL = response.URL else { return nil }
url = responseURL
super.init()
}
func open() {
let alertController = UIAlertController(
title: Strings.OpenInDownloadHelperAlertTitle,
message: Strings.OpenInDownloadHelperAlertMessage,
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction( UIAlertAction(title: Strings.OpenInDownloadHelperAlertCancel, style: .Cancel, handler: nil))
alertController.addAction(UIAlertAction(title: Strings.OpenInDownloadHelperAlertConfirm, style: .Default) { (action) in
let objectsToShare = [self.url]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
if let sourceView = self.openInView, popoverController = activityVC.popoverPresentationController {
popoverController.sourceView = sourceView
popoverController.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(sourceView.bounds), y: CGRectGetMaxY(sourceView.bounds)), size: CGSizeZero)
popoverController.permittedArrowDirections = .Up
}
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(activityVC, animated: true, completion: nil)
})
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
class OpenPassBookHelper: NSObject, OpenInHelper {
var openInView: UIView? = nil
private var url: NSURL
required init?(response: NSURLResponse) {
guard let MIMEType = response.MIMEType where MIMEType == MimeType.PASS.rawValue && PKAddPassesViewController.canAddPasses(),
let responseURL = response.URL else { return nil }
url = responseURL
super.init()
}
func open() {
guard let passData = NSData(contentsOfURL: url) else { return }
var error: NSError? = nil
let pass = PKPass(data: passData, error: &error)
if let _ = error {
// display an error
let alertController = UIAlertController(
title: Strings.UnableToAddPassErrorTitle,
message: Strings.UnableToAddPassErrorMessage,
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(
UIAlertAction(title: Strings.UnableToAddPassErrorDismiss, style: .Cancel) { (action) in
// Do nothing.
})
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
return
}
let passLibrary = PKPassLibrary()
if passLibrary.containsPass(pass) {
UIApplication.sharedApplication().openURL(pass.passURL!)
} else {
let addController = PKAddPassesViewController(pass: pass)
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(addController, animated: true, completion: nil)
}
}
}
class OpenPdfInHelper: NSObject, OpenInHelper, UIDocumentInteractionControllerDelegate {
private var url: NSURL
private var docController: UIDocumentInteractionController? = nil
private var openInURL: NSURL?
lazy var openInView: UIView? = getOpenInView(self)()
lazy var documentDirectory: NSURL = {
return NSURL(string: NSTemporaryDirectory())!.URLByAppendingPathComponent("pdfs")!
}()
private var filepath: NSURL?
required init?(response: NSURLResponse) {
guard let MIMEType = response.MIMEType where MIMEType == MimeType.PDF.rawValue && UIApplication.sharedApplication().canOpenURL(NSURL(string: "itms-books:")!),
let responseURL = response.URL else { return nil }
url = responseURL
super.init()
setFilePath(response.suggestedFilename ?? url.lastPathComponent ?? "file.pdf")
}
private func setFilePath(suggestedFilename: String) {
var filename = suggestedFilename
let pathExtension = filename.asURL?.pathExtension
if pathExtension == nil {
filename.appendContentsOf(".pdf")
}
filepath = documentDirectory.URLByAppendingPathComponent(filename)
}
deinit {
guard let url = openInURL else { return }
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtURL(url)
} catch {
log.error("failed to delete file at \(url): \(error)")
}
}
func getOpenInView() -> OpenInView {
let overlayView = OpenInView()
overlayView.openInButton.addTarget(self, action: #selector(OpenPdfInHelper.open), forControlEvents: .TouchUpInside)
return overlayView
}
func createDocumentControllerForURL(url: NSURL) {
docController = UIDocumentInteractionController(URL: url)
docController?.delegate = self
self.openInURL = url
}
func createLocalCopyOfPDF() {
guard let filePath = filepath else {
log.error("failed to create proper URL")
return
}
if docController == nil {
// if we already have a URL but no document controller, just create the document controller
if let url = openInURL {
createDocumentControllerForURL(url)
return
}
let contentsOfFile = NSData(contentsOfURL: url)
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.createDirectoryAtPath(documentDirectory.absoluteString!, withIntermediateDirectories: true, attributes: nil)
if fileManager.createFileAtPath(filePath.absoluteString!, contents: contentsOfFile, attributes: nil) {
let openInURL = NSURL(fileURLWithPath: filePath.absoluteString!)
createDocumentControllerForURL(openInURL)
} else {
log.error("Unable to create local version of PDF file at \(filePath)")
}
} catch {
log.error("Error on creating directory at \(documentDirectory)")
}
}
}
func open() {
createLocalCopyOfPDF()
guard let _parentView = self.openInView!.superview, docController = self.docController else { log.error("view doesn't have a superview so can't open anything"); return }
// iBooks should be installed by default on all devices we care about, so regardless of whether or not there are other pdf-capable
// apps on this device, if we can open in iBooks we can open this PDF
// simulators do not have iBooks so the open in view will not work on the simulator
if UIApplication.sharedApplication().canOpenURL(NSURL(string: "itms-books:")!) {
log.info("iBooks installed: attempting to open pdf")
docController.presentOpenInMenuFromRect(CGRectZero, inView: _parentView, animated: true)
} else {
log.info("iBooks is not installed")
}
}
}
class OpenInView: UIView {
let openInButton = UIButton()
init() {
super.init(frame: CGRectZero)
openInButton.setTitleColor(OpenInViewUX.TextColor, forState: UIControlState.Normal)
openInButton.setTitle(OpenInViewUX.OpenInString, forState: UIControlState.Normal)
openInButton.titleLabel?.font = OpenInViewUX.TextFont
openInButton.sizeToFit()
self.addSubview(openInButton)
openInButton.snp_makeConstraints { make in
make.centerY.equalTo(self)
make.height.equalTo(self)
make.trailing.equalTo(self).offset(OpenInViewUX.TextOffset)
}
self.backgroundColor = UIColor.whiteColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
635159d2e53fa0465e86b182ef8aa3fe
| 40.37069 | 177 | 0.668785 | false | false | false | false |
bryan1anderson/iMessage-to-Day-One-Importer
|
refs/heads/master
|
Pods/SQLite.swift/Sources/SQLite/Core/Connection.swift
|
mit
|
2
|
//
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright ยฉ 2014-2015 Stephen Celis.
//
// 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.NSUUID
import Dispatch
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif SWIFT_PACKAGE || COCOAPODS
import SQLite3
#endif
/// A connection to SQLite.
public final class Connection {
/// The location of a SQLite database.
public enum Location {
/// An in-memory database (equivalent to `.uri(":memory:")`).
///
/// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb>
case inMemory
/// A temporary, file-backed database (equivalent to `.uri("")`).
///
/// See: <https://www.sqlite.org/inmemorydb.html#temp_db>
case temporary
/// A database located at the given URI filename (or path).
///
/// See: <https://www.sqlite.org/uri.html>
///
/// - Parameter filename: A URI filename
case uri(String)
}
/// An SQL operation passed to update callbacks.
public enum Operation {
/// An INSERT operation.
case insert
/// An UPDATE operation.
case update
/// A DELETE operation.
case delete
fileprivate init(rawValue:Int32) {
switch rawValue {
case SQLITE_INSERT:
self = .insert
case SQLITE_UPDATE:
self = .update
case SQLITE_DELETE:
self = .delete
default:
fatalError("unhandled operation code: \(rawValue)")
}
}
}
public var handle: OpaquePointer { return _handle! }
fileprivate var _handle: OpaquePointer? = nil
/// Initializes a new SQLite connection.
///
/// - Parameters:
///
/// - location: The location of the database. Creates a new database if it
/// doesnโt already exist (unless in read-only mode).
///
/// Default: `.inMemory`.
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Returns: A new database connection.
public init(_ location: Location = .inMemory, readonly: Bool = false) throws {
let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE
try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil))
queue.setSpecific(key: Connection.queueKey, value: queueContext)
}
/// Initializes a new connection to a database.
///
/// - Parameters:
///
/// - filename: The location of the database. Creates a new database if
/// it doesnโt already exist (unless in read-only mode).
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Throws: `Result.Error` iff a connection cannot be established.
///
/// - Returns: A new database connection.
public convenience init(_ filename: String, readonly: Bool = false) throws {
try self.init(.uri(filename), readonly: readonly)
}
deinit {
sqlite3_close(handle)
}
// MARK: -
/// Whether or not the database was opened in a read-only state.
public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 }
/// The last rowid inserted into the database via this connection.
public var lastInsertRowid: Int64 {
return sqlite3_last_insert_rowid(handle)
}
/// The last number of changes (inserts, updates, or deletes) made to the
/// database via this connection.
public var changes: Int {
return Int(sqlite3_changes(handle))
}
/// The total number of changes (inserts, updates, or deletes) made to the
/// database via this connection.
public var totalChanges: Int {
return Int(sqlite3_total_changes(handle))
}
// MARK: - Execute
/// Executes a batch of SQL statements.
///
/// - Parameter SQL: A batch of zero or more semicolon-separated SQL
/// statements.
///
/// - Throws: `Result.Error` if query execution fails.
public func execute(_ SQL: String) throws {
_ = try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) }
}
// MARK: - Prepare
/// Prepares a single SQL statement (with optional parameter bindings).
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: A prepared statement.
public func prepare(_ statement: String, _ bindings: Binding?...) throws -> Statement {
if !bindings.isEmpty { return try prepare(statement, bindings) }
return try Statement(self, statement)
}
/// Prepares a single SQL statement and binds parameters to it.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: A prepared statement.
public func prepare(_ statement: String, _ bindings: [Binding?]) throws -> Statement {
return try prepare(statement).bind(bindings)
}
/// Prepares a single SQL statement and binds parameters to it.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Returns: A prepared statement.
public func prepare(_ statement: String, _ bindings: [String: Binding?]) throws -> Statement {
return try prepare(statement).bind(bindings)
}
// MARK: - Run
/// Runs a single SQL statement (with optional parameter bindings).
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
@discardableResult public func run(_ statement: String, _ bindings: Binding?...) throws -> Statement {
return try run(statement, bindings)
}
/// Prepares, binds, and runs a single SQL statement.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
@discardableResult public func run(_ statement: String, _ bindings: [Binding?]) throws -> Statement {
return try prepare(statement).run(bindings)
}
/// Prepares, binds, and runs a single SQL statement.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
@discardableResult public func run(_ statement: String, _ bindings: [String: Binding?]) throws -> Statement {
return try prepare(statement).run(bindings)
}
// MARK: - Scalar
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
public func scalar(_ statement: String, _ bindings: Binding?...) throws -> Binding? {
return try scalar(statement, bindings)
}
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
public func scalar(_ statement: String, _ bindings: [Binding?]) throws -> Binding? {
return try prepare(statement).scalar(bindings)
}
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
public func scalar(_ statement: String, _ bindings: [String: Binding?]) throws -> Binding? {
return try prepare(statement).scalar(bindings)
}
// MARK: - Transactions
/// The mode in which a transaction acquires a lock.
public enum TransactionMode : String {
/// Defers locking the database till the first read/write executes.
case deferred = "DEFERRED"
/// Immediately acquires a reserved lock on the database.
case immediate = "IMMEDIATE"
/// Immediately acquires an exclusive lock on all databases.
case exclusive = "EXCLUSIVE"
}
// TODO: Consider not requiring a throw to roll back?
/// Runs a transaction with the given mode.
///
/// - Note: Transactions cannot be nested. To nest transactions, see
/// `savepoint()`, instead.
///
/// - Parameters:
///
/// - mode: The mode in which a transaction acquires a lock.
///
/// Default: `.deferred`
///
/// - block: A closure to run SQL statements within the transaction.
/// The transaction will be committed when the block returns. The block
/// must throw to roll the transaction back.
///
/// - Throws: `Result.Error`, and rethrows.
public func transaction(_ mode: TransactionMode = .deferred, block: @escaping () throws -> Void) throws {
try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION")
}
// TODO: Consider not requiring a throw to roll back?
// TODO: Consider removing ability to set a name?
/// Runs a transaction with the given savepoint name (if omitted, it will
/// generate a UUID).
///
/// - SeeAlso: `transaction()`.
///
/// - Parameters:
///
/// - savepointName: A unique identifier for the savepoint (optional).
///
/// - block: A closure to run SQL statements within the transaction.
/// The savepoint will be released (committed) when the block returns.
/// The block must throw to roll the savepoint back.
///
/// - Throws: `SQLite.Result.Error`, and rethrows.
public func savepoint(_ name: String = UUID().uuidString, block: @escaping () throws -> Void) throws {
let name = name.quote("'")
let savepoint = "SAVEPOINT \(name)"
try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)")
}
fileprivate func transaction(_ begin: String, _ block: @escaping () throws -> Void, _ commit: String, or rollback: String) throws {
return try sync {
try self.run(begin)
do {
try block()
} catch {
try self.run(rollback)
throw error
}
try self.run(commit)
}
}
/// Interrupts any long-running queries.
public func interrupt() {
sqlite3_interrupt(handle)
}
// MARK: - Handlers
/// The number of seconds a connection will attempt to retry a statement
/// after encountering a busy signal (lock).
public var busyTimeout: Double = 0 {
didSet {
sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000))
}
}
/// Sets a handler to call after encountering a busy signal (lock).
///
/// - Parameter callback: This block is executed during a lock in which a
/// busy error would otherwise be returned. Itโs passed the number of
/// times itโs been called for this lock. If it returns `true`, it will
/// try again. If it returns `false`, no further attempts will be made.
public func busyHandler(_ callback: ((_ tries: Int) -> Bool)?) {
guard let callback = callback else {
sqlite3_busy_handler(handle, nil, nil)
busyHandler = nil
return
}
let box: BusyHandler = { callback(Int($0)) ? 1 : 0 }
sqlite3_busy_handler(handle, { callback, tries in
unsafeBitCast(callback, to: BusyHandler.self)(tries)
}, unsafeBitCast(box, to: UnsafeMutableRawPointer.self))
busyHandler = box
}
fileprivate typealias BusyHandler = @convention(block) (Int32) -> Int32
fileprivate var busyHandler: BusyHandler?
/// Sets a handler to call when a statement is executed with the compiled
/// SQL.
///
/// - Parameter callback: This block is invoked when a statement is executed
/// with the compiled SQL as its argument.
///
/// db.trace { SQL in print(SQL) }
public func trace(_ callback: ((String) -> Void)?) {
#if SQLITE_SWIFT_SQLCIPHER
trace_v1(callback)
#else
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
trace_v2(callback)
} else {
trace_v1(callback)
}
#endif
}
fileprivate func trace_v1(_ callback: ((String) -> Void)?) {
guard let callback = callback else {
sqlite3_trace(handle, nil /* xCallback */, nil /* pCtx */)
trace = nil
return
}
let box: Trace = { (pointer: UnsafeRawPointer) in
callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self)))
}
sqlite3_trace(handle,
{
(C: UnsafeMutableRawPointer?, SQL: UnsafePointer<Int8>?) in
if let C = C, let SQL = SQL {
unsafeBitCast(C, to: Trace.self)(SQL)
}
},
unsafeBitCast(box, to: UnsafeMutableRawPointer.self)
)
trace = box
}
fileprivate typealias Trace = @convention(block) (UnsafeRawPointer) -> Void
fileprivate var trace: Trace?
/// Registers a callback to be invoked whenever a row is inserted, updated,
/// or deleted in a rowid table.
///
/// - Parameter callback: A callback invoked with the `Operation` (one of
/// `.Insert`, `.Update`, or `.Delete`), database name, table name, and
/// rowid.
public func updateHook(_ callback: ((_ operation: Operation, _ db: String, _ table: String, _ rowid: Int64) -> Void)?) {
guard let callback = callback else {
sqlite3_update_hook(handle, nil, nil)
updateHook = nil
return
}
let box: UpdateHook = {
callback(
Operation(rawValue: $0),
String(cString: $1),
String(cString: $2),
$3
)
}
sqlite3_update_hook(handle, { callback, operation, db, table, rowid in
unsafeBitCast(callback, to: UpdateHook.self)(operation, db!, table!, rowid)
}, unsafeBitCast(box, to: UnsafeMutableRawPointer.self))
updateHook = box
}
fileprivate typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void
fileprivate var updateHook: UpdateHook?
/// Registers a callback to be invoked whenever a transaction is committed.
///
/// - Parameter callback: A callback invoked whenever a transaction is
/// committed. If this callback throws, the transaction will be rolled
/// back.
public func commitHook(_ callback: (() throws -> Void)?) {
guard let callback = callback else {
sqlite3_commit_hook(handle, nil, nil)
commitHook = nil
return
}
let box: CommitHook = {
do {
try callback()
} catch {
return 1
}
return 0
}
sqlite3_commit_hook(handle, { callback in
unsafeBitCast(callback, to: CommitHook.self)()
}, unsafeBitCast(box, to: UnsafeMutableRawPointer.self))
commitHook = box
}
fileprivate typealias CommitHook = @convention(block) () -> Int32
fileprivate var commitHook: CommitHook?
/// Registers a callback to be invoked whenever a transaction rolls back.
///
/// - Parameter callback: A callback invoked when a transaction is rolled
/// back.
public func rollbackHook(_ callback: (() -> Void)?) {
guard let callback = callback else {
sqlite3_rollback_hook(handle, nil, nil)
rollbackHook = nil
return
}
let box: RollbackHook = { callback() }
sqlite3_rollback_hook(handle, { callback in
unsafeBitCast(callback, to: RollbackHook.self)()
}, unsafeBitCast(box, to: UnsafeMutableRawPointer.self))
rollbackHook = box
}
fileprivate typealias RollbackHook = @convention(block) () -> Void
fileprivate var rollbackHook: RollbackHook?
/// Creates or redefines a custom SQL function.
///
/// - Parameters:
///
/// - function: The name of the function to create or redefine.
///
/// - argumentCount: The number of arguments that the function takes. If
/// `nil`, the function may take any number of arguments.
///
/// Default: `nil`
///
/// - deterministic: Whether or not the function is deterministic (_i.e._
/// the function always returns the same result for a given input).
///
/// Default: `false`
///
/// - block: A block of code to run when the function is called. The block
/// is called with an array of raw SQL values mapped to the functionโs
/// parameters and should return a raw SQL value (or nil).
public func createFunction(_ function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: @escaping (_ args: [Binding?]) -> Binding?) {
let argc = argumentCount.map { Int($0) } ?? -1
let box: Function = { context, argc, argv in
let arguments: [Binding?] = (0..<Int(argc)).map { idx in
let value = argv![idx]
switch sqlite3_value_type(value) {
case SQLITE_BLOB:
return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value)))
case SQLITE_FLOAT:
return sqlite3_value_double(value)
case SQLITE_INTEGER:
return sqlite3_value_int64(value)
case SQLITE_NULL:
return nil
case SQLITE_TEXT:
return String(cString: UnsafePointer(sqlite3_value_text(value)))
case let type:
fatalError("unsupported value type: \(type)")
}
}
let result = block(arguments)
if let result = result as? Blob {
sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil)
} else if let result = result as? Double {
sqlite3_result_double(context, result)
} else if let result = result as? Int64 {
sqlite3_result_int64(context, result)
} else if let result = result as? String {
sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT)
} else if result == nil {
sqlite3_result_null(context)
} else {
fatalError("unsupported result type: \(String(describing: result))")
}
}
var flags = SQLITE_UTF8
if deterministic {
flags |= SQLITE_DETERMINISTIC
}
sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, to: UnsafeMutableRawPointer.self), { context, argc, value in
let function = unsafeBitCast(sqlite3_user_data(context), to: Function.self)
function(context, argc, value)
}, nil, nil, nil)
if functions[function] == nil { self.functions[function] = [:] }
functions[function]?[argc] = box
}
fileprivate typealias Function = @convention(block) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void
fileprivate var functions = [String: [Int: Function]]()
/// Defines a new collating sequence.
///
/// - Parameters:
///
/// - collation: The name of the collation added.
///
/// - block: A collation function that takes two strings and returns the
/// comparison result.
public func createCollation(_ collation: String, _ block: @escaping (_ lhs: String, _ rhs: String) -> ComparisonResult) throws {
let box: Collation = { (lhs: UnsafeRawPointer, rhs: UnsafeRawPointer) in
let lstr = String(cString: lhs.assumingMemoryBound(to: UInt8.self))
let rstr = String(cString: rhs.assumingMemoryBound(to: UInt8.self))
return Int32(block(lstr, rstr).rawValue)
}
try check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8,
unsafeBitCast(box, to: UnsafeMutableRawPointer.self),
{ (callback: UnsafeMutableRawPointer?, _, lhs: UnsafeRawPointer?, _, rhs: UnsafeRawPointer?) in /* xCompare */
if let lhs = lhs, let rhs = rhs {
return unsafeBitCast(callback, to: Collation.self)(lhs, rhs)
} else {
fatalError("sqlite3_create_collation_v2 callback called with NULL pointer")
}
}, nil /* xDestroy */))
collations[collation] = box
}
fileprivate typealias Collation = @convention(block) (UnsafeRawPointer, UnsafeRawPointer) -> Int32
fileprivate var collations = [String: Collation]()
// MARK: - Error Handling
func sync<T>(_ block: @escaping () throws -> T) rethrows -> T {
var success: T?
var failure: Error?
let box: () -> Void = {
do {
success = try block()
} catch {
failure = error
}
}
if DispatchQueue.getSpecific(key: Connection.queueKey) == queueContext {
box()
} else {
queue.sync(execute: box) // FIXME: rdar://problem/21389236
}
if let failure = failure {
try { () -> Void in throw failure }()
}
return success!
}
@discardableResult func check(_ resultCode: Int32, statement: Statement? = nil) throws -> Int32 {
guard let error = Result(errorCode: resultCode, connection: self, statement: statement) else {
return resultCode
}
throw error
}
fileprivate var queue = DispatchQueue(label: "SQLite.Database", attributes: [])
fileprivate static let queueKey = DispatchSpecificKey<Int>()
fileprivate lazy var queueContext: Int = unsafeBitCast(self, to: Int.self)
}
extension Connection : CustomStringConvertible {
public var description: String {
return String(cString: sqlite3_db_filename(handle, nil))
}
}
extension Connection.Location : CustomStringConvertible {
public var description: String {
switch self {
case .inMemory:
return ":memory:"
case .temporary:
return ""
case .uri(let URI):
return URI
}
}
}
public enum Result : Error {
fileprivate static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE]
case error(message: String, code: Int32, statement: Statement?)
init?(errorCode: Int32, connection: Connection, statement: Statement? = nil) {
guard !Result.successCodes.contains(errorCode) else { return nil }
let message = String(cString: sqlite3_errmsg(connection.handle))
self = .error(message: message, code: errorCode, statement: statement)
}
}
extension Result : CustomStringConvertible {
public var description: String {
switch self {
case let .error(message, errorCode, statement):
if let statement = statement {
return "\(message) (\(statement)) (code: \(errorCode))"
} else {
return "\(message) (code: \(errorCode))"
}
}
}
}
#if !SQLITE_SWIFT_SQLCIPHER
@available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *)
extension Connection {
fileprivate func trace_v2(_ callback: ((String) -> Void)?) {
guard let callback = callback else {
// If the X callback is NULL or if the M mask is zero, then tracing is disabled.
sqlite3_trace_v2(handle, 0 /* mask */, nil /* xCallback */, nil /* pCtx */)
trace = nil
return
}
let box: Trace = { (pointer: UnsafeRawPointer) in
callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self)))
}
sqlite3_trace_v2(handle,
UInt32(SQLITE_TRACE_STMT) /* mask */,
{
// A trace callback is invoked with four arguments: callback(T,C,P,X).
// The T argument is one of the SQLITE_TRACE constants to indicate why the
// callback was invoked. The C argument is a copy of the context pointer.
// The P and X arguments are pointers whose meanings depend on T.
(T: UInt32, C: UnsafeMutableRawPointer?, P: UnsafeMutableRawPointer?, X: UnsafeMutableRawPointer?) in
if let P = P,
let expandedSQL = sqlite3_expanded_sql(OpaquePointer(P)) {
unsafeBitCast(C, to: Trace.self)(expandedSQL)
sqlite3_free(expandedSQL)
}
return Int32(0) // currently ignored
},
unsafeBitCast(box, to: UnsafeMutableRawPointer.self) /* pCtx */
)
trace = box
}
}
#endif
|
98db9a73e8b8dd40ba8f4862a4233859
| 35.242063 | 162 | 0.594547 | false | false | false | false |
jcwcheng/aeire-ios
|
refs/heads/master
|
SmartDoorBell/BufferViewController.swift
|
mit
|
1
|
//
// BufferViewController.swift
// SmartDoorBell
//
// Created by Archerwind on 4/17/17.
// Copyright ยฉ 2017 Archerwind. All rights reserved.
//
import UIKit
import RealmSwift
class BufferViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var CounterLabel: UILabel!
@IBOutlet weak var displayLabel: UILabel!
@IBOutlet weak var configButton: UIButton!
@IBOutlet weak var clearButton: UIButton!
@IBAction func clearAction( _ sender: Any ) {
let realm = try! Realm()
let count = realm.objects( CounterRealm.self )
try! realm.write {
realm.create( CounterRealm.self, value: ["id": (count.first?.id)!, "counter": 0], update: true )
}
self.CounterLabel.text = "0"
}
func readCounterValue() {
let realm = try! Realm()
let counter = realm.objects( CounterRealm.self )
if counter.count == 0 {
let count = CounterRealm()
count.counter = 0
try! realm.write {
realm.add( count )
}
self.CounterLabel.text = "0"
}
else {
self.CounterLabel.text = String( format: "%d", (counter.first?.counter)! )
}
}
func initializer() {
self.titleLabel.kern( 2.0 )
self.subtitleLabel.kern( 1.5 )
self.displayLabel.kern( 1.5 )
self.configButton.kern( 2.0 )
self.clearButton.kern( 2.0 )
self.CounterLabel.kern( 4.0 )
}
override func viewDidLoad() {
super.viewDidLoad()
self.initializer()
let countNotification = Notification.Name( "count" )
NotificationCenter.default.addObserver( self, selector: #selector( self.readCounterValue ), name: countNotification, object: nil )
}
override func viewWillAppear( _ animated: Bool ) {
self.readCounterValue()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
b0139267c3d6ff0a772108ad6daa07d2
| 26.797297 | 136 | 0.626641 | false | false | false | false |
inderdhir/QuickTimer
|
refs/heads/master
|
QuickTimer/EventMonitor.swift
|
mit
|
1
|
//
// EventMonitor.swift
// QuickTimer
//
// Created by Inder Dhir on 5/30/17.
// Copyright ยฉ 2017 Inder Dhir. All rights reserved.
//
import Foundation
import Cocoa
open class EventMonitor {
fileprivate var monitor: AnyObject?
fileprivate let mask: NSEvent.EventTypeMask
fileprivate let handler: (NSEvent?) -> Void
public init(mask: NSEvent.EventTypeMask, handler: @escaping (NSEvent?) -> Void) {
self.mask = mask
self.handler = handler
}
deinit { stop() }
open func start() {
monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler) as AnyObject?
}
open func stop() {
if let monitor = monitor {
NSEvent.removeMonitor(monitor)
}
monitor = nil
}
}
|
7b900b9d53300704f9354615fb824cd6
| 21.911765 | 99 | 0.636714 | false | false | false | false |
Matzo/Kamishibai
|
refs/heads/master
|
Kamishibai/Classes/Kamishibai.swift
|
mit
|
1
|
//
// Kamishibai.swift
// Hello
//
// Created by Keisuke Matsuo on 2017/08/12.
//
//
import Foundation
public protocol KamishibaiSceneIdentifierType {
var intValue: Int { get }
// static var count: Int { get }
}
public extension KamishibaiSceneIdentifierType where Self: RawRepresentable, Self.RawValue == Int {
var intValue: Int {
return rawValue
}
}
public protocol KamishibaiCustomViewAnimation: class {
func show(animated: Bool, fulfill: @escaping () -> Void)
func hide(animated: Bool, fulfill: @escaping () -> Void)
}
public func == (l: KamishibaiSceneIdentifierType?, r: KamishibaiSceneIdentifierType?) -> Bool {
guard let l = l, let r = r else { return false }
return l.intValue == r.intValue
}
public class Kamishibai {
// MARK: Properties
public weak var currentViewController: UIViewController?
public var userInfo = [AnyHashable: Any]()
public weak var currentTodo: KamishibaiScene?
public var scenes = [KamishibaiScene]()
public var completion: (() -> Void)?
public let transition = KamishibaiTransitioning()
public var focus = KamishibaiFocusViewController.create()
// MARK: Initialization
public init(initialViewController: UIViewController) {
currentViewController = initialViewController
focus.kamishibai = self
}
// MARK: Private Methods
func nextTodo() -> KamishibaiScene? {
guard let current = currentTodo else { return nil }
guard let startIndex = scenes.index(where: { $0 == current }) else { return nil }
guard scenes.count > startIndex + 1 else { return nil }
for i in (startIndex + 1)..<scenes.count {
if scenes[i].isFinished {
continue
}
return scenes[i]
}
return nil
}
// MARK: Public Methods
/**
sceneใ้ๅงใใ
*/
public func startStory() {
guard let scene = scenes.first else {
finish()
return
}
invoke(scene)
}
/**
scenes ใฎไธญใซใใ sceneItentifier ใไธ่ดใใ scene ใ็ตไบใใใ
ใใฎๅพใ็พๅจๅฎ่กไธญใฎ scene ใงใใใฐใๆฌกใฎใพใ ็ตไบใใฆใใชใ scene ใๅฎ่กใใ
*/
public func fulfill(identifier: KamishibaiSceneIdentifierType) {
guard self.currentTodo?.identifier == identifier else { return }
}
/**
ๆธกใใใ scene ใ็ตไบใใใ
ใใฎๅพใ็พๅจๅฎ่กไธญใฎ scene ใงใใใฐใๆฌกใฎใพใ ็ตไบใใฆใใชใ scene ใๅฎ่กใใ
*/
public func fulfill(scene: KamishibaiScene) {
if scene.isFinished { return }
// scene ใ็ตไบใใใ
scene.isFinished = true
// ็พๅจใฎ scene ใชใๆฌกใธ
if let current = currentTodo, current == scene {
self.next()
}
}
/**
็พๅจๅฎ่กไธญใฎ scene ใ็ตไบใใใ
ใใฎๅพใๆฌกใฎใพใ ็ตไบใใฆใใชใ scene ใๅฎ่กใใ
*/
public func fulfill() {
}
/**
ๅ
จใฆใฎsceneใๅฎไบใใ้ใซๅผใฐใใพใ
*/
public func finish() {
completion?()
}
public func skip(identifier: KamishibaiSceneIdentifierType) {
guard self.currentTodo?.identifier == identifier else { return }
}
/**
็ตไบๅฆ็ใๅผใณๅบใใพใ
*/
public func skipAll() {
completion?()
}
/**
Go back to previous ToDo
*/
public func back() {
}
/**
Go to next ToDo
*/
public func next() {
// ๅ
จ้จ็ตไบใใฆใใใฐ finish()
if scenes.filter({ !$0.isFinished }).count == 0 {
finish()
return
}
// ๆฌกใใใใฐ scene ใ้ธๆใใฆๅฎ่กใใ
if let scene = nextTodo() {
invoke(scene)
}
}
public func invoke(_ scene: KamishibaiScene) {
currentTodo = scene
if let transition = scene.transition, let vc = currentViewController {
focus.dismiss(animated: true) {
self.transition.transision(fromVC: vc, type: transition, animated: true) { [weak self] (nextVC) in
self?.currentViewController = nextVC
scene.sceneBlock(scene)
}
}
} else {
scene.sceneBlock(scene)
}
}
public func append(_ scene: KamishibaiScene) {
if scenes.contains(where: { $0.identifier == scene.identifier }) {
assertionFailure("Can't use same Identifier")
}
scene.kamishibai = self
self.scenes.append(scene)
}
/**
*/
public func insertNext(_ scene: KamishibaiScene) {
if scenes.contains(where: { $0.identifier == scene.identifier }) {
assertionFailure("Can't use same Identifier")
}
scene.kamishibai = self
if let current = currentTodo, let index = scenes.index(where: { $0 == current }), scenes.count > index + 1 {
self.scenes.insert(scene, at: index + 1)
} else {
self.scenes.append(scene)
}
}
public func clean() {
completion = nil
userInfo.removeAll()
currentTodo = nil
scenes.removeAll()
focus.dismiss(animated: true, completion: { [weak self] in
self?.focus.clean()
self?.focus = KamishibaiFocusViewController.create()
})
}
}
|
6160da2d36ebc5d9e1a07b0483388c9c
| 24.653266 | 116 | 0.582958 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKit/Permission/MicrophonePrompting.swift
|
lgpl-3.0
|
1
|
// Copyright ยฉ Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Localization
import PlatformKit
import ToolKit
public protocol MicrophonePrompting: AnyObject {
var permissionsRequestor: PermissionsRequestor { get set }
var microphonePromptingDelegate: MicrophonePromptingDelegate? { get set }
func checkMicrophonePermissions()
func willUseMicrophone()
}
extension MicrophonePrompting {
public func checkMicrophonePermissions() {
permissionsRequestor.requestPermissions([.microphone]) { [weak self] in
guard let self = self else { return }
self.microphonePromptingDelegate?.onMicrophonePromptingComplete()
}
}
public func willUseMicrophone() {
guard PermissionsRequestor.shouldDisplayMicrophonePermissionsRequest() else {
microphonePromptingDelegate?.onMicrophonePromptingComplete()
return
}
microphonePromptingDelegate?.promptToAcceptMicrophonePermissions(confirmHandler: checkMicrophonePermissions)
}
}
public protocol MicrophonePromptingDelegate: AnyObject {
var analyticsRecorder: AnalyticsEventRecorderAPI { get }
func onMicrophonePromptingComplete()
func promptToAcceptMicrophonePermissions(confirmHandler: @escaping (() -> Void))
}
extension MicrophonePromptingDelegate {
public func promptToAcceptMicrophonePermissions(confirmHandler: @escaping (() -> Void)) {
let okay = AlertAction(style: .confirm(LocalizationConstants.okString))
let notNow = AlertAction(style: .default(LocalizationConstants.KYC.notNow))
let model = AlertModel(
headline: LocalizationConstants.KYC.allowMicrophoneAccess,
body: LocalizationConstants.KYC.enableMicrophoneDescription,
actions: [okay, notNow]
)
let alert = AlertView.make(with: model) { output in
switch output.style {
case .confirm,
.default:
self.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreMicApprove)
confirmHandler()
case .dismiss:
self.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreMicDecline)
}
}
alert.show()
}
}
|
39ec10e29e7f5ca394bac84c14957781
| 36.032258 | 116 | 0.706446 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox
|
refs/heads/master
|
nRF Toolbox/Profiles/DeviceFirmwareUpdate/ViewConrollers/DFUUpdate/DFUUpdateTabBarViewController.swift
|
bsd-3-clause
|
1
|
/*
* Copyright (c) 2020, Nordic Semiconductor
* 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 NordicDFU
protocol DFUUpdateRouter: AnyObject {
func showLogs()
func done()
}
class DFUUpdateTabBarViewController: UITabBarController {
let logger = DFULogObserver()
private let router: DFURouterType
private let updateVC: DFUUpdateViewController
private let loggerVC: LoggerTableViewController
init(router: DFURouterType, firmware: DFUFirmware, peripheral: Peripheral) {
self.router = router
self.updateVC = DFUUpdateViewController(firmware: firmware, peripheral: peripheral, logger: logger)
self.loggerVC = LoggerTableViewController(observer: logger)
super.init(nibName: nil, bundle: nil)
updateVC.router = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tabBar.tintColor = .nordicBlue
navigationItem.title = "Update"
setViewControllers([updateVC, loggerVC], animated: true)
delegate = self
selectedIndex = 0
}
}
extension DFUUpdateTabBarViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
navigationItem.title = viewController.navigationItem.title
}
}
extension DFUUpdateTabBarViewController: DFUUpdateRouter {
func showLogs() {
selectedIndex = 1
}
func done() {
router.initialState()
}
}
|
6abbc9d7459daabd7a984dce65ca2c9b
| 34.168539 | 111 | 0.729393 | false | false | false | false |
micchyboy1023/Today
|
refs/heads/dev
|
Today Watch App/Today Watch Extension/ScoreInterfaceController.swift
|
mit
|
1
|
//
// ScoreInterfaceController.swift
// TodayWatch Extension
//
// Created by UetaMasamichi on 2016/01/20.
// Copyright ยฉ 2016ๅนด Masamichi Ueta. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
import TodayWatchKit
final class ScoreInterfaceController: WKInterfaceController {
@IBOutlet var scoreIcon: WKInterfaceImage!
@IBOutlet var cautionLabel: WKInterfaceLabel!
fileprivate var session: WCSession!
fileprivate var todayScore: Int = 8 {
didSet {
if todayScore == oldValue {
return
}
scoreIcon.setImageNamed(Today.type(todayScore).iconName(.hundred))
}
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if WCSession.isSupported() {
session = WCSession.default()
session.delegate = self
session.activate()
}
}
override func willActivate() {
super.willActivate()
cautionLabel.setHidden(true)
var watchData = WatchData()
if let updatedAt = watchData.updatedAt, Calendar.current.isDate(updatedAt, inSameDayAs: Date()) {
todayScore = watchData.score
}
if session.isReachable {
sendMessageToGetWatchData()
}
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func addToday() {
let watchData = WatchData()
let today = Date()
guard let updatedAt = watchData.updatedAt else {
presentController(withName: "AddTodayInterfaceController", context: self)
return
}
if !Calendar.current.isDate(updatedAt, inSameDayAs: today) {
presentController(withName: "AddTodayInterfaceController", context: self)
} else {
cautionLabel.setHidden(false)
animate(withDuration: 0.5, animations: {
self.cautionLabel.setAlpha(1.0)
Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(self.hideCautionLabel), userInfo: nil, repeats: false)
})
}
}
func hideCautionLabel() {
animate(withDuration: 0.5, animations: { [unowned self] in
self.cautionLabel.setAlpha(0.0)
self.cautionLabel.setHidden(true)
})
}
fileprivate func sendMessageToGetWatchData() {
session.sendMessage([watchConnectivityActionTypeKey: WatchConnectivityActionType.getWatchData.rawValue],
replyHandler: { content in
var watchData = WatchData()
let score = content[WatchConnectivityContentType.todayScore.rawValue] as? Int
let currentStreak = content[WatchConnectivityContentType.currentStreak.rawValue] as? Int
switch (score, currentStreak) {
case (let .some(score), let .some(currentStreak)):
watchData.score = score
watchData.currentStreak = currentStreak
watchData.updatedAt = Date()
case (let .some(score), nil):
watchData.score = score
watchData.currentStreak = 0
watchData.updatedAt = nil
case (nil, let .some(currentStreak)):
watchData.score = 8
watchData.currentStreak = currentStreak
watchData.updatedAt = nil
case (nil, nil):
watchData.score = 8
watchData.currentStreak = 0
watchData.updatedAt = nil
}
self.todayScore = watchData.score
},
errorHandler: nil)
}
}
//MARK: - WCSessionDelegate
extension ScoreInterfaceController: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
func sessionReachabilityDidChange(_ session: WCSession) {
if session.isReachable {
sendMessageToGetWatchData()
}
}
}
//MARK: - AddTodayInterfaceControllerDelegate
extension ScoreInterfaceController: AddTodayInterfaceControllerDelegate {
func todayDidAdd(_ score: Int) {
todayScore = score
}
}
|
da83882c4bcac5f16bb057573a2dee3c
| 34.148936 | 144 | 0.530872 | false | false | false | false |
XiongJoJo/OFO
|
refs/heads/master
|
App/OFO/OFO/PasscodeController.swift
|
apache-2.0
|
1
|
//
// PasscodeController.swift
// OFO
//
// Created by JoJo on 2017/6/8.
// Copyright ยฉ 2017ๅนด JoJo. All rights reserved.
//
import UIKit
import SwiftyTimer
import SwiftySound
class PasscodeController: UIViewController {
@IBOutlet weak var label1st: MyPreviewLabel!
@IBOutlet weak var label2nd: MyPreviewLabel!
@IBOutlet weak var label3rd: MyPreviewLabel!
@IBOutlet weak var label4th: MyPreviewLabel!
@IBOutlet weak var showInfo: UILabel!
//[8,4,5,6]
var passArray : [String] = []
var bikeID = ""
let defaults = UserDefaults.standard
@IBOutlet weak var countDownLabel: UILabel!
// var remindSeconds = 121
var remindSeconds = 21
var isTorchOn = false
var isVoiceOn = true
@IBOutlet weak var voiceBtn: UIButton!
@IBAction func voiceBtnTap(_ sender: UIButton) {
if isVoiceOn {
voiceBtn.setImage(#imageLiteral(resourceName: "voiceclose"), for: .normal)
} else {
voiceBtn.setImage(#imageLiteral(resourceName: "voiceopen"), for: .normal)
}
isVoiceOn = !isVoiceOn
}
@IBAction func torchBtnTap(_ sender: UIButton) {
turnTorch()
if isTorchOn {
torchBtn.setImage(#imageLiteral(resourceName: "lightopen"), for: .normal)
defaults.set(true, forKey: "isVoiceOn")
} else {
torchBtn.setImage(#imageLiteral(resourceName: "lightclose"), for: .normal)
defaults.set(false, forKey: "isVoiceOn")
}
isTorchOn = !isTorchOn
}
@IBOutlet weak var torchBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "่ฝฆ่พ่งฃ้"
self.navigationItem.hidesBackButton = true //้่่ฟๅๆ้ฎ
Sound.play(file: "ๆจ็่งฃ้็ ไธบ_D.m4a")
DispatchQueue.main.asyncAfter(deadline: .now()+1) {
Sound.play(file: "\(self.passArray[0])_D.m4a")
}
DispatchQueue.main.asyncAfter(deadline: .now()+2) {
Sound.play(file: "\(self.passArray[1])_D.m4a")
}
DispatchQueue.main.asyncAfter(deadline: .now()+3) {
Sound.play(file: "\(self.passArray[2])_D.m4a")
}
DispatchQueue.main.asyncAfter(deadline: .now()+4) {
Sound.play(file: "\(self.passArray[3])_D.m4a")
}
DispatchQueue.main.asyncAfter(deadline: .now()+5) {
Sound.play(file: "ไธ่ฝฆๅ_LH.m4a")
}
Timer.every(1) { (timer: Timer) in
self.remindSeconds -= 1
self.countDownLabel.text = self.remindSeconds.description + "็ง"
if self.remindSeconds == 0 {
timer.invalidate()
//ๆถ้ด็ปๆ่ทณ่ฝฌ่ฎกๆถ้กต้ข
self.performSegue(withIdentifier: "toTimePage", sender: self)
// Sound.play(file:"้ช่ก็ปๆ_LH.m4a")//่ฟ้ๆไปฌๆถ้ด็ฐๅฎ็ปๆไนๅๆญๆพ
}
}
voiceBtnStatus(voiceBtn: voiceBtn)
self.label1st.text = passArray[0]
self.label2nd.text = passArray[1]
self.label3rd.text = passArray[2]
self.label4th.text = passArray[3]
// let bikeID = passArray.joined(separator: "")//ๆฐ็ป่ฝฌๅญ็ฌฆไธฒ
showInfo.text = "่ฝฆ็ๅท" + bikeID + "็่งฃ้็ "
}
@IBAction func reportBtnTap(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
d0e35c2bb5af0b3b79345d30e76b43e8
| 26.910345 | 107 | 0.573264 | false | false | false | false |
niekang/WeiBo
|
refs/heads/master
|
WeiBo/Class/Utils/Extension/NSDate+Extension.swift
|
apache-2.0
|
1
|
//
// NSDate+Extension.swift
// WeiBo
//
// Created by ่ๅบท on 2017/6/23.
// Copyright ยฉ 2017ๅนด com.nk. All rights reserved.
//
import Foundation
/// ๆฅๆๆ ผๅผๅๅจ - ไธ่ฆ้ข็น็้ๆพๅๅๅปบ๏ผไผๅฝฑๅๆง่ฝ
private let dateFormatter = DateFormatter()
/// ๅฝๅๆฅๅๅฏน่ฑก
private let calendar = Calendar.current
extension Date {
/// ่ฎก็ฎไธๅฝๅ็ณป็ปๆถ้ดๅๅทฎ delta ็งๆฐ็ๆฅๆๅญ็ฌฆไธฒ
/// ๅจ Swift ไธญ๏ผๅฆๆ่ฆๅฎไน็ปๆไฝ็ `็ฑป`ๅฝๆฐ๏ผไฝฟ็จ static ไฟฎ้ฅฐ -> ้ๆๅฝๆฐ
static func dateString(delta: TimeInterval) -> String {
let date = Date(timeIntervalSinceNow: delta)
// ๆๅฎๆฅๆๆ ผๅผ
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: date)
}
/// ๅฐๆฐๆตชๆ ผๅผ็ๅญ็ฌฆไธฒ่ฝฌๆขๆๆฅๆ
///
/// - parameter string: Tue Sep 15 12:12:00 +0800 2015
///
/// - returns: ๆฅๆ
static func sinaDate(string: String) -> Date? {
// 1. ่ฎพ็ฝฎๆฅๆๆ ผๅผ
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
// 2. ่ฝฌๆขๅนถไธ่ฟๅๆฅๆ
return dateFormatter.date(from: string)
}
/**
ๅๅ(ไธๅ้ๅ
)
Xๅ้ๅ(ไธๅฐๆถๅ
)
Xๅฐๆถๅ(ๅฝๅคฉ)
ๆจๅคฉ HH:mm(ๆจๅคฉ)
MM-dd HH:mm(ไธๅนดๅ
)
yyyy-MM-dd HH:mm(ๆดๆฉๆ)
*/
var dateDescription: String {
// 1. ๅคๆญๆฅๆๆฏๅฆๆฏไปๅคฉ
if calendar.isDateInToday(self) {
let delta = -Int(self.timeIntervalSinceNow)
if delta < 60 {
return "ๅๅ"
}
if delta < 3600 {
return "\(delta / 60) ๅ้ๅ"
}
return "\(delta / 3600) ๅฐๆถๅ"
}
// 2. ๅ
ถไปๅคฉ
var fmt = " HH:mm"
if calendar.isDateInYesterday(self) {
fmt = "ๆจๅคฉ" + fmt
} else {
fmt = "MM-dd" + fmt
let year = calendar.component(.year, from: self)
let thisYear = calendar.component(.year, from: Date())
if year != thisYear {
fmt = "yyyy-" + fmt
}
}
// ่ฎพ็ฝฎๆฅๆๆ ผๅผๅญ็ฌฆไธฒ
dateFormatter.dateFormat = fmt
return dateFormatter.string(from: self)
}
}
|
da5360402ec7ffdd53d71f53ab97c060
| 22.538462 | 66 | 0.49113 | false | false | false | false |
mikelikespie/swiftled
|
refs/heads/master
|
src/main/swift/Fixtures/Controls/LightnessControl.swift
|
mit
|
1
|
//
// Created by Michael Lewis on 7/20/17.
//
import Foundation
import UIKit
import Views
import RxSwift
struct LightnessControl : Control {
let name = "Brightness"
let slider: VerticalSlider
let value = Variable<Float>(0)
let imageView = UIImageView(image: UIImage(named: "sun"))
init(slider: VerticalSlider) {
self.slider = slider
cell.addSubview(imageView)
cell.addSubview(slider)
}
let cell = UIView()
}
|
64e64cf3d4dd0a44593c21324d6fcb3a
| 17.423077 | 61 | 0.645094 | false | false | false | false |
darina/omim
|
refs/heads/master
|
iphone/Maps/Bookmarks/Categories/BMCView/BMCViewController.swift
|
apache-2.0
|
4
|
final class BMCViewController: MWMViewController {
private var viewModel: BMCDefaultViewModel! {
didSet {
viewModel.view = self
tableView.dataSource = self
}
}
private weak var coordinator: BookmarksCoordinator?
@IBOutlet private weak var tableView: UITableView! {
didSet {
let cells = [
BMCPermissionsCell.self,
BMCPermissionsPendingCell.self,
BMCCategoryCell.self,
BMCActionsCreateCell.self,
BMCNotificationsCell.self,
]
tableView.registerNibs(cells)
tableView.registerNibForHeaderFooterView(BMCCategoriesHeader.self)
}
}
@IBOutlet private var permissionsHeader: BMCPermissionsHeader! {
didSet {
permissionsHeader.delegate = self
}
}
@IBOutlet private var actionsHeader: UIView!
@IBOutlet private var notificationsHeader: BMCNotificationsHeader!
init(coordinator: BookmarksCoordinator?) {
super.init(nibName: nil, bundle: nil)
self.coordinator = coordinator
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel = BMCDefaultViewModel()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Disable all notifications in BM on appearance of this view.
// It allows to significantly improve performance in case of bookmarks
// modification. All notifications will be sent on controller's disappearance.
viewModel.setNotificationsEnabled(false)
viewModel.addToObserverList()
viewModel.convertAllKMLIfNeeded()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Allow to send all notifications in BM.
viewModel.setNotificationsEnabled(true)
viewModel.removeFromObserverList()
}
private func createNewCategory() {
alertController.presentCreateBookmarkCategoryAlert(withMaxCharacterNum: viewModel.maxCategoryNameLength,
minCharacterNum: viewModel.minCategoryNameLength)
{ [weak viewModel] (name: String!) -> Bool in
guard let model = viewModel else { return false }
if model.checkCategory(name: name) {
model.addCategory(name: name)
return true
}
return false
}
}
private func shareCategoryFile(at index: Int, anchor: UIView) {
viewModel.shareCategoryFile(at: index) {
switch $0 {
case let .success(url):
let shareController = ActivityViewController.share(for: url,
message: L("share_bookmarks_email_body"))
{ [weak self] _, _, _, _ in
self?.viewModel?.finishShareCategory()
}
shareController?.present(inParentViewController: self, anchorView: anchor)
case let .error(title, text):
MWMAlertViewController.activeAlert().presentInfoAlert(title, text: text)
}
}
}
private func shareCategory(category: BookmarkGroup, anchor: UIView) {
let storyboard = UIStoryboard.instance(.sharing)
let shareController = storyboard.instantiateInitialViewController() as! BookmarksSharingViewController
shareController.category = BookmarksManager.shared().category(withId: category.categoryId)
MapViewController.topViewController().navigationController?.pushViewController(shareController,
animated: true)
}
private func openCategorySettings(category: BookmarkGroup) {
let settingsController = CategorySettingsViewController(bookmarkGroup: BookmarksManager.shared().category(withId: category.categoryId))
settingsController.delegate = self
MapViewController.topViewController().navigationController?.pushViewController(settingsController,
animated: true)
}
private func openCategory(category: BookmarkGroup) {
let bmViewController = BookmarksListBuilder.build(markGroupId: category.categoryId,
bookmarksCoordinator: coordinator,
delegate: self)
MapViewController.topViewController().navigationController?.pushViewController(bmViewController,
animated: true)
}
private func setCategoryVisible(_ visible: Bool, at index: Int) {
let category = viewModel.category(at: index)
BookmarksManager.shared().setCategory(category.categoryId, isVisible: visible)
if let categoriesHeader = tableView.headerView(forSection: viewModel.sectionIndex(section: .categories)) as? BMCCategoriesHeader {
categoriesHeader.isShowAll = viewModel.areAllCategoriesHidden()
}
Statistics.logEvent(kStatBookmarkVisibilityChange, withParameters: [kStatFrom : kStatBookmarkList,
kStatAction : visible ? kStatShow : kStatHide])
}
private func editCategory(at index: Int, anchor: UIView) {
let category = viewModel.category(at: index)
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
if let ppc = actionSheet.popoverPresentationController {
ppc.sourceView = anchor
ppc.sourceRect = anchor.bounds
}
let settings = L("list_settings")
actionSheet.addAction(UIAlertAction(title: settings, style: .default, handler: { _ in
self.openCategorySettings(category: category)
Statistics.logEvent(kStatBookmarksListSettingsClick,
withParameters: [kStatOption : kStatListSettings])
}))
let showHide = L(category.isVisible ? "hide_from_map" : "zoom_to_country")
actionSheet.addAction(UIAlertAction(title: showHide, style: .default, handler: { _ in
self.setCategoryVisible(!category.isVisible, at: index)
let sectionIndex = self.viewModel.sectionIndex(section: .categories)
self.tableView.reloadRows(at: [IndexPath(row: index, section: sectionIndex)], with: .none)
Statistics.logEvent(kStatBookmarksListSettingsClick,
withParameters: [kStatOption : kStatMakeInvisibleOnMap])
}))
let exportFile = L("export_file")
actionSheet.addAction(UIAlertAction(title: exportFile, style: .default, handler: { _ in
self.shareCategoryFile(at: index, anchor: anchor)
Statistics.logEvent(kStatBookmarksListSettingsClick,
withParameters: [kStatOption : kStatSendAsFile])
}))
let share = L("sharing_options")
let shareAction = UIAlertAction(title: share, style: .default, handler: { _ in
self.shareCategory(category: category, anchor: anchor)
Statistics.logEvent(kStatBookmarksListSettingsClick,
withParameters: [kStatOption : kStatSharingOptions])
})
shareAction.isEnabled = BookmarksManager.shared().isCategoryNotEmpty(category.categoryId)
actionSheet.addAction(shareAction)
let delete = L("delete_list")
let deleteAction = UIAlertAction(title: delete, style: .destructive, handler: { [viewModel] _ in
viewModel!.deleteCategory(at: index)
Statistics.logEvent(kStatBookmarksListSettingsClick,
withParameters: [kStatOption : kStatDeleteGroup])
})
deleteAction.isEnabled = (viewModel.numberOfRows(section: .categories) > 1)
actionSheet.addAction(deleteAction)
let cancel = L("cancel")
actionSheet.addAction(UIAlertAction(title: cancel, style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
}
extension BMCViewController: BMCView {
func update(sections: [BMCSection]) {
if sections.isEmpty {
tableView.reloadData()
} else {
let indexes = IndexSet(sections.map { viewModel.sectionIndex(section: $0) })
tableView.update { tableView.reloadSections(indexes, with: .automatic) }
}
}
func insert(at indexPaths: [IndexPath]) {
tableView.insertRows(at: indexPaths, with: .automatic)
}
func delete(at indexPaths: [IndexPath]) {
tableView.deleteRows(at: indexPaths, with: .automatic)
}
func conversionFinished(success: Bool) {
MWMAlertViewController.activeAlert().closeAlert {
if !success {
MWMAlertViewController.activeAlert().presentBookmarkConversionErrorAlert()
}
}
}
}
extension BMCViewController: UITableViewDataSource {
func numberOfSections(in _: UITableView) -> Int {
return viewModel.numberOfSections()
}
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
switch viewModel.sectionType(section: section) {
case .permissions:
return permissionsHeader.isCollapsed ? 0 : viewModel.numberOfRows(section: section)
case .categories: fallthrough
case .actions: fallthrough
case .notifications: return viewModel.numberOfRows(section: section)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func dequeCell<Cell>(_ cell: Cell.Type) -> Cell where Cell: UITableViewCell {
return tableView.dequeueReusableCell(cell: cell, indexPath: indexPath)
}
switch viewModel.sectionType(section: indexPath.section) {
case .permissions:
let permission = viewModel.permission(at: indexPath.row)
if viewModel.isPendingPermission {
return dequeCell(BMCPermissionsPendingCell.self).config(permission: permission)
} else {
return dequeCell(BMCPermissionsCell.self).config(permission: permission, delegate: self)
}
case .categories:
return dequeCell(BMCCategoryCell.self).config(category: viewModel.category(at: indexPath.row),
delegate: self)
case .actions:
return dequeCell(BMCActionsCreateCell.self).config(model: viewModel.action(at: indexPath.row))
case .notifications:
return dequeCell(BMCNotificationsCell.self)
}
}
}
extension BMCViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if viewModel.sectionType(section: indexPath.section) != .categories {
return false
}
return viewModel.numberOfRows(section: .categories) > 1
}
func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
guard editingStyle == .delete,
viewModel.sectionType(section: indexPath.section) == .categories else {
assertionFailure()
return
}
viewModel.deleteCategory(at: indexPath.row)
}
func tableView(_: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch viewModel.sectionType(section: section) {
case .permissions: fallthrough
case .notifications: fallthrough
case .categories: return 48
case .actions: return 24
}
}
func tableView(_: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch viewModel.sectionType(section: section) {
case .permissions: return permissionsHeader
case .categories:
let categoriesHeader = tableView.dequeueReusableHeaderFooterView(BMCCategoriesHeader.self)
categoriesHeader.isShowAll = viewModel.areAllCategoriesHidden()
categoriesHeader.title = L("bookmarks_groups")
categoriesHeader.delegate = self
return categoriesHeader
case .actions: return actionsHeader
case .notifications: return notificationsHeader
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch viewModel.sectionType(section: indexPath.section) {
case .permissions:
return
case .categories:
openCategory(category: viewModel.category(at: indexPath.row))
case .actions:
switch viewModel.action(at: indexPath.row) {
case .create: createNewCategory()
}
default:
assertionFailure()
}
}
}
extension BMCViewController: BMCPermissionsCellDelegate {
func permissionAction(permission: BMCPermission, anchor: UIView) {
switch permission {
case .signup:
viewModel.pendingPermission(isPending: true)
signup(anchor: anchor, source: .bookmarksBackup, onComplete: { [weak self, viewModel] result in
if result == .succes {
viewModel!.grant(permission: .backup)
} else if result == .cancel {
viewModel?.pendingPermission(isPending: false)
} else if result == .error {
Statistics.logEvent(kStatBookmarksAuthRequestError)
viewModel?.pendingPermission(isPending: false)
MWMAlertViewController.activeAlert().presentAuthErrorAlert {
self?.permissionAction(permission: permission, anchor: anchor)
}
}
})
case .backup:
viewModel.grant(permission: permission)
case .restore:
viewModel.requestRestoring()
}
}
}
extension BMCViewController: BMCCategoryCellDelegate {
func cell(_ cell: BMCCategoryCell, didCheck visible: Bool) {
guard let indexPath = tableView.indexPath(for: cell) else {
assertionFailure()
return
}
setCategoryVisible(visible, at: indexPath.row)
}
func cell(_ cell: BMCCategoryCell, didPress moreButton: UIButton) {
guard let indexPath = tableView.indexPath(for: cell) else {
assertionFailure()
return
}
editCategory(at: indexPath.row, anchor: moreButton)
}
}
extension BMCViewController: BMCPermissionsHeaderDelegate {
func collapseAction(isCollapsed: Bool) {
permissionsHeader.isCollapsed = !isCollapsed
let sectionIndex = viewModel.sectionIndex(section: .permissions)
let rowsInSection = viewModel.numberOfRows(section: .permissions)
var rowIndexes = [IndexPath]()
for rowIndex in 0..<rowsInSection {
rowIndexes.append(IndexPath(row: rowIndex, section: sectionIndex))
}
if (permissionsHeader.isCollapsed) {
delete(at: rowIndexes)
} else {
insert(at: rowIndexes)
}
}
}
extension BMCViewController: BMCCategoriesHeaderDelegate {
func visibilityAction(_ categoriesHeader: BMCCategoriesHeader) {
viewModel.updateAllCategoriesVisibility(isShowAll: categoriesHeader.isShowAll)
categoriesHeader.isShowAll = viewModel.areAllCategoriesHidden()
tableView.reloadData()
}
}
extension BMCViewController: CategorySettingsViewControllerDelegate {
func categorySettingsController(_ viewController: CategorySettingsViewController,
didEndEditing categoryId: MWMMarkGroupID) {
navigationController?.popViewController(animated: true)
}
func categorySettingsController(_ viewController: CategorySettingsViewController,
didDelete categoryId: MWMMarkGroupID) {
navigationController?.popViewController(animated: true)
}
}
extension BMCViewController: BookmarksListDelegate {
func bookmarksListDidDeleteGroup() {
guard let parentVC = parent else { return }
navigationController?.popToViewController(parentVC, animated: true)
}
}
|
191c78dd0c57fd1eedea87550884ef9d
| 37.418953 | 139 | 0.69064 | false | false | false | false |
csnu17/My-Swift-learning
|
refs/heads/master
|
ComposingComplexInterfaces/Landmarks/Landmarks/Supporting Views/BadgeSymbol.swift
|
mit
|
2
|
/*
See LICENSE folder for this sampleโs licensing information.
Abstract:
A view that display a symbol in a badge.
*/
import SwiftUI
struct BadgeSymbol: View {
static let symbolColor = Color(red: 79.0 / 255, green: 79.0 / 255, blue: 191.0 / 255)
var body: some View {
GeometryReader { geometry in
Path { path in
let width = min(geometry.size.width, geometry.size.height)
let height = width * 0.75
let spacing = width * 0.030
let middle = width / 2
let topWidth = 0.226 * width
let topHeight = 0.488 * height
path.addLines([
CGPoint(x: middle, y: spacing),
CGPoint(x: middle - topWidth, y: topHeight - spacing),
CGPoint(x: middle, y: topHeight / 2 + spacing),
CGPoint(x: middle + topWidth, y: topHeight - spacing),
CGPoint(x: middle, y: spacing)
])
path.move(to: CGPoint(x: middle, y: topHeight / 2 + spacing * 3))
path.addLines([
CGPoint(x: middle - topWidth, y: topHeight + spacing),
CGPoint(x: spacing, y: height - spacing),
CGPoint(x: width - spacing, y: height - spacing),
CGPoint(x: middle + topWidth, y: topHeight + spacing),
CGPoint(x: middle, y: topHeight / 2 + spacing * 3)
])
}
.fill(Self.symbolColor)
}
}
}
#if DEBUG
struct BadgeSymbol_Previews: PreviewProvider {
static var previews: some View {
BadgeSymbol()
}
}
#endif
|
a7ac0fbe1f89280bcfd1d5a0feaa8d2d
| 32.862745 | 89 | 0.503185 | false | false | false | false |
sagardesai16/MystifyStrings
|
refs/heads/master
|
MystifyStrings/Classes/String-Class/Mystifier.swift
|
mit
|
1
|
//
// Mystifier.swift
// SecureString
//
// Created by Sagar Desai on 18/06/17.
// Copyright ยฉ 2017 Sagar Desai. All rights reserved.
//
import Foundation
class Mystifier: NSObject {
// MARK: - Variables
/// The salt used to Mystify and reveal the string.
private var salt: String = "MyAppMystifier"
// MARK: - Initialization
init(withSalt salt: [AnyObject]) {
self.salt = salt.description
}
// MARK: - Instance Methods
/**
This method mystifies the string passed in using the salt
that was used when the Mystifier was initialized.
- parameter string: the string to mystify
- returns: the mystified string in a byte array
*/
func bytesByMystifyingString(string: String) -> [UInt8] {
let text = [UInt8](string.utf8)
let cipher = [UInt8](self.salt.utf8)
let length = cipher.count
var encrypted = [UInt8]()
for t in text.enumerated() {
encrypted.append(t.element ^ cipher[t.offset % length])
}
#if DEVELOPMENT
print("Salt used: \(self.salt)\n")
print("// Original \"\(string)\"")
print("let key: [UInt8] = \(encrypted)\n")
#endif
return encrypted
}
/**
This method reveals the original string from the mystified
byte array passed in. The salt must be the same as the one
used to encrypt it in the first place.
- parameter key: the byte array to reveal
- returns: the original string
*/
func reveal(key: [UInt8]) -> String {
let cipher = [UInt8](self.salt.utf8)
let length = cipher.count
var decrypted = [UInt8]()
for k in key.enumerated() {
decrypted.append(k.element ^ cipher[k.offset % length])
}
return String(bytes: decrypted, encoding: .utf8)!
}
}
|
d360544bf758f7903d94064622df3cd7
| 24.075949 | 67 | 0.564361 | false | false | false | false |
Limon-O-O/Lego
|
refs/heads/master
|
Modules/Door/Door/Targets/Target_Door.swift
|
mit
|
1
|
//
// Target_Door.swift
// Door
//
// Created by Limon.F on 19/2/2017.
// Copyright ยฉ 2017 Limon.F. All rights reserved.
//
import UIKit
@objc(Target_Door)
class Target_Door: NSObject {}
// MARK: - Controllers
extension Target_Door {
func Action_WelcomeViewController(params: [String: Any]) -> UIViewController? {
let navigationController = Storyboard.door.navigationController(with: "DoorNavigationController") as? DoorNavigationController
navigationController?.innateParams = params
return navigationController
}
func Action_PresentWelcomeViewController(params: [String: Any]) {
if DoorUserDefaults.didLogin { // ๅทฒๅฐ็ปๅฝไบ๏ผไธ้่ฆๅ present Door
(params["callbackAction"] as? ([String: Any]) -> Void)?(["result": true])
} else {
guard let navigationController = Storyboard.door.navigationController(with: "DoorNavigationController") as? DoorNavigationController else { return }
let action: ([String: Any]) -> Void = { [weak navigationController] info in
navigationController?.dismiss(animated: true, completion: nil)
(params["callbackAction"] as? ([String: Any]) -> Void)?(info)
}
var paramsBuffer = params
paramsBuffer["callbackAction"] = action
navigationController.innateParams = paramsBuffer
UIApplication.shared.keyWindow?.rootViewController?.present(navigationController, animated: true, completion: nil)
}
}
func Action_LoginViewController(params: [String: Any]) -> UIViewController {
let viewController = Storyboard.login.viewController(of: LoginViewController.self)
viewController.innateParams = params
return viewController
}
func Action_PhoneNumberPickerViewController(params: [String: Any]) -> UIViewController {
let viewController = Storyboard.register.viewController(of: PhoneNumberPickerViewController.self)
viewController.innateParams = params
return viewController
}
func Action_ProfilePickerViewController(params: [String: Any]) -> UIViewController {
let viewController = Storyboard.register.viewController(of: ProfilePickerViewController.self)
viewController.innateParams = params
return viewController
}
}
// MARK: - Properties
extension Target_Door {
func Action_AccessToken() -> [String: Any]? {
return DoorUserDefaults.accessToken.flatMap { accessToken -> [String: Any] in
return ["result": accessToken]
}
}
func Action_UserID() -> [String: Any]? {
return DoorUserDefaults.userID.flatMap { accessToken -> [String: Any] in
return ["result": accessToken]
}
}
}
// MARK: - Methods
extension Target_Door {
func Action_ClearUserDefaults() {
DoorUserDefaults.clear()
}
}
|
30389016e11beeff05ee8d90d14ea1ec
| 31.761364 | 161 | 0.671523 | false | false | false | false |
iOS-mamu/SS
|
refs/heads/master
|
P/Pods/PSOperations/PSOperations/DelayOperation.swift
|
mit
|
1
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sampleโs licensing information
Abstract:
This file shows how to make an operation that efficiently waits.
*/
import Foundation
/**
`DelayOperation` is an `Operation` that will simply wait for a given time
interval, or until a specific `NSDate`.
It is important to note that this operation does **not** use the `sleep()`
function, since that is inefficient and blocks the thread on which it is called.
Instead, this operation uses `dispatch_after` to know when the appropriate amount
of time has passed.
If the interval is negative, or the `NSDate` is in the past, then this operation
immediately finishes.
*/
open class DelayOperation: Operation {
// MARK: Types
fileprivate enum Delay {
case interval(TimeInterval)
case date(Foundation.Date)
}
// MARK: Properties
fileprivate let delay: Delay
// MARK: Initialization
public init(interval: TimeInterval) {
delay = .interval(interval)
super.init()
}
public init(until date: Date) {
delay = .date(date)
super.init()
}
override open func execute() {
let interval: TimeInterval
// Figure out how long we should wait for.
switch delay {
case .interval(let theInterval):
interval = theInterval
case .date(let date):
interval = date.timeIntervalSinceNow
}
guard interval > 0 else {
finish()
return
}
let when = DispatchTime.now() + interval
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).asyncAfter(deadline: when) {
// If we were cancelled, then finish() has already been called.
if !self.isCancelled {
self.finish()
}
}
}
}
|
5db4d27b80ddefc79e3e52f7ba7c0cae
| 26.180556 | 92 | 0.605519 | false | false | false | false |
5604Pocusset/PlaySwift
|
refs/heads/master
|
GuidedTour.playground/section-58.swift
|
apache-2.0
|
1
|
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
|
6d021b2ae845ddbbe493deaa7b9d834d
| 24.461538 | 76 | 0.60423 | false | false | false | false |
ChinaPicture/Blog
|
refs/heads/master
|
UI Testing with Xcode 7/Test/ViewController.swift
|
mit
|
3
|
//
// ViewController.swift
// Test
//
// Created by Laurin Brandner on 15/06/15.
// Copyright ยฉ 2015 Laurin Brandner. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
private let cells = ["Detail View Controller", "Popover", "Action Sheet"]
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "UI Testing"
let cellClass = UITableViewCell.self
tableView.registerClass(cellClass, forCellReuseIdentifier: NSStringFromClass(cellClass))
tableView.accessibilityIdentifier = "ViewControllerTableView"
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(UITableViewCell.self), forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = cells[indexPath.row]
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
navigationController?.pushViewController(DetailViewController(), animated: true)
}
else {
let style: UIAlertControllerStyle = indexPath.row == 1 ? .Alert : .ActionSheet
let alertController = UIAlertController(title: cells[indexPath.row], message: "Just for testing", preferredStyle: style)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel) { _ in
tableView.deselectRowAtIndexPath(indexPath, animated: true)
})
alertController.view.accessibilityIdentifier = "ViewControllerAlert"
presentViewController(alertController, animated: true, completion: nil)
}
}
}
|
8d89ab85441412b1d1a075a886e6c329
| 34.096774 | 148 | 0.670956 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceComponents/Tests/DealerComponentTests/Presenter Tests/Test Doubles/CapturingDealerDetailScene.swift
|
mit
|
1
|
import DealerComponent
import EurofurenceModel
import UIKit
class CapturingDealerDetailScene: UIViewController, DealerDetailScene, DealerDetailItemComponentFactory {
private(set) var delegate: DealerDetailSceneDelegate?
func setDelegate(_ delegate: DealerDetailSceneDelegate) {
self.delegate = delegate
}
private(set) var boundNumberOfComponents: Int?
private(set) var binder: DealerDetailSceneBinder?
func bind(numberOfComponents: Int, using binder: DealerDetailSceneBinder) {
boundNumberOfComponents = numberOfComponents
self.binder = binder
}
typealias Component = AnyObject
private(set) var boundDealerSummaryComponent: CapturingDealerDetailSummaryComponent?
func makeDealerSummaryComponent(configureUsing block: (DealerDetailSummaryComponent) -> Void) -> Component {
let component = CapturingDealerDetailSummaryComponent()
block(component)
boundDealerSummaryComponent = component
return component
}
private(set) var boundLocationAndAvailabilityComponent: CapturingDealerLocationAndAvailabilityComponent?
func makeDealerLocationAndAvailabilityComponent(
configureUsing block: (DealerLocationAndAvailabilityComponent) -> Void
) -> Component {
let component = CapturingDealerLocationAndAvailabilityComponent()
block(component)
boundLocationAndAvailabilityComponent = component
return component
}
private(set) var boundAboutTheArtistComponent: CapturingAboutTheArtistComponent?
func makeAboutTheArtistComponent(configureUsing block: (DealerAboutTheArtistComponent) -> Void) -> Component {
let component = CapturingAboutTheArtistComponent()
block(component)
boundAboutTheArtistComponent = component
return component
}
private(set) var boundAboutTheArtComponent: CapturingAboutTheArtComponent?
func makeAboutTheArtComponent(configureUsing block: (AboutTheArtComponent) -> Void) -> Component {
let component = CapturingAboutTheArtComponent()
block(component)
boundAboutTheArtComponent = component
return component
}
}
extension CapturingDealerDetailScene {
@discardableResult
func bindComponent(at index: Int) -> Component? {
return binder?.bindComponent(at: index, using: self)
}
func simulateShareButtonTapped(_ sender: Any) {
delegate?.dealerDetailSceneDidTapShareButton(sender)
}
}
class CapturingDealerDetailSummaryComponent: DealerDetailSummaryComponent {
private(set) var capturedOnWebsiteSelected: (() -> Void)?
func onWebsiteSelected(perform block: @escaping () -> Void) {
capturedOnWebsiteSelected = block
}
private(set) var capturedOnTwitterSelected: (() -> Void)?
func onTwitterSelected(perform block: @escaping () -> Void) {
capturedOnTwitterSelected = block
}
private(set) var capturedOnTelegramSelected: (() -> Void)?
func onTelegramSelected(perform block: @escaping () -> Void) {
capturedOnTelegramSelected = block
}
private(set) var capturedArtistImagePNGData: Data?
func showArtistArtworkImageWithPNGData(_ data: Data) {
capturedArtistImagePNGData = data
}
private(set) var didHideArtistArtwork = false
func hideArtistArtwork() {
didHideArtistArtwork = true
}
private(set) var capturedDealerTitle: String?
func setDealerTitle(_ title: String) {
capturedDealerTitle = title
}
private(set) var capturedDealerSubtitle: String?
func showDealerSubtitle(_ subtitle: String) {
capturedDealerSubtitle = subtitle
}
private(set) var didHideSubtitle = false
func hideDealerSubtitle() {
didHideSubtitle = true
}
private(set) var capturedDealerCategories: String?
func setDealerCategories(_ categories: String) {
capturedDealerCategories = categories
}
private(set) var capturedDealerShortDescription: String?
func showDealerShortDescription(_ shortDescription: String) {
capturedDealerShortDescription = shortDescription
}
private(set) var didHideShortDescription = false
func hideDealerShortDescription() {
didHideShortDescription = true
}
private(set) var capturedDealerWebsite: String?
func showDealerWebsite(_ website: String) {
capturedDealerWebsite = website
}
private(set) var didHideWebsite = false
func hideDealerWebsite() {
didHideWebsite = true
}
private(set) var capturedDealerTwitterHandle: String?
func showDealerTwitterHandle(_ twitterHandle: String) {
capturedDealerTwitterHandle = twitterHandle
}
private(set) var didHideTwitterHandle = false
func hideTwitterHandle() {
didHideTwitterHandle = true
}
private(set) var capturedDealerTelegramHandle: String?
func showDealerTelegramHandle(_ telegramHandle: String) {
capturedDealerTelegramHandle = telegramHandle
}
private(set) var didHideTelegramHandle = false
func hideTelegramHandle() {
didHideTelegramHandle = true
}
}
class CapturingDealerLocationAndAvailabilityComponent: DealerLocationAndAvailabilityComponent {
private(set) var capturedTitle: String?
func setComponentTitle(_ title: String) {
capturedTitle = title
}
private(set) var capturedMapPNGGraphicData: Data?
func showMapPNGGraphicData(_ data: Data) {
capturedMapPNGGraphicData = data
}
private(set) var capturedLimitedAvailabilityWarning: String?
func showDealerLimitedAvailabilityWarning(_ warning: String) {
capturedLimitedAvailabilityWarning = warning
}
private(set) var capturedLocatedInAfterDarkDealersDenMessage: String?
func showLocatedInAfterDarkDealersDenMessage(_ message: String) {
capturedLocatedInAfterDarkDealersDenMessage = message
}
private(set) var didHideMap = false
func hideMap() {
didHideMap = true
}
private(set) var didHideLimitedAvailbilityWarning = false
func hideLimitedAvailbilityWarning() {
didHideLimitedAvailbilityWarning = true
}
private(set) var didHideAfterDarkDenNotice = false
func hideAfterDarkDenNotice() {
didHideAfterDarkDenNotice = true
}
}
class CapturingAboutTheArtistComponent: DealerAboutTheArtistComponent {
private(set) var capturedTitle: String?
func setAboutTheArtistTitle(_ title: String) {
capturedTitle = title
}
private(set) var capturedArtistDescription: String?
func setArtistDescription(_ artistDescription: String) {
capturedArtistDescription = artistDescription
}
}
class CapturingAboutTheArtComponent: AboutTheArtComponent {
private(set) var capturedTitle: String?
func setComponentTitle(_ title: String) {
capturedTitle = title
}
private(set) var capturedAboutTheArt: String?
func showAboutTheArtDescription(_ aboutTheArt: String) {
capturedAboutTheArt = aboutTheArt
}
private(set) var didHideAboutTheArtDescription = false
func hideAboutTheArtDescription() {
didHideAboutTheArtDescription = true
}
private(set) var capturedArtPreviewImagePNGData: Data?
func showArtPreviewImagePNGData(_ artPreviewImagePNGData: Data) {
capturedArtPreviewImagePNGData = artPreviewImagePNGData
}
private(set) var didHideArtPreview = false
func hideArtPreviewImage() {
didHideArtPreview = true
}
private(set) var capturedArtPreviewCaption: String?
func showArtPreviewCaption(_ caption: String) {
capturedArtPreviewCaption = caption
}
private(set) var didHideArtPreviewCaption = false
func hideArtPreviewCaption() {
didHideArtPreviewCaption = true
}
}
|
66344d92c2848ddf178c3ddab68c5666
| 30.417671 | 114 | 0.726192 | false | false | false | false |
AlesTsurko/DNMKit
|
refs/heads/master
|
DNM_iOS/DNM_iOS/ScoreViewController.swift
|
gpl-2.0
|
1
|
//
// ScoreViewController.swift
// DNM_iOS
//
// Created by James Bean on 11/26/15.
// Copyright ยฉ 2015 James Bean. All rights reserved.
//
import UIKit
import DNMModel
public class ScoreViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - UI
@IBOutlet weak var previousPageButton: UIButton!
@IBOutlet weak var nextPageButton: UIButton!
@IBOutlet weak var menuButton: UIButton!
@IBOutlet weak var viewSelectorTableView: UITableView!
// MARK: - Score Views
/// All ScoreViews organized by ID
private var scoreViewsByID = OrderedDictionary<PerformerID, ScoreView>()
/// All ScoreViewIDs (populates ScoreViewTableView) // performerIDs + "omni"
private var scoreViewIDs: [PerformerID] = []
// Identifiers for each PerformerView in the ensemble
private var performerIDs: [PerformerID] = []
/// ScoreView currently displayed
private var currentScoreView: ScoreView?
/// Model of an entire musical work
public var scoreModel: DNMScoreModel!
public override func viewDidLoad() {
super.viewDidLoad()
}
public func showScoreWithScoreModel(scoreModel: DNMScoreModel) {
self.scoreModel = scoreModel // maybe don't make this an ivar?
setPerformerIDsWithScoreModel(scoreModel)
setScoreViewIDsWithScoreModel(scoreModel)
manageColorMode()
build()
}
private func build() {
setupScoreViewTableView()
createScoreViews()
showScoreViewWithID("omni")
goToFirstPage()
}
// MARK: ScoreView Management
/**
Show the ScoreView with a PerformerID
- parameter id: PerformerID
*/
public func showScoreViewWithID(id: PerformerID) {
if let scoreView = scoreViewsByID[id] {
removeCurrentScoreView()
showScoreView(scoreView)
}
}
private func createScoreViews() {
for viewerID in scoreViewIDs {
let peerIDs = performerIDs.filter { $0 != viewerID }
let scoreView = ScoreView(
scoreModel: scoreModel, viewerID: viewerID, peerIDs: peerIDs
)
scoreViewsByID[viewerID] = scoreView
}
}
private func showScoreView(scoreView: ScoreView) {
view.insertSubview(scoreView, atIndex: 0)
currentScoreView = scoreView
}
private func removeCurrentScoreView() {
if let currentScoreView = currentScoreView { currentScoreView.removeFromSuperview() }
}
private func setPerformerIDsWithScoreModel(scoreModel: DNMScoreModel) {
performerIDs = scoreModel.instrumentIDsAndInstrumentTypesByPerformerID.keys
}
private func setScoreViewIDsWithScoreModel(scoreModel: DNMScoreModel) {
scoreViewIDs = performerIDs + ["omni"]
}
// MARK: - UI Setup
private func setupScoreViewTableView() {
viewSelectorTableView.delegate = self
viewSelectorTableView.dataSource = self
viewSelectorTableView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
viewSelectorTableView.translatesAutoresizingMaskIntoConstraints = true
positionViewSelectorTableView()
}
private func manageColorMode() {
view.backgroundColor = DNMColorManager.backgroundColor
setViewSelectorTableViewBackground()
}
private func setViewSelectorTableViewBackground() {
let bgView = UIView()
bgView.backgroundColor = DNMColorManager.backgroundColor
viewSelectorTableView.backgroundView = bgView
}
// MARK: - PageLayer Navigation
/**
Go to the first page of the currently displayed ScoreView
*/
public func goToFirstPage() {
currentScoreView?.goToFirstPage()
}
/**
Go to the last page of the currently displayed ScoreView
*/
public func goToLastPage() {
currentScoreView?.goToLastPage()
}
/**
Go to the next page of the currently displayed ScoreView
*/
public func goToNextPage() {
currentScoreView?.goToNextPage()
}
/**
Go to the previous page of the currently displayed ScoreView
*/
public func goToPreviousPage() {
currentScoreView?.goToPreviousPage()
}
@IBAction func didPressPreviousButton(sender: UIButton) {
goToPreviousPage()
}
@IBAction func didPressNextButton(sender: UIButton) {
goToNextPage()
}
private func resizeViewSelectorTableView() {
let contentsHeight = viewSelectorTableView.contentSize.height
let frameHeight = viewSelectorTableView.frame.height
if contentsHeight <= frameHeight {
var frame = viewSelectorTableView.frame
frame.size.height = contentsHeight
viewSelectorTableView.frame = frame
}
}
private func positionViewSelectorTableView() {
let pad: CGFloat = 20
let right = view.bounds.width
let centerX = right - 0.5 * viewSelectorTableView.frame.width - pad
viewSelectorTableView.layer.position.x = centerX
}
// MARK: - View Selector UITableViewDelegate
public func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath
)
{
if let identifier = (tableView.cellForRowAtIndexPath(indexPath)
as? ScoreSelectorTableViewCell)?.identifier
{
showScoreViewWithID(identifier)
}
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scoreViewIDs.count
}
// extend beyond title
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("scoreSelectorCell",
forIndexPath: indexPath
) as! ScoreSelectorTableViewCell
let viewerID = scoreViewIDs[indexPath.row]
// do all this in ScoreSelectorTableViewCell implementation
cell.identifier = viewerID
cell.textLabel?.text = viewerID
setVisualAttributesOfTableViewCell(cell)
resizeViewSelectorTableView()
return cell
}
// do this in ScoreSelectorTableViewCell
private func setVisualAttributesOfTableViewCell(cell: UITableViewCell) {
cell.textLabel?.textColor = UIColor.grayscaleColorWithDepthOfField(.Foreground)
cell.backgroundColor = UIColor.grayscaleColorWithDepthOfField(DepthOfField.Background)
let selBGView = UIView()
selBGView.backgroundColor = UIColor.grayscaleColorWithDepthOfField(.Middleground)
cell.selectedBackgroundView = selBGView
}
public override func prefersStatusBarHidden() -> Bool {
return true
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
babf3c6255dddcda6aefb242c69786d2
| 30.026316 | 96 | 0.668222 | false | false | false | false |
LarsStegman/helios-for-reddit
|
refs/heads/master
|
Sources/Model/Subreddit/Header.swift
|
mit
|
1
|
//
// Header.swift
// Helios
//
// Created by Lars Stegman on 02-01-17.
// Copyright ยฉ 2017 Stegman. All rights reserved.
//
import Foundation
public struct Header: Decodable, Equatable {
public let imageUrl: URL
public let size: CGSize
public let title: String
public static func ==(lhs: Header, rhs: Header) -> Bool {
return lhs.imageUrl == rhs.imageUrl && lhs.size == rhs.size && lhs.title == rhs.title
}
private enum CodingKeys: String, CodingKey {
case imageUrl = "header_img"
case size = "header_size"
case title = "header_title"
}
}
|
cf6f78a0eb07f32f9e4b53be3bf1476f
| 23.32 | 93 | 0.631579 | false | false | false | false |
zhaobin19918183/zhaobinCode
|
refs/heads/master
|
HTK/HTK/HomeViewController/WeatherView/WeatherView.swift
|
gpl-3.0
|
1
|
//
// WeatherView.swift
// HTK
//
// Created by Zhao.bin on 16/5/17.
// Copyright ยฉ 2016ๅนด ่ตตๆ. All rights reserved.
//
import UIKit
class WeatherView: UIView
{
@IBOutlet var _weatherVIew: UIView!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var tempratureLabel: UILabel!
@IBOutlet weak var weatherImageView: UIImageView!
@IBOutlet weak var weatherLabel: UILabel!
@IBOutlet weak var powerLabel: UILabel!
@IBOutlet weak var directLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var moreButton: UIButton!
override func draw(_ rect: CGRect) {
// Drawing code
}
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)!
resetUILayout()
}
func resetUILayout()
{
Bundle.main.loadNibNamed("WeatherView", owner:self,options:nil)
_weatherVIew.backgroundColor = UIColor(patternImage: UIImage(named:"weatherImage.png")!)
self.addSubview(_weatherVIew)
}
func weatherDic(_ infor:NSDictionary)
{
let windDic = infor.value(forKey: "wind")
let weatherDic = infor.value(forKey: "weather")
let info = (weatherDic! as AnyObject).value(forKey: "info") as! String
tempratureLabel.text = String(format: "ๆธฉๅบฆ : %@ ยฐ",((weatherDic as AnyObject).value(forKey: "temperature") as? String)!)
let pow = "้ฃๅ:"
powerLabel.text = pow+(((windDic as AnyObject).value(forKey: "power"))! as! String)
let dire = "้ฃๅ:"
directLabel.text = dire+(((windDic as AnyObject).value(forKey: "direct"))! as! String)
let img = UIImage(named:((weatherDic as AnyObject).value(forKey: "img"))! as! String)
weatherImageView.image = img
let moon = " ๅๅ : "
dateLabel.text = (infor.value(forKey: "date") as? String)!+moon+(infor.value(forKey: "moon") as? String)!
weatherLabel.text = info
}
}
|
e6aa7fb5b61ae9a2786184bd86d57a96
| 28.588235 | 127 | 0.614314 | false | false | false | false |
superk589/CGSSGuide
|
refs/heads/master
|
DereGuide/Common/CGSSFavoriteManager.swift
|
mit
|
2
|
//
// CGSSFavoriteManager.swift
// CGSSFoundation
//
// Created by zzk on 16/7/9.
// Copyright ยฉ 2016 zzk. All rights reserved.
//
import Foundation
class CGSSFavoriteManager {
static let `default` = CGSSFavoriteManager()
static let favoriteCardsFilePath = NSHomeDirectory() + "/Documents/favoriteCards.plist"
static let favoriteCharsFilePath = NSHomeDirectory() + "/Documents/favoriteChars.plist"
var favoriteCards: [Int] = NSArray.init(contentsOfFile: CGSSFavoriteManager.favoriteCardsFilePath) as? [Int] ?? [Int]() {
didSet {
writeFavoriteCardsToFile()
NotificationCenter.default.post(name: .favoriteCardsChanged, object: self)
}
}
var favoriteChars: [Int] = NSArray.init(contentsOfFile: CGSSFavoriteManager.favoriteCharsFilePath) as? [Int] ?? [Int]() {
didSet {
writeFavoriteCharsToFile()
NotificationCenter.default.post(name: .favoriteCharasChanged, object: self)
}
}
private init() {
}
private func writeFavoriteCardsToFile() {
(favoriteCards as NSArray).write(toFile: CGSSFavoriteManager.favoriteCardsFilePath, atomically: true)
}
private func writeFavoriteCharsToFile() {
(favoriteChars as NSArray).write(toFile: CGSSFavoriteManager.favoriteCharsFilePath, atomically: true)
}
func add(_ card: CGSSCard) {
self.favoriteCards.append(card.id!)
}
func remove(_ card: CGSSCard) {
if let index = favoriteCards.firstIndex(of: card.id!) {
self.favoriteCards.remove(at: index)
}
}
func contains(cardId: Int) -> Bool {
return favoriteCards.contains(cardId)
}
func add(_ char: CGSSChar) {
self.favoriteChars.append(char.charaId)
}
func remove(_ char: CGSSChar) {
if let index = favoriteChars.firstIndex(of: char.charaId!) {
self.favoriteChars.remove(at: index)
}
}
func contains(charId: Int) -> Bool {
return favoriteChars.contains(charId)
}
}
|
21fdb5750406ade02b13971f8da62988
| 28.647887 | 125 | 0.63753 | false | false | false | false |
JGiola/swift-package-manager
|
refs/heads/master
|
Sources/TestSupport/XCTAssertHelpers.swift
|
apache-2.0
|
2
|
/*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import POSIX
import Utility
#if os(macOS)
import class Foundation.Bundle
#endif
public func XCTAssertBuilds(
_ path: AbsolutePath,
configurations: Set<Configuration> = [.Debug, .Release],
file: StaticString = #file,
line: UInt = #line,
Xcc: [String] = [],
Xld: [String] = [],
Xswiftc: [String] = [],
env: [String: String]? = nil
) {
for conf in configurations {
do {
print(" Building \(conf)")
_ = try executeSwiftBuild(
path,
configuration: conf,
Xcc: Xcc,
Xld: Xld,
Xswiftc: Xswiftc,
env: env)
} catch {
XCTFail("""
`swift build -c \(conf)' failed:
\(error)
""", file: file, line: line)
}
}
}
public func XCTAssertSwiftTest(
_ path: AbsolutePath,
file: StaticString = #file,
line: UInt = #line,
env: [String: String]? = nil
) {
do {
_ = try SwiftPMProduct.SwiftTest.execute([], packagePath: path, env: env)
} catch {
XCTFail("""
`swift test' failed:
\(error)
""", file: file, line: line)
}
}
public func XCTAssertBuildFails(
_ path: AbsolutePath,
file: StaticString = #file,
line: UInt = #line,
Xcc: [String] = [],
Xld: [String] = [],
Xswiftc: [String] = [],
env: [String: String]? = nil
) {
do {
_ = try executeSwiftBuild(path, Xcc: Xcc, Xld: Xld, Xswiftc: Xswiftc)
XCTFail("`swift build' succeeded but should have failed", file: file, line: line)
} catch SwiftPMProductError.executionFailure(let error, _, _) {
switch error {
case ProcessResult.Error.nonZeroExit(let result) where result.exitStatus != .terminated(code: 0):
break
default:
XCTFail("`swift build' failed in an unexpected manner")
}
} catch {
XCTFail("`swift build' failed in an unexpected manner")
}
}
public func XCTAssertFileExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {
if !isFile(path) {
XCTFail("Expected file doesn't exist: \(path.asString)", file: file, line: line)
}
}
public func XCTAssertDirectoryExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {
if !isDirectory(path) {
XCTFail("Expected directory doesn't exist: \(path.asString)", file: file, line: line)
}
}
public func XCTAssertNoSuchPath(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {
if exists(path) {
XCTFail("path exists but should not: \(path.asString)", file: file, line: line)
}
}
public func XCTAssertThrows<T: Swift.Error>(
_ expectedError: T,
file: StaticString = #file,
line: UInt = #line,
_ body: () throws -> Void
) where T: Equatable {
do {
try body()
XCTFail("body completed successfully", file: file, line: line)
} catch let error as T {
XCTAssertEqual(error, expectedError, file: file, line: line)
} catch {
XCTFail("unexpected error thrown", file: file, line: line)
}
}
public func XCTAssertThrows<T: Swift.Error, Ignore>(
_ expression: @autoclosure () throws -> Ignore,
file: StaticString = #file,
line: UInt = #line,
_ errorHandler: (T) -> Bool
) {
do {
let result = try expression()
XCTFail("body completed successfully: \(result)", file: file, line: line)
} catch let error as T {
XCTAssertTrue(errorHandler(error), "Error handler returned false")
} catch {
XCTFail("unexpected error thrown", file: file, line: line)
}
}
public func XCTNonNil<T>(
_ optional: T?,
file: StaticString = #file,
line: UInt = #line,
_ body: (T) throws -> Void
) {
guard let optional = optional else {
return XCTFail("Unexpected nil value", file: file, line: line)
}
do {
try body(optional)
} catch {
XCTFail("Unexpected error \(error)", file: file, line: line)
}
}
public func XCTAssertNoDiagnostics(_ engine: DiagnosticsEngine, file: StaticString = #file, line: UInt = #line) {
let diagnostics = engine.diagnostics.filter({ $0.behavior != .note })
if diagnostics.isEmpty { return }
let diags = engine.diagnostics.map({ "- " + $0.localizedDescription }).joined(separator: "\n")
XCTFail("Found unexpected diagnostics: \n\(diags)", file: file, line: line)
}
|
ecf4dea33bc1bb1edc9f682a2d6c22a7
| 28.215569 | 113 | 0.596434 | false | false | false | false |
devroo/onTodo
|
refs/heads/master
|
Swift/OptionalChaining.playground/section-1.swift
|
gpl-2.0
|
1
|
// Playground - noun: a place where people can play
import UIKit
/*
* ์ต์
๋ ์ฒด์ธ (Optional Chaining)
*/
/*
์ค์ํํธ(Swift)์ ์ต์
๋ ์ฒด์ธ์ด ์ค๋ธ์ ํฐ๋ธ์จ(Objective-C)์ ์๋ nil์ ๋ฉ์์ง ๋ณด๋ด๊ธฐ์ ์ ์ฌํ๋ค. ๊ทธ๋ฌ๋, ๋ชจ๋ ํ์
(any type)์์ ๋์ํ๊ณ , ์ฑ๊ณต, ์คํจ ์ฌ๋ถ๋ฅผ ํ์ธํ ์ ์๋ค๋ ์ ์์ ์ฐจ์ด๊ฐ ์๋ค.
*/
// ๊ฐ์ ๋ฉํ ํด์ (Forced Unwrapping) ๋์์ผ๋ก์จ ์ต์
๋ ์ฒด์ธ
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
//let roomCount = john.residence!.numberOfRooms
// ๊ฐ์ ๋ฉํ ์๋ฌ (nil์ด๊ธฐ๋๋ฌธ์)
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has \(roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// prints "Unable to retrieve the number of rooms."
john.residence = Residence()
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has \(roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// prints "John's residence has 1 room(s)."
// ์ต์
๋ ์ฒด์ธ์ ์ํ ๋ชจ๋ธ(Model) ํด๋์ค(Class) ์ ์ธ
|
773c88a2394994ce7bae208101bf2b5b
| 22.046512 | 130 | 0.684157 | false | false | false | false |
jopamer/swift
|
refs/heads/master
|
test/Constraints/tuple.swift
|
apache-2.0
|
1
|
// RUN: %target-typecheck-verify-swift
// Test various tuple constraints.
func f0(x: Int, y: Float) {}
var i : Int
var j : Int
var f : Float
func f1(y: Float, rest: Int...) {}
func f2(_: (_ x: Int, _ y: Int) -> Int) {}
func f2xy(x: Int, y: Int) -> Int {}
func f2ab(a: Int, b: Int) -> Int {}
func f2yx(y: Int, x: Int) -> Int {}
func f3(_ x: (_ x: Int, _ y: Int) -> ()) {}
func f3a(_ x: Int, y: Int) {}
func f3b(_: Int) {}
func f4(_ rest: Int...) {}
func f5(_ x: (Int, Int)) {}
func f6(_: (i: Int, j: Int), k: Int = 15) {}
//===----------------------------------------------------------------------===//
// Conversions and shuffles
//===----------------------------------------------------------------------===//
// Variadic functions.
f4()
f4(1)
f4(1, 2, 3)
f2(f2xy)
f2(f2ab)
f2(f2yx)
f3(f3a)
f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(Int, Int) -> ()'}}
func getIntFloat() -> (int: Int, float: Float) {}
var values = getIntFloat()
func wantFloat(_: Float) {}
wantFloat(values.float)
var e : (x: Int..., y: Int) // expected-error{{cannot create a variadic tuple}}
typealias Interval = (a:Int, b:Int)
func takeInterval(_ x: Interval) {}
takeInterval(Interval(1, 2))
f5((1,1))
// Tuples with existentials
var any : Any = ()
any = (1, 2)
any = (label: 4)
// Scalars don't have .0/.1/etc
i = j.0 // expected-error{{value of type 'Int' has no member '0'}}
any.1 // expected-error{{value of type 'Any' has no member '1'}}
// expected-note@-1{{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
any = (5.0, 6.0) as (Float, Float)
_ = (any as! (Float, Float)).1
// Fun with tuples
protocol PosixErrorReturn {
static func errorReturnValue() -> Self
}
extension Int : PosixErrorReturn {
static func errorReturnValue() -> Int { return -1 }
}
func posixCantFail<A, T : Comparable & PosixErrorReturn>
(_ f: @escaping (A) -> T) -> (_ args:A) -> T
{
return { args in
let result = f(args)
assert(result != T.errorReturnValue())
return result
}
}
func open(_ name: String, oflag: Int) -> Int { }
var foo: Int = 0
var fd = posixCantFail(open)(("foo", 0))
// Tuples and lvalues
class C {
init() {}
func f(_: C) {}
}
func testLValue(_ c: C) {
var c = c
c.f(c)
let x = c
c = x
}
// <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType
func invalidPatternCrash(_ k : Int) {
switch k {
case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}}
break
}
}
// <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang
class Paws {
init() throws {}
}
func scruff() -> (AnyObject?, Error?) {
do {
return try (Paws(), nil)
} catch {
return (nil, error)
}
}
// Test variadics with trailing closures.
func variadicWithTrailingClosure(_ x: Int..., y: Int = 2, fn: (Int, Int) -> Int) {
}
variadicWithTrailingClosure(1, 2, 3) { $0 + $1 }
variadicWithTrailingClosure(1) { $0 + $1 }
variadicWithTrailingClosure() { $0 + $1 }
variadicWithTrailingClosure { $0 + $1 }
variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 }
variadicWithTrailingClosure(1, y: 0) { $0 + $1 }
variadicWithTrailingClosure(y: 0) { $0 + $1 }
variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +)
variadicWithTrailingClosure(1, y: 0, fn: +)
variadicWithTrailingClosure(y: 0, fn: +)
variadicWithTrailingClosure(1, 2, 3, fn: +)
variadicWithTrailingClosure(1, fn: +)
variadicWithTrailingClosure(fn: +)
// <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment
func gcd_23700031<T>(_ a: T, b: T) {
var a = a
var b = b
(a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}}
// expected-note @-1 {{overloads for '%' exist with these partially matching parameter lists: (UInt8, UInt8), (Int8, Int8), (UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), (Int32, Int32), (UInt64, UInt64), (Int64, Int64), (UInt, UInt), (Int, Int)}}
}
// <rdar://problem/24210190>
// Don't ignore tuple labels in same-type constraints or stronger.
protocol Kingdom {
associatedtype King
}
struct Victory<General> {
init<K: Kingdom>(_ king: K) where K.King == General {}
}
struct MagicKingdom<K> : Kingdom {
typealias King = K
}
func magify<T>(_ t: T) -> MagicKingdom<T> { return MagicKingdom() }
func foo(_ pair: (Int, Int)) -> Victory<(x: Int, y: Int)> {
return Victory(magify(pair)) // expected-error {{cannot convert return expression of type 'Victory<(Int, Int)>' to return type 'Victory<(x: Int, y: Int)>'}}
}
// https://bugs.swift.org/browse/SR-596
// Compiler crashes when accessing a non-existent property of a closure parameter
func call(_ f: (C) -> Void) {}
func makeRequest() {
call { obj in
print(obj.invalidProperty) // expected-error {{value of type 'C' has no member 'invalidProperty'}}
}
}
// <rdar://problem/25271859> QoI: Misleading error message when expression result can't be inferred from closure
struct r25271859<T> {
}
extension r25271859 {
func map<U>(f: (T) -> U) -> r25271859<U> {
}
func andThen<U>(f: (T) -> r25271859<U>) {
}
}
func f(a : r25271859<(Float, Int)>) {
a.map { $0.0 }
.andThen { _ in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{18-18=-> r25271859<String> }}
print("hello") // comment this out and it runs, leave any form of print in and it doesn't
return r25271859<String>()
}
}
// LValue to rvalue conversions.
func takesRValue(_: (Int, (Int, Int))) {}
func takesAny(_: Any) {}
var x = 0
var y = 0
let _ = (x, (y, 0))
takesRValue((x, (y, 0)))
takesAny((x, (y, 0)))
// SR-2600 - Closure cannot infer tuple parameter names
typealias Closure<A, B> = ((a: A, b: B)) -> String
func invoke<A, B>(a: A, b: B, _ closure: Closure<A,B>) {
print(closure((a, b)))
}
invoke(a: 1, b: "B") { $0.b }
invoke(a: 1, b: "B") { $0.1 }
invoke(a: 1, b: "B") { (c: (a: Int, b: String)) in
return c.b
}
invoke(a: 1, b: "B") { c in
return c.b
}
// Crash with one-element tuple with labeled element
class Dinner {}
func microwave() -> Dinner? {
let d: Dinner? = nil
return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner?'}}
}
func microwave() -> Dinner {
let d: Dinner? = nil
return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner'}}
}
|
d2b635fc8b4ad2c4b13af5439f4c0b38
| 25.57085 | 254 | 0.616029 | false | false | false | false |
davejlin/treehouse
|
refs/heads/master
|
swift/swift2/selfie-photo/SelfiePhoto/PhotoSortListController.swift
|
unlicense
|
1
|
//
// PhotoSortListController.swift
// SelfiePhoto
//
// Created by Lin David, US-205 on 11/15/16.
// Copyright ยฉ 2016 Lin David. All rights reserved.
//
import UIKit
import CoreData
class PhotoSortListController<SortType: CustomTitleConvertible where SortType: NSManagedObject>: UITableViewController {
let dataSource: SortableDataSource<SortType>
let sortItemSelector: SortItemSelector<SortType>
var onSortSelection: (Set<SortType> -> Void)?
init(dataSource: SortableDataSource<SortType>, sortItemSelector: SortItemSelector<SortType>) {
self.dataSource = dataSource
self.sortItemSelector = sortItemSelector
super.init(style: .Grouped)
tableView.dataSource = dataSource
tableView.delegate = sortItemSelector
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigation()
}
private func setupNavigation() {
let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(PhotoSortListController.dismissPhotoSortListController))
navigationItem.rightBarButtonItem = doneButton
}
@objc private func dismissPhotoSortListController() {
guard let onSortSelection = onSortSelection else { return }
onSortSelection(sortItemSelector.checkedItems)
dismissViewControllerAnimated(true, completion: nil)
}
}
|
ffbfe99fd92d2cc6f7987808b359bf14
| 31.369565 | 157 | 0.706317 | false | false | false | false |
raulriera/TextFieldEffects
|
refs/heads/master
|
TextFieldEffects/TextFieldEffects/YoshikoTextField.swift
|
mit
|
1
|
//
// YoshikoTextField.swift
// TextFieldEffects
//
// Created by Keenan Cassidy on 01/10/2015.
// Copyright ยฉ 2015 Raul Riera. All rights reserved.
//
import UIKit
/**
An YoshikoTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the edges and background of the control.
*/
@IBDesignable open class YoshikoTextField: TextFieldEffects {
private let borderLayer = CALayer()
private let textFieldInsets = CGPoint(x: 6, y: 0)
private let placeHolderInsets = CGPoint(x: 6, y: 0)
/**
The size of the border.
This property applies a thickness to the border of the control. The default value for this property is 2 points.
*/
@IBInspectable open var borderSize: CGFloat = 2.0 {
didSet {
updateBorder()
}
}
/**
The color of the border when it has content.
This property applies a color to the edges of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var activeBorderColor: UIColor = .clear {
didSet {
updateBorder()
updateBackground()
updatePlaceholder()
}
}
/**
The color of the border when it has no content.
This property applies a color to the edges of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var inactiveBorderColor: UIColor = .clear {
didSet {
updateBorder()
updateBackground()
updatePlaceholder()
}
}
/**
The color of the input's background when it has content. When it's not focused it reverts to the color of the `inactiveBorderColor`
This property applies a color to the background of the input.
*/
@IBInspectable dynamic open var activeBackgroundColor: UIColor = .clear {
didSet {
updateBackground()
}
}
/**
The color of the placeholder text.
This property applies a color to the complete placeholder string. The default value for this property is a dark gray color.
*/
@IBInspectable dynamic open var placeholderColor: UIColor = .darkGray {
didSet {
updatePlaceholder()
}
}
/**
The scale of the placeholder font.
This property determines the size of the placeholder label relative to the font size of the text field.
*/
@IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.7 {
didSet {
updatePlaceholder()
}
}
override open var placeholder: String? {
didSet {
updatePlaceholder()
}
}
// MARK: Private
private func updateBorder() {
borderLayer.frame = rectForBounds(bounds)
borderLayer.borderWidth = borderSize
borderLayer.borderColor = (isFirstResponder || text!.isNotEmpty) ? activeBorderColor.cgColor : inactiveBorderColor.cgColor
}
private func updateBackground() {
if isFirstResponder || text!.isNotEmpty {
borderLayer.backgroundColor = activeBackgroundColor.cgColor
} else {
borderLayer.backgroundColor = inactiveBorderColor.cgColor
}
}
private func updatePlaceholder() {
placeholderLabel.frame = placeholderRect(forBounds: bounds)
placeholderLabel.text = placeholder
placeholderLabel.textAlignment = textAlignment
if isFirstResponder || text!.isNotEmpty {
placeholderLabel.font = placeholderFontFromFontAndPercentageOfOriginalSize(font: font!, percentageOfOriginalSize: placeholderFontScale * 0.8)
placeholderLabel.text = placeholder?.uppercased()
placeholderLabel.textColor = activeBorderColor
} else {
placeholderLabel.font = placeholderFontFromFontAndPercentageOfOriginalSize(font: font!, percentageOfOriginalSize: placeholderFontScale)
placeholderLabel.textColor = placeholderColor
}
}
private func placeholderFontFromFontAndPercentageOfOriginalSize(font: UIFont, percentageOfOriginalSize: CGFloat) -> UIFont! {
let smallerFont = UIFont(descriptor: font.fontDescriptor, size: font.pointSize * placeholderFontScale)
return smallerFont
}
private func rectForBounds(_ bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x, y: bounds.origin.y + placeholderHeight, width: bounds.size.width, height: bounds.size.height - placeholderHeight)
}
private var placeholderHeight : CGFloat {
return placeHolderInsets.y + placeholderFontFromFontAndPercentageOfOriginalSize(font: font!, percentageOfOriginalSize: placeholderFontScale).lineHeight
}
private func animateViews() {
UIView.animate(withDuration: 0.2, animations: {
// Prevents a "flash" in the placeholder
if self.text!.isEmpty {
self.placeholderLabel.alpha = 0
}
self.placeholderLabel.frame = self.placeholderRect(forBounds: self.bounds)
}) { _ in
self.updatePlaceholder()
UIView.animate(withDuration: 0.3, animations: {
self.placeholderLabel.alpha = 1
self.updateBorder()
self.updateBackground()
}, completion: { _ in
self.animationCompletionHandler?(self.isFirstResponder ? .textEntry : .textDisplay)
})
}
}
// MARK: - TextFieldEffects
override open func animateViewsForTextEntry() {
animateViews()
}
override open func animateViewsForTextDisplay() {
animateViews()
}
// MARK: - Overrides
override open var bounds: CGRect {
didSet {
updatePlaceholder()
updateBorder()
updateBackground()
}
}
override open func drawViewsForRect(_ rect: CGRect) {
updatePlaceholder()
updateBorder()
updateBackground()
layer.insertSublayer(borderLayer, at: 0)
addSubview(placeholderLabel)
}
open override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
if isFirstResponder || text!.isNotEmpty {
return CGRect(x: placeHolderInsets.x, y: placeHolderInsets.y, width: bounds.width, height: placeholderHeight)
} else {
return textRect(forBounds: bounds)
}
}
open override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.offsetBy(dx: textFieldInsets.x, dy: textFieldInsets.y + placeholderHeight / 2)
}
// MARK: - Interface Builder
open override func prepareForInterfaceBuilder() {
placeholderLabel.alpha = 1
}
}
|
7e0996f48e1fcfd3f93b6096bfbc4e1d
| 31.99061 | 190 | 0.639818 | false | false | false | false |
tryswift/trySwiftData
|
refs/heads/master
|
TrySwiftData/Extensions/Date+Timepiece.swift
|
mit
|
1
|
//
// Date+Timepiece.swift
// trySwiftData
//
// Created by Tim Oliver on 2/12/17.
// Copyright ยฉ 2017 CocoaPods. All rights reserved.
//
import Foundation
// taken from https://github.com/naoty/Timepiece
extension Date {
// MARK: - Get components
var year: Int {
return components.year!
}
var month: Int {
return components.month!
}
var weekday: Int {
return components.weekday!
}
var day: Int {
return components.day!
}
var hour: Int {
return components.hour!
}
var minute: Int {
return components.minute!
}
var second: Int {
return components.second!
}
fileprivate var calendar: Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
return calendar
}
fileprivate var components: DateComponents {
return (calendar as NSCalendar).components([.year, .month, .weekday, .day, .hour, .minute, .second], from: self)
}
public static func date(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int) -> Date {
let now = Date()
return now.change(year: year, month: month, day: day, hour: hour, minute: minute, second: second)
}
static func date(year: Int, month: Int, day: Int) -> Date {
return Date.date(year: year, month: month, day: day, hour: 0, minute: 0, second: 0)
}
/**
Initialize a date by changing date components of the receiver.
*/
func change(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil) -> Date! {
var components = self.components
components.year = year ?? self.year
components.month = month ?? self.month
components.day = day ?? self.day
components.hour = hour ?? self.hour
components.minute = minute ?? self.minute
components.second = second ?? self.second
return calendar.date(from: components)
}
}
|
2081acc148985762045860735a40350e
| 25.675325 | 138 | 0.605161 | false | false | false | false |
flexih/CorePlayer.Swift
|
refs/heads/master
|
CorePlayer/CPPlayerView.swift
|
mit
|
1
|
//
// CPPlayerView.swift
// CorePlayer
//
// Created by flexih on 4/14/15.
// Copyright (c) 2015 flexih. All rights reserved.
//
import AVFoundation
#if os(iOS)
import UIKit
#else
import AppKit
#endif
enum VideoGravity: Int {
case Aspect = 1
case Fill
}
class CPPlayerView: UXView {
var gravity: VideoGravity {
get {
let videoGravity = playerLayer().videoGravity
if videoGravity == AVLayerVideoGravityResizeAspect {
return .Aspect
} else {
return .Fill
}
}
set(newGravity) {
if newGravity == .Aspect {
playerLayer().videoGravity = AVLayerVideoGravityResizeAspect
} else {
playerLayer().videoGravity = AVLayerVideoGravityResizeAspectFill
}
}
}
var scale: CGFloat = 1 {
didSet {
let frame = self.frame
self.frame = frame
}
}
#if os(iOS)
override class func layerClass() -> AnyClass {
return AVPlayerLayer.self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
#else
required init?(coder: NSCoder) {
super.init(coder: coder)
}
#endif
override init(frame: CGRect) {
super.init(frame: frame)
#if os(iOS)
userInteractionEnabled = false
#else
wantsLayer = true
layer = AVPlayerLayer()
#endif
}
override var frame: CGRect {
get {
return super.frame
}
set(newFrame) {
var frame = newFrame
#if __USE_SCALE__
frame.size.width *= scale
frame.size.height *= scale
frame.origin.x = floor((newFrame.size.width - frame.size.width) * 0.5)
frame.origin.y = floor((newFrame.size.height - frame.size.height) * 0.5)
#endif
super.frame = frame
}
}
func playerLayer() -> AVPlayerLayer {
return layer as! AVPlayerLayer
}
}
|
e119a82615bd232244bcb07d7b09f347
| 21.285714 | 88 | 0.512363 | false | false | false | false |
justindhill/Jiramazing
|
refs/heads/master
|
src/Jiramazing.swift
|
mit
|
1
|
//
// Jiramazing.swift
// Jiramazing
//
// Created by Justin Hill on 7/23/16.
// Copyright ยฉ 2016 Justin Hill. All rights reserved.
//
import Foundation
import Dispatch
@objc(JRAErrorCode) public enum ErrorCode: Int {
case Unauthenticated
case BaseUrlNotSet
case InvalidParameter
case MalformedBaseUrl
case MalformedPath
case MalformedJSONResponse
case UnexpectedResponseStructure
case JSONEncodingError
}
@objc public class Jiramazing: NSObject, NSURLSessionDelegate {
public private(set) var authenticated: Bool = false
private var urlSession: NSURLSession!
private static let TimeoutInterval: NSTimeInterval = 60
public var authenticationMethod: AuthenticationMethod = .Basic
public var username: String = ""
public var password: String = ""
public var baseUrl: NSURL?
public static let ErrorDomain = "JiramazingErrorDomain"
@objc(sharedInstance) public static var instance = Jiramazing()
override init() {
super.init()
self.urlSession = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: self,
delegateQueue: NSOperationQueue.mainQueue()
)
}
// MARK: - Session
public func validateSession(completion: (success: Bool) -> Void) {
if let authorizationHeader = String.jiramazing_basicAuthEncodedString(self.username, password: self.password) {
self.get("/rest/auth/1/session", authenticationMethod: .Unauthenticated, customHeaders:["Authorization": authorizationHeader], completion: { (responseJSONObject, error) in
completion(success: error == nil)
})
} else {
completion(success: false)
}
}
// MARK: - Project
public func getProjects(completion: (projects: [Project]?, error: NSError?) -> Void) {
self.get("/rest/api/2/project", queryParameters: ["expand": "description,lead,url,projectKeys"]) { (data, error) in
if let error = error {
completion(projects: nil, error: error)
return
}
if let data = data as? [[String: AnyObject]] {
let projects = data.map({ (projectDict) -> Project in
return Project(attributes: projectDict)
})
completion(projects: projects, error: nil)
} else {
completion(projects: nil, error: NSError.jiramazingUnexpectedStructureError())
}
}
}
public func getProjectWithProjectIdOrKey(projectIdOrKey: String, completion: (project: Project?, error: NSError?) -> Void) {
self.get("/rest/api/2/project/\(projectIdOrKey)") { (data, error) in
if let error = error {
completion(project: nil, error: error)
return
}
if let data = data as? [String: AnyObject] {
let project = Project(attributes: data)
completion(project: project, error: nil)
} else {
completion(project: nil, error: NSError.jiramazingUnexpectedStructureError())
}
}
}
// MARK: - Issue
public func getIssueWithIdOrKey(idOrKey: String, completion: (issue: Issue?, error: NSError?) -> Void) {
self.get("/rest/api/2/issue/\(idOrKey)", queryParameters: ["expand": "names,editmeta,changelog"]) { (data, error) in
if let error = error {
completion(issue: nil, error: error)
return
}
if let data = data as? [String: AnyObject] {
let issue = Issue(attributes: data)
completion(issue: issue, error: nil)
} else {
completion(issue: nil, error: NSError.jiramazingUnexpectedStructureError())
}
}
}
// MARK: - Search
public func searchIssuesWithJQLString(jql: String,
offset: Int = 0,
maxResults: Int = 50,
fields: [String]? = nil,
expand: [String]? = nil,
completion: (issues: [Issue]?, total: Int, error: NSError?) -> Void) {
var params: [String: AnyObject] = [
"jql": jql,
"startAt": offset,
"maxResults": maxResults
]
if let fields = fields {
params["fields"] = fields.joinWithSeparator(",")
}
if let expand = expand {
params["expand"] = expand.joinWithSeparator(",")
}
self.get("/rest/api/2/search", queryParameters: params) { (data, error) in
if let error = error {
completion(issues: nil, total: 0, error: error)
return
}
if let data = data as? [String: AnyObject],
let total = data["total"] as? Int,
let issuesAttributes = data["issues"] as? [[String: AnyObject]] {
let issues = issuesAttributes.map({ (issueAttributes) -> Issue in
return Issue(attributes: issueAttributes)
})
completion(issues: issues, total: total, error: nil)
return
} else {
completion(issues: nil, total: 0, error: NSError.jiramazingUnexpectedStructureError())
return
}
}
}
// MARK: - User
public func getUserWithUsername(username: String, completion: (user: User?, error: NSError?) -> Void) {
self.get("/rest/api/2/user", queryParameters: ["username": username, "expand": "groups,applicationRoles"]) { (data, error) in
if let error = error {
completion(user: nil, error: error)
return
}
if let data = data as? [String: AnyObject] {
let user = User(attributes: data)
completion(user: user, error: nil)
} else {
completion(user: nil, error: NSError.jiramazingUnexpectedStructureError())
}
}
}
public func getUserWithKey(key: String, completion: (user: User?, error: NSError?) -> Void) {
self.get("/rest/api/2/user", queryParameters: ["key": key, "expand": "groups,applicationRoles"]) { (data, error) in
if let error = error {
completion(user: nil, error: error)
return
}
if let data = data as? [String: AnyObject] {
let user = User(attributes: data)
completion(user: user, error: nil)
} else {
completion(user: nil, error: NSError.jiramazingUnexpectedStructureError())
}
}
}
// MARK: - HTTP methods
private func get(path: String,
queryParameters: [String: AnyObject]? = nil,
authenticationMethod: AuthenticationMethod? = nil,
customHeaders: [String: AnyObject]? = nil,
completion: (data: AnyObject?, error: NSError?) -> Void) {
guard let baseUrl = self.baseUrl else {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.BaseUrlNotSet, description: "Could not complete the request. The base URL was not set."))
return
}
do {
let request = try NSMutableURLRequest.requestWithHTTPMethod("GET", baseUrl: baseUrl, path: path, queryParameters: queryParameters, customHeaders: customHeaders)
weak var weakSelf = self
self.performDataTaskWithRequest(request, authenticationMethod: authenticationMethod ?? self.authenticationMethod, completion: completion)
} catch let error as NSError {
completion(data: nil, error: error)
}
}
private func put(path: String,
queryParameters: [String: AnyObject]? = nil,
bodyInfo: [String: AnyObject],
authenticationMethod: AuthenticationMethod?,
customHeaders: [String: AnyObject]? = nil,
completion: (data: AnyObject?, error: NSError?) -> Void) {
guard let baseUrl = self.baseUrl else {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.BaseUrlNotSet, description: "Could not complete the request. The base URL was not set."))
return
}
do {
let request = try NSMutableURLRequest.requestWithHTTPMethod("GET", baseUrl: baseUrl, path: path, queryParameters: queryParameters, customHeaders: customHeaders)
if let bodyData = try? NSJSONSerialization.dataWithJSONObject(bodyInfo, options: []) {
request.HTTPBody = bodyData
} else {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.JSONEncodingError, description: "Could not complete the request. The supplied bodyInfo could not be encoded to a JSON object."))
return
}
weak var weakSelf = self
self.performDataTaskWithRequest(request, authenticationMethod: authenticationMethod ?? self.authenticationMethod, completion: completion)
} catch let error as NSError {
completion(data: nil, error: error)
}
}
private func post(path: String,
queryParameters: [String: AnyObject]? = nil,
bodyInfo: [String: AnyObject],
authenticationMethod: AuthenticationMethod?,
customHeaders: [String: AnyObject]? = nil,
completion: (data: AnyObject?, error: NSError?) -> Void) {
guard let baseUrl = self.baseUrl else {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.BaseUrlNotSet, description: "Could not complete the request. The base URL was not set."))
return
}
do {
let request = try NSMutableURLRequest.requestWithHTTPMethod("GET", baseUrl: baseUrl, path: path, queryParameters: queryParameters, customHeaders: customHeaders)
if let bodyData = try? NSJSONSerialization.dataWithJSONObject(bodyInfo, options: []) {
request.HTTPBody = bodyData
} else {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.JSONEncodingError, description: "Could not complete the request. The supplied bodyInfo could not be encoded to a JSON object."))
return
}
weak var weakSelf = self
self.performDataTaskWithRequest(request, authenticationMethod: authenticationMethod ?? self.authenticationMethod, completion: completion)
} catch let error as NSError {
completion(data: nil, error: error)
}
}
private func delete(path: String,
queryParameters: [String: AnyObject]? = nil,
authenticationMethod: AuthenticationMethod?,
customHeaders: [String: AnyObject]? = nil,
completion: (data: AnyObject?, error: NSError?) -> Void) {
guard let baseUrl = self.baseUrl else {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.BaseUrlNotSet, description: "Could not complete the request. The base URL was not set."))
return
}
do {
let request = try NSMutableURLRequest.requestWithHTTPMethod("GET", baseUrl: baseUrl, path: path, queryParameters: queryParameters, customHeaders: customHeaders)
weak var weakSelf = self
self.performDataTaskWithRequest(request, authenticationMethod: authenticationMethod ?? self.authenticationMethod, completion: completion)
} catch let error as NSError {
completion(data: nil, error: error)
}
}
private func performDataTaskWithRequest(request: NSMutableURLRequest,
authenticationMethod: AuthenticationMethod?,
completion: (data: AnyObject?, error: NSError?) -> Void) {
var resolvedAuthMethod = self.authenticationMethod
if let authenticationMethod = authenticationMethod {
resolvedAuthMethod = authenticationMethod
}
if resolvedAuthMethod == .Basic {
if self.username.isEmpty || self.password.isEmpty {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.Unauthenticated, description: "Authentication method is .Basic, but username or password is not set."))
return
}
let authString = String.jiramazing_basicAuthEncodedString(username, password: password)
request.setValue(authString, forHTTPHeaderField: "Authorization")
}
request.setValue("gzip", forHTTPHeaderField: "Accept-Encoding")
let task = self.urlSession.dataTaskWithRequest(request) { (data, response, error) in
if let error = error {
completion(data: nil, error: error)
return
} else if let response = response as? NSHTTPURLResponse where response.statusCode >= 400 {
fatalError("Handling non-fatal HTTP errors not yet supported.")
} else if let data = data {
do {
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? AnyObject {
completion(data: jsonObject, error: nil)
return
}
} catch {
completion(data: nil, error: NSError.jiramazingErrorWithCode(.MalformedJSONResponse, description: "Unabled to parse the server response because it was malformed."))
return
}
}
}
task.resume()
}
}
// MARK: - Extensions
private extension NSError {
class func jiramazingErrorWithCode(code: ErrorCode, description: String) -> NSError {
return NSError(
domain: Jiramazing.ErrorDomain,
code: code.rawValue,
userInfo: [NSLocalizedDescriptionKey: description]
)
}
class func jiramazingUnexpectedStructureError() -> NSError {
return NSError.jiramazingErrorWithCode(.UnexpectedResponseStructure, description: "The response was valid JSON, but was of an unexpected structure.")
}
}
private extension NSMutableURLRequest {
class func requestWithHTTPMethod(method: String, baseUrl: NSURL, path: String, queryParameters: [String: AnyObject]? = nil, customHeaders: [String: AnyObject]? = nil) throws -> NSMutableURLRequest {
if let components = NSURLComponents(URL: baseUrl, resolvingAgainstBaseURL: true) {
components.path = path
if let queryParameters = queryParameters {
let queryItemsToAdd = queryParameters.map({ (key, value) -> NSURLQueryItem in
return NSURLQueryItem(name: key, value: String(value))
})
if components.queryItems == nil {
components.queryItems = queryItemsToAdd
} else {
components.queryItems?.appendContentsOf(queryItemsToAdd)
}
}
if let url = components.URL {
let request = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: Jiramazing.TimeoutInterval)
request.HTTPMethod = method
if let customHeaders = customHeaders {
for (key, value) in customHeaders {
request.addValue(String(value), forHTTPHeaderField: key)
}
}
return request
} else {
throw NSError.jiramazingErrorWithCode(.MalformedPath, description: "Could not complete the request. The path was malformed.")
}
} else {
throw NSError.jiramazingErrorWithCode(.MalformedBaseUrl, description: "The request's base URL was malformed.")
}
}
}
|
1678fcc355237db14c83ccc29a488bab
| 40.720513 | 206 | 0.588163 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.