repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RupiDev/QExpandableTableView
|
Pod/Classes/QExpandableTableView.swift
|
1
|
7541
|
//
// QExpandableTableView.swift
// Pods
//
// Created by Rupin Bhalla on 3/25/16.
//
//
import Foundation
// This cocoa-pod will be for used as an Expandable Table View. In this cocoa-pod you
// will be able to expand and collaspe rows according to what you need.
/**
This class is the QExpandableTableView class. It inherits from UITableViewDelegate and UITableViewDataSource.
This class contains the methods that allow the user to have an expandable table view. As long you specify in the
plist, this class will read all the information from the plist and display the information as an expandable table view
*/
public class QExpandableTableView: UIViewController, UITableViewDelegate, UITableViewDataSource
{
/// This array wil contain all the information in the plist into this array. We pull all the information from this array
var cellDescriptors: NSMutableArray!
/// This is a double array because you have section and all the rows. In this example there is only 1 section
var visibleRowsInSection = [[Int]]()
override public func viewDidLoad() {
super.viewDidLoad()
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
/**
Assigns tableview delegates and registers all required nibs for cells
- parameter tableView: the tableView which will be given from the child class
*/
public func configureTableView(tableView: UITableView) {
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView(frame: CGRectZero)
//Assigns a xib file with the cell identifier
tableView.registerNib(UINib(nibName: "NormalCell", bundle: nil), forCellReuseIdentifier: "idCellNormal")
tableView.registerNib(UINib(nibName: "ValuePickerCell", bundle: nil), forCellReuseIdentifier: "idCellValuePicker")
}
/**
* This will load all cell attributes from the p-list. You will have to make the p-list yourself.
* Once you make the p-list you can specifiy what rows you can put it and then this method will allow you
to load those contents into an array called cellDescriptors that you will use throughout the project.
*/
public func loadCellDescriptors(tableView: UITableView) {
//Locates the plist file and load it into the table view
if (NSBundle.mainBundle().pathForResource("CellDescriptor", ofType: "plist") != nil){
cellDescriptors = NSMutableArray(contentsOfFile: NSBundle.mainBundle().pathForResource("CellDescriptor", ofType: "plist")!)
print(cellDescriptors)
getIndicesOfVisibleRows()
tableView.reloadData()
}
}
/**
This method will recieve all the indices of the visible rows in each section. After it revieves all the indices
it will append to the same array. So after this method is called you will have an array of all the visible
*/
func getIndicesOfVisibleRows() {
visibleRowsInSection.removeAll()//To prevent duplicate cells
for currentSectionCells in cellDescriptors {
var visibleRows = [Int]()
for row in 0...( ( currentSectionCells as! [[String: AnyObject]] ).count - 1) {
if (currentSectionCells[row]["isVisible"] as! Bool == true) {
visibleRows.append(row)
}
}
visibleRowsInSection.append(visibleRows)
}
}
/**
This will get the Cell Description from the plist that you want to have
- parameter indexPath: keeps track of where you are in the pList
- returns: This will return a String that tells you what kind of cell you have, that you made as a unique cell
*/
func getCellDescriptorForIndexPath(index: Int) -> [String: AnyObject] {
let cell = cellDescriptors[0][index] as! [String: AnyObject]
return cell
}
/**
This function allows the user to select the current cell. If the cell you want is a custom cell, you can decide
it there. It will return the specific cell of that indexPath
- parameter tableView: This is the tableview that you are working and you want to insert into the tableview
- parameter indexPath: This is the specific indexPath that you are at.
- returns: This method returns the cell.
*/
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let actualIndex = visibleRowsInSection[0][indexPath.row]
let currentCellDescriptor = getCellDescriptorForIndexPath(actualIndex)
let cell = tableView.dequeueReusableCellWithIdentifier(currentCellDescriptor["cellIdentifier"] as! String, forIndexPath: indexPath) as! CustomCell
cell.textLabel?.text = ""
cell.detailTextLabel?.text = ""
if (currentCellDescriptor["isVisible"] as! Int == 1) {
if ( (currentCellDescriptor["primaryTitle"] as! String).characters.count > 0 ){
cell.textLabel?.text = currentCellDescriptor["primaryTitle"] as? String
}
else if ((currentCellDescriptor["secondaryTitle"] as! String).characters.count > 0) {
cell.detailTextLabel?.text = currentCellDescriptor["secondaryTitle"] as? String
}
}
return cell
}
/**
This method will be activated when you selected a certain row/cell. This method will do the collasping and expanding
of the expandable table view
- parameter tableView: This is the tableview that you are working on
- parameter indexPath: This is the indexPath that you are on during the tableView
*/
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexOfTappedRow = visibleRowsInSection[indexPath.section][indexPath.row]
if (cellDescriptors[indexPath.section][indexOfTappedRow]["isExpandable"] as! Bool == true) {
var shouldExpandAndShowSubRows = false
if (cellDescriptors[indexPath.section][indexOfTappedRow]["isExpanded"] as! Bool == false) {
shouldExpandAndShowSubRows = true
}
cellDescriptors[indexPath.section][indexOfTappedRow].setValue(shouldExpandAndShowSubRows, forKey: "isExpanded")
for i in (indexOfTappedRow + 1)...(indexOfTappedRow + (cellDescriptors[indexPath.section][indexOfTappedRow]["additionalRows"] as! Int)) {
cellDescriptors[indexPath.section][i].setValue(shouldExpandAndShowSubRows, forKey: "isVisible")
}
}
getIndicesOfVisibleRows()
tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: UITableViewRowAnimation.None)
}
/**
This will return the number of Rows in the section
- parameter tableView: The specific table view you want the rows of
- parameter section: The specific section in the table view you want the rows of
- returns: Returns the number of rows in the desired section of the desired tableview
*/
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (visibleRowsInSection != []) {
return visibleRowsInSection[0].count
}
else {
return 0
}
}
}
|
mit
|
d54ce351bcc0d20f45a2c0e2cae4de01
| 42.848837 | 154 | 0.670999 | 5.236806 | false | false | false | false |
saagarjha/iina
|
iina/JavascriptPolyfill.swift
|
1
|
3292
|
//
// JavascriptPolyfill.swift
// iina
//
// Created by Collider LI on 6/3/2020.
// Copyright © 2020 lhc. All rights reserved.
//
import JavaScriptCore
class JavascriptPolyfill {
weak var plugin: JavascriptPluginInstance!
var timers = [String: Timer]()
init(pluginInstance: JavascriptPluginInstance) {
self.plugin = pluginInstance
}
deinit {
for timer in timers.values {
timer.invalidate()
}
}
func removeTimer(identifier: String) {
let timer = self.timers.removeValue(forKey: identifier)
timer?.invalidate()
}
func createTimer(callback: JSValue, ms: Double, repeats : Bool) -> String {
let timeInterval = ms/1000.0
let uuid = NSUUID().uuidString
DispatchQueue.main.async(execute: {
let timer = Timer.scheduledTimer(timeInterval: timeInterval,
target: self,
selector: #selector(self.callJSCallback),
userInfo: callback,
repeats: repeats)
self.timers[uuid] = timer
})
return uuid
}
@objc func callJSCallback(_ timer: Timer) {
let callback = (timer.userInfo as! JSValue)
callback.call(withArguments: nil)
}
func register(inContext context: JSContext) {
let setInterval: @convention(block) (JSValue, Double) -> String = { [unowned self] (callback, ms) in
return self.createTimer(callback: callback, ms: ms, repeats: true)
}
let setTimeout: @convention(block) (JSValue, Double) -> String = { [unowned self] (callback, ms) in
return self.createTimer(callback: callback, ms: ms, repeats: false)
}
let clearInterval: @convention(block) (String) -> () = { [unowned self] identifier in
self.removeTimer(identifier: identifier)
}
let clearTimeout: @convention(block) (String) -> () = { [unowned self] identifier in
self.removeTimer(identifier: identifier)
}
let require: @convention(block) (String) -> Any? = { [unowned self] path in
let instance = self.plugin!
let currentPath = instance.currentFile!.deletingLastPathComponent()
let requiredURL = currentPath.appendingPathComponent(path).standardized
guard requiredURL.absoluteString.hasPrefix(instance.plugin.root.absoluteString) else {
return nil
}
return [
"path": requiredURL.path,
"module": instance.evaluateFile(requiredURL, asModule: true)
] as [String: Any?]
}
context.setObject(clearInterval, forKeyedSubscript: "clearInterval" as NSString)
context.setObject(clearTimeout, forKeyedSubscript: "clearTimeout" as NSString)
context.setObject(setInterval, forKeyedSubscript: "setInterval" as NSString)
context.setObject(setTimeout, forKeyedSubscript: "setTimeout" as NSString)
context.setObject(require, forKeyedSubscript: "__require__" as NSString)
context.evaluateScript(requirePolyfill)
}
}
fileprivate let requirePolyfill = """
require = (() => {
const cache = {};
return function (file) {
if (cache[file]) {
return cache[file];
}
const result = __require__(file);
if (result) {
cache[result.path] = result.module;
return result.module;
}
return undefined;
};
})();
"""
|
gpl-3.0
|
511a07a9d75905f008959fd9e1ba5fdc
| 30.644231 | 104 | 0.648435 | 4.324573 | false | false | false | false |
skedgo/tripkit-ios
|
Sources/TripKitUI/views/map annotations/TKUICircleAnnotationView.swift
|
1
|
1909
|
//
// TKUICircleAnnotationView.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 12.12.18.
// Copyright © 2018 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
open class TKUICircleAnnotationView: MKAnnotationView {
private enum Constants {
static let circleSize: CGFloat = 12.0
static let smallFactor: CGFloat = 0.8
static let lineWidth: CGFloat = 1.5
}
public let isLarge: Bool
public var circleColor: UIColor? = nil
public var borderColor: UIColor? = nil
public var isFaded: Bool = false
public init(annotation: MKAnnotation?, drawLarge: Bool, reuseIdentifier: String?) {
self.isLarge = drawLarge
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
let radius = Constants.circleSize * (drawLarge ? 1 : Constants.smallFactor)
frame.size = CGSize(width: radius, height: radius)
isOpaque = true
backgroundColor = .clear
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
let fillColor = self.circleColor ?? .black
let borderColor = self.borderColor ?? fillColor.darkerColor(percentage: 0.75)
let lineWidth = Constants.lineWidth * (isLarge ? 1 : Constants.smallFactor)
let lineOffset = lineWidth / 2
let circleRect = CGRect(x: lineOffset, y: lineOffset, width: bounds.width - lineWidth, height: bounds.height - lineWidth)
if isFaded || circleColor != nil {
context.setFillColor(fillColor.cgColor)
} else {
context.setFillColor(UIColor.tkBackground.cgColor)
}
context.fillEllipse(in: circleRect)
context.setLineWidth(lineWidth)
context.setStrokeColor(borderColor.cgColor)
context.strokeEllipse(in: circleRect)
}
}
|
apache-2.0
|
0c936a2c25eec1fac4fecf2983304d43
| 30.262295 | 125 | 0.70215 | 4.394009 | false | false | false | false |
P0ed/Fx
|
Sources/FxTestKit/ReactiveOperator+TestSignal.swift
|
1
|
1192
|
import Fx
public struct TestSignal<Value, ReturnValues>: ReactiveOperator {
public let expectedReturns: Int
public let generator: (ReactiveOperatorContext, @escaping (ReturnValues) -> Void) -> Disposable
public init(
expectedReturns: Int,
timedInputs: [TimedValue<Value>],
generator: @escaping (ReactiveOperatorContext, Signal<Value>) -> Signal<ReturnValues>
) {
self.expectedReturns = expectedReturns
self.generator = { context, sink in
let pipe = SignalPipe<Value>()
timedInputs.forEach { v in
context.timed(at: v.time) { pipe.put(v.value) }
}
return generator(context, pipe.signal).observe(sink)
}
}
}
public extension TestSignal {
init(
expectedReturns: Int,
inputs: [Value],
generator: @escaping (ReactiveOperatorContext, Signal<Value>) -> Signal<ReturnValues>
) {
self = .init(
expectedReturns: expectedReturns,
timedInputs: inputs.map { timed(at: 0, value: $0) },
generator: generator
)
}
init(
expectedReturns: Int,
inputs: Value...,
generator: @escaping (ReactiveOperatorContext, Signal<Value>) -> Signal<ReturnValues>
) {
self = .init(expectedReturns: expectedReturns, inputs: inputs, generator: generator)
}
}
|
mit
|
b1f7337ff76d68e80a1b90c465bb2077
| 26.090909 | 96 | 0.715604 | 3.475219 | false | false | false | false |
behrang/YamlSwift
|
Sources/Yaml/Yaml.swift
|
2
|
6927
|
import Foundation
public enum Yaml: Hashable {
case null
case bool(Bool)
case int(Int)
case double(Double)
case string(String)
case array([Yaml])
case dictionary([Yaml: Yaml])
static public func == (lhs: Yaml, rhs: Yaml) -> Bool {
switch (lhs, rhs) {
case (.null, .null):
return true
case (.bool(let lv), .bool(let rv)):
return lv == rv
case (.int(let lv), .int(let rv)):
return lv == rv
case (.int(let lv), .double(let rv)):
return Double(lv) == rv
case (.double(let lv), .double(let rv)):
return lv == rv
case (.double(let lv), .int(let rv)):
return lv == Double(rv)
case (.string(let lv), .string(let rv)):
return lv == rv
case (.array(let lv), .array(let rv)):
return lv == rv
case (.dictionary(let lv), .dictionary(let rv)):
return lv == rv
default:
return false
}
}
// unary `-` operator
static public prefix func - (value: Yaml) -> Yaml {
switch value {
case .int(let v):
return .int(-v)
case .double(let v):
return .double(-v)
default:
fatalError("`-` operator may only be used on .int or .double Yaml values")
}
}
}
extension Yaml {
public enum ResultError: Error {
case message(String?)
}
}
extension Yaml: ExpressibleByNilLiteral {
public init(nilLiteral: ()) {
self = .null
}
}
extension Yaml: ExpressibleByBooleanLiteral {
public init(booleanLiteral: BooleanLiteralType) {
self = .bool(booleanLiteral)
}
}
extension Yaml: ExpressibleByIntegerLiteral {
public init(integerLiteral: IntegerLiteralType) {
self = .int(integerLiteral)
}
}
extension Yaml: ExpressibleByFloatLiteral {
public init(floatLiteral: FloatLiteralType) {
self = .double(floatLiteral)
}
}
extension Yaml: ExpressibleByStringLiteral {
public init(stringLiteral: StringLiteralType) {
self = .string(stringLiteral)
}
public init(extendedGraphemeClusterLiteral: StringLiteralType) {
self = .string(extendedGraphemeClusterLiteral)
}
public init(unicodeScalarLiteral: StringLiteralType) {
self = .string(unicodeScalarLiteral)
}
}
extension Yaml: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Yaml...) {
self = .array(elements)
}
}
extension Yaml: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (Yaml, Yaml)...) {
var dictionary = [Yaml: Yaml]()
for (k, v) in elements {
dictionary[k] = v
}
self = .dictionary(dictionary)
}
}
extension Yaml: CustomStringConvertible {
public var description: String {
switch self {
case .null:
return "Null"
case .bool(let b):
return "Bool(\(b))"
case .int(let i):
return "Int(\(i))"
case .double(let f):
return "Double(\(f))"
case .string(let s):
return "String(\(s))"
case .array(let s):
return "Array(\(s))"
case .dictionary(let m):
return "Dictionary(\(m))"
}
}
}
extension Yaml {
public static func load (_ text: String) throws -> Yaml {
let result = tokenize(text) >>=- Context.parseDoc
if let value = result.value { return value } else { throw ResultError.message(result.error) }
}
public static func loadMultiple (_ text: String) throws -> [Yaml] {
let result = tokenize(text) >>=- Context.parseDocs
if let value = result.value { return value } else { throw ResultError.message(result.error) }
}
public static func debug (_ text: String) -> Yaml? {
let result = tokenize(text)
>>- { tokens in print("\n====== Tokens:\n\(tokens)"); return tokens }
>>=- Context.parseDoc
>>- { value -> Yaml in print("------ Doc:\n\(value)"); return value }
if let error = result.error {
print("~~~~~~\n\(error)")
}
return result.value
}
public static func debugMultiple (_ text: String) -> [Yaml]? {
let result = tokenize(text)
>>- { tokens in print("\n====== Tokens:\n\(tokens)"); return tokens }
>>=- Context.parseDocs
>>- { values -> [Yaml] in values.forEach {
v in print("------ Doc:\n\(v)")
}; return values }
if let error = result.error {
print("~~~~~~\n\(error)")
}
return result.value
}
}
extension Yaml {
public subscript(index: Int) -> Yaml {
get {
assert(index >= 0)
switch self {
case .array(let array):
if array.indices.contains(index) {
return array[index]
} else {
return .null
}
default:
return .null
}
}
set {
assert(index >= 0)
switch self {
case .array(let array):
let emptyCount = max(0, index + 1 - array.count)
let empty = [Yaml](repeating: .null, count: emptyCount)
var new = array
new.append(contentsOf: empty)
new[index] = newValue
self = .array(new)
default:
var array = [Yaml](repeating: .null, count: index + 1)
array[index] = newValue
self = .array(array)
}
}
}
public subscript(key: Yaml) -> Yaml {
get {
switch self {
case .dictionary(let dictionary):
return dictionary[key] ?? .null
default:
return .null
}
}
set {
switch self {
case .dictionary(let dictionary):
var new = dictionary
new[key] = newValue
self = .dictionary(new)
default:
var dictionary = [Yaml: Yaml]()
dictionary[key] = newValue
self = .dictionary(dictionary)
}
}
}
}
extension Yaml {
public var bool: Bool? {
switch self {
case .bool(let b):
return b
default:
return nil
}
}
public var int: Int? {
switch self {
case .int(let i):
return i
case .double(let f):
if Double(Int(f)) == f {
return Int(f)
} else {
return nil
}
default:
return nil
}
}
public var double: Double? {
switch self {
case .double(let f):
return f
case .int(let i):
return Double(i)
default:
return nil
}
}
public var string: String? {
switch self {
case .string(let s):
return s
default:
return nil
}
}
public var array: [Yaml]? {
switch self {
case .array(let array):
return array
default:
return nil
}
}
public var dictionary: [Yaml: Yaml]? {
switch self {
case .dictionary(let dictionary):
return dictionary
default:
return nil
}
}
public var count: Int? {
switch self {
case .array(let array):
return array.count
case .dictionary(let dictionary):
return dictionary.count
default:
return nil
}
}
}
|
mit
|
70516457b9f1c5b6e3d027e8b6870eef
| 22.013289 | 97 | 0.564891 | 4.118312 | false | false | false | false |
BalestraPatrick/TweetsCounter
|
Carthage/Checkouts/Swifter/Sources/JSON.swift
|
2
|
8538
|
//
// JSON.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public enum JSON : Equatable, CustomStringConvertible {
case string(String)
case number(Double)
case object(Dictionary<String, JSON>)
case array(Array<JSON>)
case bool(Bool)
case null
case invalid
public init(_ rawValue: Any) {
switch rawValue {
case let json as JSON:
self = json
case let array as [JSON]:
self = .array(array)
case let dict as [String: JSON]:
self = .object(dict)
case let data as Data:
do {
let object = try JSONSerialization.jsonObject(with: data, options: [])
self = JSON(object)
} catch {
self = .invalid
}
case let array as [Any]:
let newArray = array.map { JSON($0) }
self = .array(newArray)
case let dict as [String: Any]:
var newDict = [String: JSON]()
for (key, value) in dict {
newDict[key] = JSON(value)
}
self = .object(newDict)
case let string as String:
self = .string(string)
case let number as NSNumber:
self = number.isBoolean ? .bool(number.boolValue) : .number(number.doubleValue)
case _ as Optional<Any>:
self = .null
default:
assert(true, "This location should never be reached")
self = .invalid
}
}
public var string : String? {
guard case .string(let value) = self else {
return nil
}
return value
}
public var integer : Int? {
guard case .number(let value) = self else {
return nil
}
return Int(value)
}
public var double : Double? {
guard case .number(let value) = self else {
return nil
}
return value
}
public var object : [String: JSON]? {
guard case .object(let value) = self else {
return nil
}
return value
}
public var array : [JSON]? {
guard case .array(let value) = self else {
return nil
}
return value
}
public var bool : Bool? {
guard case .bool(let value) = self else {
return nil
}
return value
}
public subscript(key: String) -> JSON {
guard case .object(let dict) = self, let value = dict[key] else {
return .invalid
}
return value
}
public subscript(index: Int) -> JSON {
guard case .array(let array) = self, array.count > index else {
return .invalid
}
return array[index]
}
static func parse(jsonData: Data) throws -> JSON {
do {
let object = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
return JSON(object)
} catch {
throw SwifterError(message: "\(error)", kind: .jsonParseError)
}
}
static func parse(string : String) throws -> JSON {
do {
guard let data = string.data(using: .utf8, allowLossyConversion: false) else {
throw SwifterError(message: "Cannot parse invalid string", kind: .jsonParseError)
}
return try parse(jsonData: data)
} catch {
throw SwifterError(message: "\(error)", kind: .jsonParseError)
}
}
func stringify(_ indent: String = " ") -> String? {
guard self != .invalid else {
assert(true, "The JSON value is invalid")
return nil
}
return prettyPrint(indent, 0)
}
public var description: String {
guard let string = stringify() else {
return "<INVALID JSON>"
}
return string
}
private func prettyPrint(_ indent: String, _ level: Int) -> String {
let currentIndent = (0...level).map({ _ in "" }).joined(separator: indent)
let nextIndent = currentIndent + " "
switch self {
case .bool(let bool):
return bool ? "true" : "false"
case .number(let number):
return "\(number)"
case .string(let string):
return "\"\(string.replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\r", with: "").replacingOccurrences(of: "\n", with: "\\n"))\""
case .array(let array):
return "[\n" + array.map { "\(nextIndent)\($0.prettyPrint(indent, level + 1))" }.joined(separator: ",\n") + "\n\(currentIndent)]"
case .object(let dict):
return "{\n" + dict.map { "\(nextIndent)\"\($0)\" : \($1.prettyPrint(indent, level + 1))"}.joined(separator: ",\n") + "\n\(currentIndent)}"
case .null:
return "null"
case .invalid:
assert(true, "This should never be reached")
return ""
}
}
}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case (.null, .null):
return true
case (.bool(let lhsValue), .bool(let rhsValue)):
return lhsValue == rhsValue
case (.string(let lhsValue), .string(let rhsValue)):
return lhsValue == rhsValue
case (.number(let lhsValue), .number(let rhsValue)):
return lhsValue == rhsValue
case (.array(let lhsValue), .array(let rhsValue)):
return lhsValue == rhsValue
case (.object(let lhsValue), .object(let rhsValue)):
return lhsValue == rhsValue
default:
return false
}
}
extension JSON: ExpressibleByStringLiteral,
ExpressibleByIntegerLiteral,
ExpressibleByBooleanLiteral,
ExpressibleByFloatLiteral,
ExpressibleByArrayLiteral,
ExpressibleByDictionaryLiteral,
ExpressibleByNilLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
public init(dictionaryLiteral elements: (String, Any)...) {
let object = elements.reduce([String: Any]()) { $0 + [$1.0: $1.1] }
self.init(object)
}
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
private func +(lhs: [String: Any], rhs: [String: Any]) -> [String: Any] {
var lhs = lhs
for element in rhs {
lhs[element.key] = element.value
}
return lhs
}
private extension NSNumber {
var isBoolean: Bool {
return NSNumber(value: true).objCType == self.objCType
}
}
|
mit
|
59fddb6641c853eadeb3dbeb022c9c3e
| 28.139932 | 164 | 0.557742 | 4.680921 | false | false | false | false |
february29/Learning
|
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Range.swift
|
94
|
2562
|
//
// Range.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension Observable where Element : SignedInteger {
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RangeProducer<E>(start: start, count: count, scheduler: scheduler)
}
}
final fileprivate class RangeProducer<E: SignedInteger> : Producer<E> {
fileprivate let _start: E
fileprivate let _count: E
fileprivate let _scheduler: ImmediateSchedulerType
init(start: E, count: E, scheduler: ImmediateSchedulerType) {
if count < 0 {
rxFatalError("count can't be negative")
}
if start &+ (count - 1) < start {
rxFatalError("overflow of count")
}
_start = start
_count = count
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = RangeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final fileprivate class RangeSink<O: ObserverType> : Sink<O> where O.E: SignedInteger {
typealias Parent = RangeProducer<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in
if i < self._parent._count {
self.forwardOn(.next(self._parent._start + i))
recurse(i + 1)
}
else {
self.forwardOn(.completed)
self.dispose()
}
}
}
}
|
mit
|
d6951ddf05fbae987a1aa82574b191ae
| 34.082192 | 157 | 0.637251 | 4.54078 | false | false | false | false |
asifkhan99/swift-product
|
Sources/App/Middleware/ProductMiddleware.swift
|
1
|
1071
|
import HTTP
import JSON
class ProductMiddleware: Middleware {
func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
let response = try chain.respond(to: request)
guard let node = response.json?.node else { return response }
let modified = node.appendedUrl(for: request)
response.json = JSON(modified)
return response
}
}
extension Node {
fileprivate func appendedUrl(for request: Request) -> Node {
if let array = nodeArray {
let mapped = array.map { $0.appendedUrl(for: request) }
return Node(mapped)
}
guard
let id = self["id"]?.string,
let baseUrl = request.baseUrl
else { return self }
var node = self
let url = baseUrl + "products/\(id)"
node["url"] = .string(url)
return node
}
}
extension Request {
var baseUrl: String? {
guard let host = headers["Host"]?.finished(with: "/") else { return nil }
return "\(uri.scheme)://\(host)"
}
}
|
mit
|
c821ae8b05e5dec705da8d686d24a68e
| 27.184211 | 87 | 0.583567 | 4.371429 | false | false | false | false |
apple/swift-tools-support-core
|
Sources/TSCBasic/GraphAlgorithms.swift
|
1
|
5108
|
/*
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
*/
public enum GraphError: Error {
/// A cycle was detected in the input.
case unexpectedCycle
}
/// Compute the transitive closure of an input node set.
///
/// - Note: The relation is *not* assumed to be reflexive; i.e. the result will
/// not automatically include `nodes` unless present in the relation defined by
/// `successors`.
public func transitiveClosure<T>(
_ nodes: [T], successors: (T) throws -> [T]
) rethrows -> Set<T> {
var result = Set<T>()
// The queue of items to recursively visit.
//
// We add items post-collation to avoid unnecessary queue operations.
var queue = nodes
while let node = queue.popLast() {
for succ in try successors(node) {
if result.insert(succ).inserted {
queue.append(succ)
}
}
}
return result
}
/// Perform a topological sort of an graph.
///
/// This function is optimized for use cases where cycles are unexpected, and
/// does not attempt to retain information on the exact nodes in the cycle.
///
/// - Parameters:
/// - nodes: The list of input nodes to sort.
/// - successors: A closure for fetching the successors of a particular node.
///
/// - Returns: A list of the transitive closure of nodes reachable from the
/// inputs, ordered such that every node in the list follows all of its
/// predecessors.
///
/// - Throws: GraphError.unexpectedCycle
///
/// - Complexity: O(v + e) where (v, e) are the number of vertices and edges
/// reachable from the input nodes via the relation.
public func topologicalSort<T: Hashable>(
_ nodes: [T], successors: (T) throws -> [T]
) throws -> [T] {
// Implements a topological sort via recursion and reverse postorder DFS.
func visit(_ node: T,
_ stack: inout OrderedSet<T>, _ visited: inout Set<T>, _ result: inout [T],
_ successors: (T) throws -> [T]) throws {
// Mark this node as visited -- we are done if it already was.
if !visited.insert(node).inserted {
return
}
// Otherwise, visit each adjacent node.
for succ in try successors(node) {
guard stack.append(succ) else {
// If the successor is already in this current stack, we have found a cycle.
//
// FIXME: We could easily include information on the cycle we found here.
throw GraphError.unexpectedCycle
}
try visit(succ, &stack, &visited, &result, successors)
let popped = stack.removeLast()
assert(popped == succ)
}
// Add to the result.
result.append(node)
}
// FIXME: This should use a stack not recursion.
var visited = Set<T>()
var result = [T]()
var stack = OrderedSet<T>()
for node in nodes {
precondition(stack.isEmpty)
stack.append(node)
try visit(node, &stack, &visited, &result, successors)
let popped = stack.removeLast()
assert(popped == node)
}
return result.reversed()
}
/// Finds the first cycle encountered in a graph.
///
/// This method uses DFS to look for a cycle and immediately returns when a
/// cycle is encounted.
///
/// - Parameters:
/// - nodes: The list of input nodes to sort.
/// - successors: A closure for fetching the successors of a particular node.
///
/// - Returns: nil if a cycle is not found or a tuple with the path to the start of the cycle and the cycle itself.
public func findCycle<T: Hashable>(
_ nodes: [T],
successors: (T) throws -> [T]
) rethrows -> (path: [T], cycle: [T])? {
// Ordered set to hold the current traversed path.
var path = OrderedSet<T>()
var validNodes = Set<T>()
// Function to visit nodes recursively.
// FIXME: Convert to stack.
func visit(_ node: T, _ successors: (T) throws -> [T]) rethrows -> (path: [T], cycle: [T])? {
if validNodes.contains(node) { return nil }
// If this node is already in the current path then we have found a cycle.
if !path.append(node) {
let index = path.firstIndex(of: node)!
return (Array(path[path.startIndex..<index]), Array(path[index..<path.endIndex]))
}
for succ in try successors(node) {
if let cycle = try visit(succ, successors) {
return cycle
}
}
// No cycle found for this node, remove it from the path.
let item = path.removeLast()
assert(item == node)
validNodes.insert(node)
return nil
}
for node in nodes {
if let cycle = try visit(node, successors) {
return cycle
}
}
// Couldn't find any cycle in the graph.
return nil
}
|
apache-2.0
|
f7534d533d35ff98838913de7f023e76
| 33.053333 | 115 | 0.613156 | 4.186885 | false | false | false | false |
peigen/iLife
|
iLife/MyApps.swift
|
1
|
3806
|
//
// MyApps.swift
// iLife
//
// Created by zq on 14-7-9.
// Copyright (c) 2014 Peigen.info. All rights reserved.
//
class MyApps
{
var _country: String? = nil
func country() -> String
{
if (!_country)
{
_country = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as? String
}
return _country!;
}
func detectAppSchemes(successApp:(NSArray) -> Void,failApp:(NSError) -> Void)
{
var path = NSBundle.mainBundle().pathForResource("schemeApps", ofType: "json")
NSDataReadingOptions.DataReadingMappedIfSafe
var dataError : NSErrorPointer
var schemeAppsData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
var schemeAppsDictionary = NSJSONSerialization.JSONObjectWithData(schemeAppsData, options: .MutableContainers, error: nil) as NSDictionary
var appschemes = Array<NSDictionary>()
var appIdSuccess = NSMutableArray()
for scheme : AnyObject in schemeAppsDictionary.allKeys
{
var appIds = schemeAppsDictionary.objectForKey(scheme) as NSArray
var newScheme = scheme as String
newScheme = "\(scheme)://"
if(sysUrl.canOpenURLApp(newScheme))
{
for appId : AnyObject in appIds
{
if (!appIdSuccess.containsObject(appId))
{
appIdSuccess.addObject(appId)
appschemes += ["scheme":newScheme,"ids":appIds]
}
}
}
}
var appString = appIdSuccess.componentsJoinedByString(",")
var urlString = "http://itunes.apple.com/lookup?id=\(appString)&country=\(country())"
var manager :AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
manager.requestSerializer.timeoutInterval = 15;
manager.responseSerializer.acceptableContentTypes = NSSet(objects:"text/javascript")
manager.POST(urlString, parameters: nil, success:
{
operation,responseObject in
var resultDic = responseObject as NSDictionary
var resultAy = resultDic.objectForKey("results") as Array<NSDictionary>
var appsDic = NSMutableArray()
for result in resultAy
{
var trackViewUrl = result.objectForKey("trackViewUrl") as NSString
var appId = (((trackViewUrl.componentsSeparatedByString("?") as NSArray).objectAtIndex(0) as NSString).componentsSeparatedByString("id") as NSArray).objectAtIndex(1) as NSString
for dic in appschemes
{
var ids = dic.objectForKey("ids") as NSArray
var idsString = ids.componentsJoinedByString(",")
if(idsString.hasPrefix(appId))
{
var newDic = NSMutableDictionary(dictionary:result)
var scheme = dic.objectForKey("scheme") as String
newDic.setValue(scheme, forKey: "scheme")
appsDic.addObject(newDic)
}
}
}
successApp(appsDic)
}
, failure:
{
operation,error in
failApp(error)
})
}
}
|
gpl-3.0
|
0fea913f21f7ffde1c36fd3a4cf12575
| 34.570093 | 197 | 0.513137 | 6.022152 | false | false | false | false |
naoto0822/transient-watch-ios
|
TransientWatch/Presentation/ViewController/ChartViewController.swift
|
1
|
6645
|
//
// ChartViewController.swift
// TransientWatch
//
// Created by naoto yamaguchi on 2015/04/12.
// Copyright (c) 2015年 naoto yamaguchi. All rights reserved.
//
import UIKit
class ChartViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate {
// MARK: - Property
@IBOutlet weak var tableView: UITableView!
var astroObj: AstroObj?
var chartArray: [Chart] = []
var chartView = ChartView(frame: CGRectZero)
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = astroObj?.name
self.navigationController?.navigationBar.barStyle = .Black
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.setBackgroundImage(
UIImage(),
forBarMetrics: UIBarMetrics.DefaultPrompt
)
self.view.backgroundColor = UIColor.clearColor()
self.tableView.backgroundColor = UIColor.clearColor()
let backGroundImage = UIImage(named: "BackGround")
let imageView = UIImageView(image: backGroundImage)
imageView.frame = self.view.bounds
self.navigationController?.view.insertSubview(imageView, atIndex: 0)
self.tableView.dataSource = self
self.tableView.delegate = self
let nib = UINib(nibName: "ChartCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: "Chart")
let frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 300)
self.chartView = ChartView(frame: frame)
self.tableView.setParallaxHeaderView(
self.chartView,
mode: VGParallaxHeaderMode.TopFill,
height: 300
)
self.fetchChartData()
}
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Private
func fetchChartData() {
SVProgressHUD.show()
var id = 1
if let validId = self.astroObj?.id { id = validId }
ChartModel.GET(
id: id.description,
success: { (task: NSURLSessionDataTask!, array: Array<Chart>!) -> Void in
self.chartArray = array
let frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 300)
self.chartView.chartData = self.chartArray
dispatch_async(dispatch_get_main_queue(), {
self.chartView.drawChart(frame)
self.tableView.reloadData()
SVProgressHUD.showSuccessWithStatus("load success")
})
},
failure: { (task: NSURLSessionDataTask!, error: NSError!) -> Void in
SVProgressHUD.showErrorWithStatus("load error")
}
)
}
// MARK: - UITableView DataSource & Delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 70
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setPreservesSuperviewLayoutMargins:")) {
cell.preservesSuperviewLayoutMargins = false
}
if cell.respondsToSelector(Selector("setLayoutMargins:")) {
cell.layoutMargins = UIEdgeInsetsZero
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Chart") as ChartCell
cell.textLabel?.textColor = UIColor.whiteColor()
if indexPath.row == 0 {
cell.textLabel?.text = astroObj?.name
}
else if indexPath.row == 1 {
cell.sectionLabel.text = "Ra:"
cell.valueLabel.text = astroObj?.ra?.description
}
else if indexPath.row == 2 {
cell.sectionLabel.text = "Dec:"
cell.valueLabel.text = astroObj?.dec?.description
}
else if indexPath.row == 3 {
cell.sectionLabel.text = "Class:"
cell.valueLabel.text = astroObj?.astroClassId?.description
}
else if indexPath.row == 4 {
cell.sectionLabel.text = "Flux Chane:"
if let rate = self.astroObj?.fluxRate?.description {
cell.valueLabel.text = rate + "%"
}
}
else if indexPath.row == 5 {
cell.sectionLabel.text = "Date URL:"
cell.valueLabel.text = astroObj?.link
cell.accessoryType = .DisclosureIndicator
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 5 {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let browser = storyboard.instantiateViewControllerWithIdentifier("BrowserViewController") as BrowserViewController
if let url = self.astroObj?.link {
browser.url = NSURL(string: url)
}
self.navigationController?.pushViewController(browser, animated: true)
}
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
scrollView.shouldPositionParallaxHeader()
}
}
|
gpl-3.0
|
ef76431d96797dc07edb263dfdc6a29c
| 34.524064 | 126 | 0.609062 | 5.462993 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard
|
Pods/SlackKit/SlackKit/Sources/UserGroup.swift
|
2
|
2985
|
//
// UserGroup.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct UserGroup {
public let id: String?
internal(set) public var teamID: String?
public let isUserGroup: Bool?
internal(set) public var name: String?
internal(set) public var description: String?
internal(set) public var handle: String?
internal(set) public var isExternal: Bool?
public let dateCreated: Int?
internal(set) public var dateUpdated: Int?
internal(set) public var dateDeleted: Int?
internal(set) public var autoType: String?
public let createdBy: String?
internal(set) public var updatedBy: String?
internal(set) public var deletedBy: String?
internal(set) public var preferences: [String: AnyObject]?
internal(set) public var users: [String]?
internal(set) public var userCount: Int?
internal init?(userGroup: [String: AnyObject]?) {
id = userGroup?["id"] as? String
teamID = userGroup?["team_id"] as? String
isUserGroup = userGroup?["is_usergroup"] as? Bool
name = userGroup?["name"] as? String
description = userGroup?["description"] as? String
handle = userGroup?["handle"] as? String
isExternal = userGroup?["is_external"] as? Bool
dateCreated = userGroup?["date_create"] as? Int
dateUpdated = userGroup?["date_update"] as? Int
dateDeleted = userGroup?["date_delete"] as? Int
autoType = userGroup?["auto_type"] as? String
createdBy = userGroup?["created_by"] as? String
updatedBy = userGroup?["updated_by"] as? String
deletedBy = userGroup?["deleted_by"] as? String
preferences = userGroup?["prefs"] as? [String: AnyObject]
users = userGroup?["users"] as? [String]
if let count = userGroup?["user_count"] as? String {
userCount = Int(count)
}
}
}
|
gpl-3.0
|
10694d76dc952bed55271462ac63ff21
| 42.882353 | 80 | 0.688003 | 4.281205 | false | false | false | false |
Gathros/algorithm-archive
|
contents/euclidean_algorithm/code/swift/euclidean_algorithm.swift
|
2
|
522
|
func euclidSub(a: Int, b: Int) -> Int {
var a = abs(a)
var b = abs(b)
while (a != b) {
if (a > b) {
a -= b
} else {
b -= a
}
}
return a
}
func euclidMod(a: Int, b: Int) -> Int {
var a = abs(a);
var b = abs(b);
while (b != 0) {
let temp = b
b = a % b
a = temp
}
return a
}
func main() {
print(euclidMod(a: 64 * 67, b: 64 * 81))
print(euclidSub(a: 128 * 12, b: 128 * 77))
}
main()
|
mit
|
cb5ba90d6e7bc0f4d394a51dbf1f89f8
| 14.352941 | 46 | 0.37931 | 2.776596 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Loader/Pulse/PulseContainerView.swift
|
1
|
2602
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import RxCocoa
final class PulseContainerView: PassthroughView {
// MARK: Rx
var selection: Signal<Void> {
selectionRelay.asSignal()
}
private let selectionRelay = PublishRelay<Void>()
// MARK: - Properties
private let max: CGRect = .init(origin: .zero, size: .init(width: 32.0, height: 32.0))
private lazy var pulseAnimationView: PulseAnimationView = {
let animationView = PulseAnimationView(
diameter: self.frame.min(max).width
)
return animationView
}()
private lazy var feedbackGenerator: UIImpactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
private lazy var button: UIButton = {
let button = UIButton(frame: max)
button.addTarget(self, action: #selector(containerTapped(_:)), for: .touchUpInside)
return button
}()
// MARK: - Setup
init() {
super.init(frame: UIScreen.main.bounds)
addSubview(button)
addSubview(pulseAnimationView)
button.layoutToSuperviewCenter()
pulseAnimationView.layoutToSuperviewCenter()
pulseAnimationView.layout(size: CGSize(width: frame.min(max).width, height: frame.min(max).height))
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Selection
@objc private func containerTapped(_ sender: UIButton) {
feedbackGenerator.prepare()
feedbackGenerator.impactOccurred()
selectionRelay.accept(())
}
}
// MARK: - PulseContainerViewProtocol
extension PulseContainerView: PulseContainerViewProtocol {
func animate() {
let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeOut)
animator.addAnimations {
self.alpha = Visibility.visible.defaultAlpha
}
animator.addAnimations({
self.pulseAnimationView.animate()
}, delayFactor: 0.1)
animator.startAnimation()
}
func fadeOut() {
let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeIn)
animator.addAnimations {
let scale = CGAffineTransform(scaleX: 0.1, y: 0.1)
self.pulseAnimationView.transform = scale
}
animator.addAnimations({
self.alpha = Visibility.hidden.defaultAlpha
}, delayFactor: 0.1)
animator.addCompletion { _ in
self.removeFromSuperview()
}
animator.startAnimation()
}
}
|
lgpl-3.0
|
9791e80e5739551f43fb73ec981efd64
| 28.224719 | 108 | 0.647443 | 4.834572 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/CryptoAssets/Sources/EthereumKit/Models/EIP681URI.swift
|
1
|
5248
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import Foundation
import MoneyKit
import PlatformKit
import ToolKit
import WalletCore
/// Implementation of EIP 681 URI
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-681.md
public struct EIP681URI {
public enum Method: Equatable {
case send(amount: CryptoValue?, gasLimit: BigUInt?, gasPrice: BigUInt?)
case transfer(destination: String, amount: CryptoValue?)
public var amount: CryptoValue? {
switch self {
case .send(let amount, _, _):
return amount
case .transfer(_, let amount):
return amount
}
}
public var destination: String? {
switch self {
case .send:
return nil
case .transfer(let destination, _):
return destination
}
}
}
public let cryptoCurrency: CryptoCurrency
public let address: String
public let method: Method
public var amount: CryptoValue? {
method.amount
}
public init?(address: String, cryptoCurrency: CryptoCurrency) {
guard Self.validate(address: address) else {
return nil
}
if let erc20ContractAddress = cryptoCurrency.assetModel.kind.erc20ContractAddress {
self.address = erc20ContractAddress
method = .transfer(
destination: address,
amount: nil
)
} else if cryptoCurrency == .ethereum {
self.address = address
method = .send(amount: nil, gasLimit: nil, gasPrice: nil)
} else if cryptoCurrency == .polygon {
self.address = address
method = .send(amount: nil, gasLimit: nil, gasPrice: nil)
} else {
return nil
}
self.cryptoCurrency = cryptoCurrency
}
public init?(
url: String,
network: EVMNetwork,
enabledCurrenciesService: EnabledCurrenciesServiceAPI
) {
guard let parser = EIP681URIParser(string: url) else {
return nil
}
guard let cryptoCurrency = parser.cryptoCurrency(
enabledCurrenciesService: enabledCurrenciesService,
network: network
) else {
return nil
}
guard let method = parser.method.method(cryptoCurrency: cryptoCurrency) else {
return nil
}
guard Self.validate(address: parser.address) else {
return nil
}
guard Self.validate(method: method) else {
return nil
}
self.init(cryptoCurrency: cryptoCurrency, address: parser.address, method: method)
}
init(cryptoCurrency: CryptoCurrency, address: String, method: EIP681URI.Method) {
self.cryptoCurrency = cryptoCurrency
self.address = address
self.method = method
}
static func validate(method: Method) -> Bool {
switch method {
case .send:
return true
case .transfer(let address, _):
return validate(address: address)
}
}
static func validate(address: String) -> Bool {
WalletCore.CoinType.ethereum.validate(address: address)
}
}
extension EIP681URIParser {
/// From a EIP681URIParser, returns correct CryptoCurrency.
func cryptoCurrency(
enabledCurrenciesService: EnabledCurrenciesServiceAPI,
network: EVMNetwork
) -> CryptoCurrency? {
switch method {
case .send:
// If this is a 'send', then we are sending Ethereum.
return network.cryptoCurrency
case .transfer:
// If this is a 'transfer', then we need to find which token we are sending.
// We do this by matching 'address' with one of the coins contract address.
return enabledCurrenciesService.allEnabledCryptoCurrencies
.first { cryptoCurrency in
cryptoCurrency.assetModel.kind.erc20ContractAddress?
.caseInsensitiveCompare(address) == .orderedSame
}
}
}
}
extension EIP681URIParser.Method {
func method(cryptoCurrency: CryptoCurrency) -> EIP681URI.Method? {
switch self {
case .send(let amount, let gasLimit, let gasPrice):
return .send(
amount: amount
.flatMap(BigInt.init(scientificNotation:))
.flatMap { amount in
CryptoValue(amount: amount, currency: cryptoCurrency)
},
gasLimit: gasLimit.flatMap { BigUInt($0) },
gasPrice: gasPrice.flatMap { BigUInt($0) }
)
case .transfer(let address, let amount):
guard let address = address else {
return nil
}
return .transfer(
destination: address,
amount: amount
.flatMap(BigInt.init(scientificNotation:))
.flatMap { amount in
CryptoValue(amount: amount, currency: cryptoCurrency)
}
)
}
}
}
|
lgpl-3.0
|
7e5249634cf39e8f07ae523a614d92f2
| 31.388889 | 91 | 0.572518 | 5.16437 | false | false | false | false |
spark/photon-tinker-ios
|
Photon-Tinker/Mesh/Gen3SetupEncryptionManager.swift
|
1
|
3926
|
//
// Created by Raimundas Sakalauskas on 23/08/2018.
// Copyright (c) 2018 Particle. All rights reserved.
//
import Foundation
import mbedTLSWrapper
class Gen3SetupEncryptionManager: NSObject {
private var cipher:AesCcmWrapper
private var key:Data
private var reqNonce:Data
private var repNonce:Data
required init(derivedSecret: Data) {
key = derivedSecret.subdata(in: 0..<16)
reqNonce = derivedSecret.subdata(in: 16..<24)
repNonce = derivedSecret.subdata(in: 24..<32)
cipher = AesCcmWrapper(key: key)!
super.init()
}
func getRequestNonce(requestId: UInt32) -> Data {
var data = Data()
var reqIdLe = requestId.littleEndian
data.append(UInt8(reqIdLe & 0xff))
data.append(UInt8((reqIdLe >> 8) & 0xff))
data.append(UInt8((reqIdLe >> 16) & 0xff))
data.append(UInt8((reqIdLe >> 24) & 0xff))
data.append(reqNonce)
return data
}
func getReplyNonce(requestId: UInt32) -> Data {
var data = Data()
var reqIdLe = requestId.littleEndian
data.append(UInt8(reqIdLe & 0xff))
data.append(UInt8((reqIdLe >> 8) & 0xff))
data.append(UInt8((reqIdLe >> 16) & 0xff))
data.append(UInt8(((reqIdLe >> 24) & 0xff) | 0x80))
data.append(repNonce)
return data
}
func encrypt(_ msg: RequestMessage) -> Data {
var requestId = UInt32(msg.id)
var outputData = Data()
var dataToEncrypt = Data()
//size - store it in output data to be used as additional data during the encryption process
var leValue = UInt16(msg.data.count).littleEndian
outputData.append(UnsafeBufferPointer(start: &leValue, count: 1))
//requestId
leValue = msg.id.littleEndian
dataToEncrypt.append(UnsafeBufferPointer(start: &leValue, count: 1))
//type
leValue = msg.type.rawValue.littleEndian
dataToEncrypt.append(UnsafeBufferPointer(start: &leValue, count: 1))
//reserved for future use
dataToEncrypt.append(Data(repeating: 0, count: 2))
//payload
dataToEncrypt.append(msg.data)
var tag:NSData? = nil
outputData.append(cipher.encryptData(dataToEncrypt, nonce: getRequestNonce(requestId: requestId), add: outputData, tag: &tag, tagSize: 8)!)
outputData.append(tag as! Data)
return outputData
}
//decrypt part assumes that it will decrypt
//the reply to previously encrypted request
func decrypt(_ data: Data, messageId: UInt16) -> ReplyMessage {
var data = data
//read data
var sizeData = data.subdata(in: 0..<2)
var size: Int16 = data.withUnsafeBytes { (pointer: UnsafePointer<Int16>) -> Int16 in
return Int16(pointer[0])
}
var leSize = size.littleEndian
data.removeSubrange(0..<2)
//read encrypted data
var dataToDecrypt = data.subdata(in: 0..<6+Int(size))
data.removeSubrange(0..<6+Int(size))
//remaining part is tag
var tag = data
//try to decrypt
var replNonce = getReplyNonce(requestId: UInt32(messageId))
var decryptedData = cipher.decryptData(dataToDecrypt, nonce: replNonce, add: sizeData, tag: tag)!
var rm = ReplyMessage(id: 0, result: .NONE, data: Data())
//get id
rm.id = decryptedData.withUnsafeBytes { (pointer: UnsafePointer<UInt16>) -> UInt16 in
return UInt16(pointer[0])
}
decryptedData.removeSubrange(0..<2)
//get type
rm.result = ControlReplyErrorType(rawValue: decryptedData.withUnsafeBytes { (pointer: UnsafePointer<Int32>) -> Int32 in
return Int32(pointer[0])
}) ?? ControlReplyErrorType.INVALID_UNKNOWN
decryptedData.removeSubrange(0..<4)
//get data
rm.data = decryptedData
return rm
}
}
|
apache-2.0
|
2ee534586d29cf0e3a39d08dd821abc4
| 29.671875 | 147 | 0.625064 | 4.014315 | false | false | false | false |
Jnosh/swift
|
stdlib/public/core/UTFEncoding.swift
|
2
|
3351
|
//===--- UTFEncoding.swift - Common guts of the big 3 UnicodeEncodings ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// These components would be internal if it were possible to use internal
// protocols to supply public conformance requirements.
//
//===----------------------------------------------------------------------===//
public protocol _UTFParser {
associatedtype Encoding : _UnicodeEncoding_
func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8)
func _bufferedScalar(bitCount: UInt8) -> _UIntBuffer<UInt32, Encoding.CodeUnit>
var _buffer: _UIntBuffer<UInt32, Encoding.CodeUnit> { get set }
}
extension _UTFParser
where Encoding.EncodedScalar == _UIntBuffer<UInt32, Encoding.CodeUnit> {
@inline(__always)
public mutating func parseScalar<I : IteratorProtocol>(
from input: inout I
) -> Unicode.ParseResult<Encoding.EncodedScalar>
where I.Element == Encoding.CodeUnit {
// Bufferless single-scalar fastpath.
if _fastPath(_buffer.isEmpty) {
guard let codeUnit = input.next() else { return .emptyInput }
// ASCII, return immediately.
if Encoding._isScalar(codeUnit) {
return .valid(Encoding.EncodedScalar(containing: codeUnit))
}
// Non-ASCII, proceed to buffering mode.
_buffer.append(codeUnit)
} else if Encoding._isScalar(
Encoding.CodeUnit(extendingOrTruncating: _buffer._storage)
) {
// ASCII in _buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
let codeUnit = Encoding.CodeUnit(extendingOrTruncating: _buffer._storage)
_buffer.remove(at: _buffer.startIndex)
return .valid(Encoding.EncodedScalar(containing: codeUnit))
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
repeat {
if let codeUnit = input.next() {
_buffer.append(codeUnit)
} else {
if _buffer.isEmpty { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _buffer.count < _buffer.capacity
// Find one unicode scalar.
let (isValid, scalarBitCount) = _parseMultipleCodeUnits()
_sanityCheck(scalarBitCount % numericCast(Encoding.CodeUnit.bitWidth) == 0)
_sanityCheck(1...4 ~= scalarBitCount / 8)
_sanityCheck(scalarBitCount <= _buffer._bitCount)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let encodedScalar = _bufferedScalar(bitCount: scalarBitCount)
_buffer._storage = UInt32(
// widen to 64 bits so that we can empty the buffer in the 4-byte case
extendingOrTruncating: UInt64(_buffer._storage) &>> scalarBitCount)
_buffer._bitCount = _buffer._bitCount &- scalarBitCount
if _fastPath(isValid) {
return .valid(encodedScalar)
}
return .error(
length: Int(scalarBitCount / numericCast(Encoding.CodeUnit.bitWidth)))
}
}
|
apache-2.0
|
5318167fc1aad28fdfc333d7885226d8
| 37.517241 | 81 | 0.655924 | 4.528378 | false | false | false | false |
ldt25290/MyInstaMap
|
ThirdParty/Alamofire/Source/ParameterEncoding.swift
|
1
|
17733
|
//
// ParameterEncoding.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// HTTP method definitions.
///
/// See https://tools.ietf.org/html/rfc7231#section-4.3
public enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
// MARK: -
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
/// A type used to define how a set of parameters are applied to a `URLRequest`.
public protocol ParameterEncoding {
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
///
/// - returns: The encoded request.
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
// MARK: -
/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
/// the HTTP body depends on the destination of the encoding.
///
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
/// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode
/// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending
/// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
public struct URLEncoding: ParameterEncoding {
// MARK: Helper Types
/// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
/// resulting URL request.
///
/// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
/// requests and sets as the HTTP body for requests with any other HTTP method.
/// - queryString: Sets or appends encoded query string result to existing query string.
/// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
public enum Destination {
case methodDependent, queryString, httpBody
}
// MARK: Properties
/// Returns a default `URLEncoding` instance.
public static var `default`: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.methodDependent` destination.
public static var methodDependent: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.queryString` destination.
public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
/// Returns a `URLEncoding` instance with an `.httpBody` destination.
public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
/// The destination defining where the encoded query string is to be applied to the URL request.
public let destination: Destination
// MARK: Initialization
/// Creates a `URLEncoding` instance using the specified destination.
///
/// - parameter destination: The destination defining where the encoded query string is to be applied.
///
/// - returns: The new `URLEncoding` instance.
public init(destination: Destination = .methodDependent) {
self.destination = destination
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
}
return urlRequest
}
/// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
///
/// - parameter key: The key of the query component.
/// - parameter value: The value of the query component.
///
/// - returns: The percent-escaped, URL encoded query string components.
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: "\(key)[]", value: value)
}
} else if let value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape((value.boolValue ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
} else if let bool = value as? Bool {
components.append((escape(key), escape((bool ? "1" : "0"))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string[range]
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring)
index = endIndex
}
}
return escaped
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
switch destination {
case .queryString:
return true
case .httpBody:
return false
default:
break
}
switch method {
case .get, .head, .delete:
return true
default:
return false
}
}
}
// MARK: -
/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
public struct JSONEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncoding { return JSONEncoding() }
/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions
// MARK: Initialization
/// Creates a `JSONEncoding` instance using the specified options.
///
/// - parameter options: The options for writing the parameters as JSON data.
///
/// - returns: The new `JSONEncoding` instance.
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
/// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
///
/// - parameter urlRequest: The request to apply the JSON object to.
/// - parameter jsonObject: The JSON object to apply to the request.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let jsonObject = jsonObject else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
/// field of an encoded request is set to `application/x-plist`.
public struct PropertyListEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a default `PropertyListEncoding` instance.
public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
/// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
/// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
/// The property list serialization format.
public let format: PropertyListSerialization.PropertyListFormat
/// The options for writing the parameters as plist data.
public let options: PropertyListSerialization.WriteOptions
// MARK: Initialization
/// Creates a `PropertyListEncoding` instance using the specified format and options.
///
/// - parameter format: The property list serialization format.
/// - parameter options: The options for writing the parameters as plist data.
///
/// - returns: The new `PropertyListEncoding` instance.
public init(
format: PropertyListSerialization.PropertyListFormat = .xml,
options: PropertyListSerialization.WriteOptions = 0)
{
self.format = format
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try PropertyListSerialization.data(
fromPropertyList: parameters,
format: format,
options: options
)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
extension NSNumber {
fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
|
mit
|
e78b92343b271668b8535e3d51dabe52
| 40.048611 | 123 | 0.646027 | 5.09862 | false | false | false | false |
karwa/swift-corelibs-foundation
|
Foundation/NSError.swift
|
3
|
9338
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public let NSCocoaErrorDomain: String = "NSCocoaErrorDomain"
public let NSPOSIXErrorDomain: String = "NSPOSIXErrorDomain"
public let NSOSStatusErrorDomain: String = "NSOSStatusErrorDomain"
public let NSMachErrorDomain: String = "NSMachErrorDomain"
public let NSUnderlyingErrorKey: String = "NSUnderlyingError"
public let NSLocalizedDescriptionKey: String = "NSLocalizedDescription"
public let NSLocalizedFailureReasonErrorKey: String = "NSLocalizedFailureReason"
public let NSLocalizedRecoverySuggestionErrorKey: String = "NSLocalizedRecoverySuggestion"
public let NSLocalizedRecoveryOptionsErrorKey: String = "NSLocalizedRecoveryOptions"
public let NSRecoveryAttempterErrorKey: String = "NSRecoveryAttempter"
public let NSHelpAnchorErrorKey: String = "NSHelpAnchor"
public let NSStringEncodingErrorKey: String = "NSStringEncodingErrorKey"
public let NSURLErrorKey: String = "NSURL"
public let NSFilePathErrorKey: String = "NSFilePathErrorKey"
public class NSError : NSObject, NSCopying, NSSecureCoding, NSCoding {
typealias CFType = CFError
internal var _cfObject: CFType {
return CFErrorCreate(kCFAllocatorSystemDefault, domain._cfObject, code, nil)
}
// ErrorType forbids this being internal
public var _domain: String
public var _code: Int
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
private var _userInfo: [String : Any]?
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
public init(domain: String, code: Int, userInfo dict: [String : Any]?) {
_domain = domain
_code = code
_userInfo = dict
}
public required init?(coder aDecoder: NSCoder) {
if aDecoder.allowsKeyedCoding {
_code = aDecoder.decodeIntegerForKey("NSCode")
_domain = aDecoder.decodeObjectOfClass(NSString.self, forKey: "NSDomain")!._swiftObject
if let info = aDecoder.decodeObjectOfClasses([NSSet.self, NSDictionary.self, NSArray.self, NSString.self, NSNumber.self, NSData.self, NSURL.self], forKey: "NSUserInfo") as? NSDictionary {
var filteredUserInfo = [String : Any]()
// user info must be filtered so that the keys are all strings
info.enumerateKeysAndObjectsUsingBlock() {
if let key = $0.0 as? NSString {
filteredUserInfo[key._swiftObject] = $0.1
}
}
_userInfo = filteredUserInfo
}
} else {
var codeValue: Int32 = 0
aDecoder.decodeValueOfObjCType("i", at: &codeValue)
_code = Int(codeValue)
_domain = (aDecoder.decodeObject() as? NSString)!._swiftObject
if let info = aDecoder.decodeObject() as? NSDictionary {
var filteredUserInfo = [String : Any]()
// user info must be filtered so that the keys are all strings
info.enumerateKeysAndObjectsUsingBlock() {
if let key = $0.0 as? NSString {
filteredUserInfo[key._swiftObject] = $0.1
}
}
_userInfo = filteredUserInfo
}
}
}
public static func supportsSecureCoding() -> Bool {
return true
}
public func encodeWithCoder(_ aCoder: NSCoder) {
if aCoder.allowsKeyedCoding {
aCoder.encodeObject(_domain.bridge(), forKey: "NSDomain")
aCoder.encodeInt(Int32(_code), forKey: "NSCode")
aCoder.encodeObject(_userInfo?.bridge(), forKey: "NSUserInfo")
} else {
var codeValue: Int32 = Int32(self._code)
aCoder.encodeValueOfObjCType("i", at: &codeValue)
aCoder.encodeObject(self._domain.bridge())
aCoder.encodeObject(self._userInfo?.bridge())
}
}
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(_ zone: NSZone) -> AnyObject {
return self
}
public var domain: String {
return _domain
}
public var code: Int {
return _code
}
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
public var userInfo: [String : Any] {
if let info = _userInfo {
return info
} else {
return Dictionary<String, Any>()
}
}
public var localizedDescription: String {
let desc = userInfo[NSLocalizedDescriptionKey] as? String
return desc ?? "The operation could not be completed"
}
public var localizedFailureReason: String? {
return userInfo[NSLocalizedFailureReasonErrorKey] as? String
}
public var localizedRecoverySuggestion: String? {
return userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String
}
public var localizedRecoveryOptions: [String]? {
return userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String]
}
public var recoveryAttempter: AnyObject? {
return userInfo[NSRecoveryAttempterErrorKey] as? AnyObject
}
public var helpAnchor: String? {
return userInfo[NSHelpAnchorErrorKey] as? String
}
internal typealias NSErrorProvider = (error: NSError, key: String) -> AnyObject?
internal static var userInfoProviders = [String: NSErrorProvider]()
public class func setUserInfoValueProviderForDomain(_ errorDomain: String, provider: ((NSError, String) -> AnyObject?)?) {
NSError.userInfoProviders[errorDomain] = provider
}
public class func userInfoValueProviderForDomain(_ errorDomain: String) -> ((NSError, String) -> AnyObject?)? {
return NSError.userInfoProviders[errorDomain]
}
}
extension NSError : ErrorProtocol { }
extension NSError : _CFBridgable { }
extension CFError : _NSBridgable {
typealias NSType = NSError
internal var _nsObject: NSType {
let userInfo = CFErrorCopyUserInfo(self)._swiftObject
var newUserInfo: [String: Any] = [:]
for (key, value) in userInfo {
if let key = key as? NSString {
newUserInfo[key._swiftObject] = value
}
}
return NSError(domain: CFErrorGetDomain(self)._swiftObject, code: CFErrorGetCode(self), userInfo: newUserInfo)
}
}
public protocol _ObjectTypeBridgeableErrorType : ErrorProtocol {
init?(_bridgedNSError: NSError)
}
public protocol __BridgedNSError : RawRepresentable, ErrorProtocol {
static var __NSErrorDomain: String { get }
}
@warn_unused_result
public func ==<T: __BridgedNSError where T.RawValue: SignedInteger>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax()
}
public extension __BridgedNSError where RawValue: SignedInteger {
public final var _domain: String { return Self.__NSErrorDomain }
public final var _code: Int { return Int(rawValue.toIntMax()) }
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self.__NSErrorDomain {
return nil
}
self.init(rawValue: RawValue(IntMax(_bridgedNSError.code)))
}
public final var hashValue: Int { return _code }
}
@warn_unused_result
public func ==<T: __BridgedNSError where T.RawValue: UnsignedInteger>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax()
}
public extension __BridgedNSError where RawValue: UnsignedInteger {
public final var _domain: String { return Self.__NSErrorDomain }
public final var _code: Int {
return Int(bitPattern: UInt(rawValue.toUIntMax()))
}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self.__NSErrorDomain {
return nil
}
self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code))))
}
public final var hashValue: Int { return _code }
}
public protocol _BridgedNSError : __BridgedNSError, Hashable {
// TODO: Was _NSErrorDomain, but that caused a module error.
static var __NSErrorDomain: String { get }
}
|
apache-2.0
|
ca7a6dfdf716f0c101906558dae62010
| 36.653226 | 199 | 0.657957 | 4.959108 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Examples/SciChartDemo/ShareChartSwiftExample/ShareChartSwiftExample/SCSDataManager.swift
|
1
|
30982
|
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// SCSDataManager.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
import Foundation
import SciChart
import Accelerate
typealias OnNewData = (_ sender: SCSMultiPaneItem) -> Void
class SCSDataManager {
class func getLissajousCurve(dataSeries:SCIXyDataSeries, alpha:Double, beta:Double, delta:Double, count:Int){
// From http://en.wikipedia.org/wiki/Lissajous_curve
// x = Asin(at + d), y = Bsin(bt)
for i in 0..<count {
dataSeries.appendX(SCIGeneric(sin(alpha * Double(i) * 0.1 + delta)),
y: SCIGeneric(sin(beta * Double(i) * 0.1)))
}
}
class func getStraightLine(series:SCIXyDataSeries, gradient:(Double), yIntercept:(Double), pointCount:(Int)) {
for i in 0..<pointCount {
let x = Double(i) + 1;
series.appendX(SCIGeneric(x), y: SCIGeneric(gradient*x+yIntercept))
}
}
static fileprivate func generateXDateTimeSeries(with yValues: [Int]) -> SCIXyDataSeriesProtocol {
let dataSeries = SCIXyDataSeries(xType: .dateTime, yType: .double)
for i in 0..<yValues.count {
let date = Date(timeIntervalSince1970: Double(60 * 60 * 24 * i))
let xData = SCIGeneric(date)
let value: Double = CDouble(yValues[i])
dataSeries.appendX(xData, y: SCIGeneric(value))
}
dataSeries.dataDistributionCalculator = SCIUserDefinedDistributionCalculator()
return dataSeries
}
static open func getRandomDoubleSeries(data: SCIXyDataSeriesProtocol, count: Int) {
let amplitude = drand48() + 0.5;
let freq = Double.pi * (drand48() + 0.5) * 10;
let offset = drand48() - 0.5;
for i in 0..<count {
data.appendX(SCIGeneric(i), y: SCIGeneric(offset + amplitude + sin(freq * Double(i))))
}
}
static open func getExponentialCurve(data: SCIXyDataSeriesProtocol, count: Int, exponent: Double) {
var x = 0.00001;
var y = 0.0;
let fudgeFactor = 1.4;
for i in 0..<count {
x *= fudgeFactor
y = pow(Double(i + 1), exponent)
data.appendX(SCIGeneric(x), y: SCIGeneric(y))
}
}
static open func porkDataSeries() -> SCIDataSeriesProtocol {
let porkData = [10, 13, 7, 16, 4, 6, 20, 14, 16, 10, 24, 11]
let dataSeries = generateXDateTimeSeries(with: porkData)
dataSeries.seriesName = "Pork"
return dataSeries
}
static open func tomatoesDataSeries() -> SCIDataSeriesProtocol {
let tomatoesData = [7, 30, 27, 24, 21, 15, 17, 26, 22, 28, 21, 22]
let dataSeries = generateXDateTimeSeries(with: tomatoesData)
dataSeries.seriesName = "Tomatoes"
return dataSeries
}
static open func cucumberDataSeries() -> SCIDataSeriesProtocol {
let cucumberData = [16, 10, 9, 8, 22, 14, 12, 27, 25, 23, 17, 17]
let dataSeries = generateXDateTimeSeries(with: cucumberData)
dataSeries.seriesName = "Cucumber"
return dataSeries
}
static open func vealDataSeries() -> SCIDataSeriesProtocol {
let vealData = [12, 17, 21, 15, 19, 18, 13, 21, 22, 20, 5, 10]
let dataSeries = generateXDateTimeSeries(with: vealData)
dataSeries.seriesName = "Veal"
return dataSeries
}
static open func pepperDataSeries() -> SCIDataSeriesProtocol {
let pepperData = [7, 24, 21, 11, 19, 17, 14, 27, 26, 22, 28, 16]
let dataSeries = generateXDateTimeSeries(with: pepperData)
dataSeries.seriesName = "Pepper"
return dataSeries
}
static open func stackedBarChartSeries() -> [SCIDataSeriesProtocol] {
var dataSeries = [SCIDataSeriesProtocol]()
var yValues_1 = [0.0, 0.1, 0.2, 0.4, 0.8, 1.1, 1.5, 2.4, 4.6, 8.1, 11.7, 14.4, 16.0, 13.7, 10.1, 6.4, 3.5, 2.5, 5.4, 6.4, 7.1, 8.0, 9.0]
var yValues_2 = [2.0, 10.1, 10.2, 10.4, 10.8, 1.1, 11.5, 3.4, 4.6, 0.1, 1.7, 14.4, 16.0, 13.7, 10.1, 6.4, 3.5, 2.5, 1.4, 0.4, 10.1, 0.0, 0.0]
var yValues_3 = [20.0, 4.1, 4.2, 10.4, 10.8, 1.1, 11.5, 3.4, 4.6, 5.1, 5.7, 14.4, 16.0, 13.7, 10.1, 6.4, 3.5, 2.5, 1.4, 10.4, 8.1, 10.0, 15.0]
let data1 = SCIXyDataSeries(xType: .double, yType: .double)
let data2 = SCIXyDataSeries(xType: .double, yType: .double)
let data3 = SCIXyDataSeries(xType: .double, yType: .double)
for i in 0..<yValues_1.count {
data1.appendX(SCIGeneric(i), y: SCIGeneric(CDouble(yValues_1[i])))
data2.appendX(SCIGeneric(i), y: SCIGeneric(CDouble(yValues_2[i])))
data3.appendX(SCIGeneric(i), y: SCIGeneric(CDouble(yValues_3[i])))
}
dataSeries.append(data1)
dataSeries.append(data2)
dataSeries.append(data3)
return dataSeries
}
static open func stackedSideBySideDataSeries() -> [SCIDataSeries] {
var china : [Double] = [1.269, 1.330, 1.356, 1.304]
var india : [Double] = [1.004, 1.173, 1.236, 1.656]
var usa : [Double] = [0.282, 0.310, 0.319, 0.439]
var indonesia : [Double] = [0.214, 0.243, 0.254, 0.313]
var brazil : [Double] = [0.176, 0.201, 0.203, 0.261]
var pakistan : [Double] = [0.146, 0.184, 0.196, 0.276]
var nigeria : [Double] = [0.123, 0.152, 0.177, 0.264]
var bangladesh : [Double] = [0.130, 0.156, 0.166, 0.234]
var russia : [Double] = [0.147, 0.139, 0.142, 0.109]
var japan : [Double] = [0.126, 0.127, 0.127, 0.094]
var restOfWorld : [Double] = [2.466, 2.829, 3.005, 4.306]
let data1 = SCIXyDataSeries(xType: .double, yType: .double)
let data2 = SCIXyDataSeries(xType: .double, yType: .double)
let data3 = SCIXyDataSeries(xType: .double, yType: .double)
let data4 = SCIXyDataSeries(xType: .double, yType: .double)
let data5 = SCIXyDataSeries(xType: .double, yType: .double)
let data6 = SCIXyDataSeries(xType: .double, yType: .double)
let data7 = SCIXyDataSeries(xType: .double, yType: .double)
let data8 = SCIXyDataSeries(xType: .double, yType: .double)
let data9 = SCIXyDataSeries(xType: .double, yType: .double)
let data10 = SCIXyDataSeries(xType: .double, yType: .double)
let data11 = SCIXyDataSeries(xType: .double, yType: .double)
let data12 = SCIXyDataSeries(xType: .double, yType: .double)
for i in 0..<4 {
var xValue: Double = 2000
if i == 1 {
xValue = 2010
} else if i == 2 {
xValue = 2014
} else if i == 3 {
xValue = 2050
}
data1.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(china[i])))
if i != 2 {
data2.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(india[i])))
data3.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(usa[i])))
data4.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(indonesia[i])))
data5.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(brazil[i])))
} else {
data2.appendX(SCIGeneric(xValue), y: SCIGeneric(Double.nan))
data3.appendX(SCIGeneric(xValue), y: SCIGeneric(Double.nan))
data4.appendX(SCIGeneric(xValue), y: SCIGeneric(Double.nan))
data5.appendX(SCIGeneric(xValue), y: SCIGeneric(Double.nan))
}
data6.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(pakistan[i])))
data7.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(nigeria[i])))
data8.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(bangladesh[i])))
data9.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(russia[i])))
data10.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(japan[i])))
data11.appendX(SCIGeneric(xValue), y: SCIGeneric(CDouble(restOfWorld[i])))
let asia = china[i] + india[i] + indonesia[i]
let asia2 = bangladesh[i] + japan[i]
let newWorld = usa[i] + brazil[i]
let rest = pakistan[i] + nigeria[i] + russia[i] + restOfWorld[i]
let all = asia+newWorld+rest+asia2
data12.appendX(SCIGeneric(xValue), y: SCIGeneric(all))
}
let dataSeries = [data1, data2, data3, data4, data5, data6, data7, data8, data9, data10, data11, data12]
return dataSeries
}
class func getPriceIndu(dataSeries: SCIOhlcDataSeriesProtocol, fileName: String) {
if let resourcePath = Bundle.main.resourcePath {
let filePath = resourcePath + "/" + fileName + ".csv"
do {
let contentFile = try? String.init(contentsOfFile: filePath, encoding: String.Encoding.utf8)
let items = contentFile?.components(separatedBy: "\r\n")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LL/dd/yyyy"
for i in 0..<(items?.count)! - 1 {
let subItems = (items?[i].components(separatedBy: ","))! as [String]
let date:Date = dateFormatter.date(from: subItems[0])!
dataSeries.appendX(SCIGeneric(date),
open: SCIGeneric(Float(subItems[1])!),
high: SCIGeneric(Float(subItems[2])!),
low: SCIGeneric(Float(subItems[3])!),
close: SCIGeneric(Float(subItems[4])!))
}
}
}
}
static open func stackedVerticalColumnSeries() -> [SCIDataSeriesProtocol] {
return [porkDataSeries(), vealDataSeries(), tomatoesDataSeries(), cucumberDataSeries(), pepperDataSeries()]
}
static func loadData<DataSeriesType:SCIXyDataSeriesProtocol>(into dataSeries: DataSeriesType,
fileName: String,
startIndex: Int,
increment: Int,
reverse: Bool) {
if let resourcePath = Bundle.main.resourcePath {
let filePath = resourcePath + "/" + fileName + ".txt"
do {
let contentFile = try NSString(contentsOfFile: filePath, usedEncoding: nil) as String
let items = contentFile.components(separatedBy: "\n")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
if reverse {
var i = items.count - 1
while i >= startIndex {
let subItems = items[i].components(separatedBy: ",")
let date = dateFormatter.date(from: subItems[0])
let value = Float(subItems[1])
dataSeries.appendX(SCIGeneric(date!), y: SCIGeneric(value!))
i = i - increment
}
} else {
var i = startIndex
while i < items.count {
let subItems = items[i].components(separatedBy: ",")
let date = dateFormatter.date(from: subItems[0])
let value = Float(subItems[1])
dataSeries.appendX(SCIGeneric(date!), y: SCIGeneric(value!))
i = i + increment
}
}
} catch {
}
}
}
static func getTradeTicks(_ dataSeries: SCIXyzDataSeriesProtocol, fileName: String) {
if let resourcePath = Bundle.main.resourcePath {
let filePath = resourcePath + "/" + fileName + ".csv"
do {
let contentFile = try? String.init(contentsOfFile: filePath, encoding: String.Encoding.utf8)
let items = contentFile?.components(separatedBy: "\r\n")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss.s"
for i in 0..<(items?.count)! - 1 {
let subItems = (items?[i].components(separatedBy: ","))! as [String]
let date = dateFormatter.date(from: subItems[0])
let value = Float(subItems[1])
let zValue = Float(subItems[2])
dataSeries.appendX(SCIGeneric(date!), y: SCIGeneric(value!), z: SCIGeneric(zValue!))
}
}
}
}
static func putDataInto(_ dataSeries: SCIXyDataSeries) {
let dataCount = 20
var i = 0
while i <= dataCount {
let x = 10.0 * Float(i) / Float(dataCount)
let y = arc4random_uniform(UInt32(dataCount))
let xValue = Float(x)
let yValue = Float(y)
dataSeries.appendX(SCIGeneric(xValue), y: SCIGeneric(yValue))
i = i + 1
}
}
static func putFourierDataInto(_ dataSeries: SCIXyDataSeries) {
let dataCount = 1000
var i = 0
while i <= dataCount {
let x = Float(10.0 * Float(i) / Float(dataCount))
let y = 2 * sin(x) + 10
dataSeries.appendX(SCIGeneric(x), y: SCIGeneric(y))
i = i + 1
}
}
static func setFourierDataInto(_ dataSeries: SCIXyDataSeries, amplitude: (Double), phaseShift: (Double), count: (Int)) {
for i in 0..<count {
let time = 10 * Double(i) / Double(count);
let wn = 2 * .pi / Double(count / 10);
let y1 = sin(Double(i) * wn + phaseShift)
let y2 = 0.33 * sin(Double(i) * 3 * wn + phaseShift)
let y3 = 0.20 * sin(Double(i) * 5 * wn + phaseShift)
let y4 = 0.14 * sin(Double(i) * 7 * wn + phaseShift)
let y5 = 0.11 * sin(Double(i) * 9 * wn + phaseShift)
let y6 = 0.09 * sin(Double(i) * 11 * wn + phaseShift)
let y = .pi * amplitude * (y1 + y2 + y3 + y4 + y5 + y6);
dataSeries.appendX(SCIGeneric(time), y: SCIGeneric(y))
}
}
static func getFourierDataZoomed(_ dataSeries: SCIXyDataSeries, amplitude: (Double), phaseShift: (Double), xStart: (Double), xEnd: (Double), count: (Int)) {
self.setFourierDataInto(dataSeries, amplitude: amplitude, phaseShift: phaseShift, count: 5000)
var index0: Int = 0
var index1: Int = 0
for i in 0..<count {
if (SCIGenericDouble(dataSeries.xValues().value(at: Int32(i))) > xStart && index0 == 0) {
index0 = i;
}
if (SCIGenericDouble(dataSeries.xValues().value(at: Int32(i))) > xEnd && index1 == 0) {
index1 = i;
break;
}
}
dataSeries.xValues().removeRange(from: Int32(index1), count: Int32(count - index1))
dataSeries.yValues().removeRange(from: Int32(index1), count: Int32(count - index1))
dataSeries.xValues().removeRange(from: 0, count: Int32(index0))
dataSeries.yValues().removeRange(from: 0, count: Int32(index0))
}
static func randomize(_ min: Double, max: Double) -> Double {
return RandomUtil.nextDouble() * (max - min) + min
}
static open func loadPriceData(into dataSeries: SCIOhlcDataSeriesProtocol, fileName: String, isReversed: Bool, count: Int) {
let filePath = Bundle.main.path(forResource: fileName, ofType: "txt")!
let data = try! String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
let items = data.components(separatedBy: "\n")
var subItems = [String]()
if !isReversed {
for i in 0..<count {
subItems = items[i].components(separatedBy: ",")
dataSeries.appendX(SCIGeneric(i),
open: SCIGeneric(Float(subItems[1])!),
high: SCIGeneric(Float(subItems[2])!),
low: SCIGeneric(Float(subItems[3])!),
close: SCIGeneric(Float(subItems[4])!))
}
} else {
var j = 0
var i = count - 1
while i >= 0 {
subItems = items[i].components(separatedBy: ",")
dataSeries.appendX(SCIGeneric(j),
open: SCIGeneric(Float(subItems[1])!),
high: SCIGeneric(Float(subItems[2])!),
low: SCIGeneric(Float(subItems[3])!),
close: SCIGeneric(Float(subItems[4])!))
j += 1
i -= 1
}
}
}
static open func loadPaneStockData() -> [SCSMultiPaneItem] {
let count = 3000
let filePath = Bundle.main.path(forResource: "EURUSD_Daily", ofType: "txt")!
let data = try! String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
var items = data.components(separatedBy: "\n")
var subItems = [String]()
var array = [SCSMultiPaneItem]() /* capacity: count */
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
for i in 0..<count {
subItems = items[i].components(separatedBy: ",")
let item = SCSMultiPaneItem()
item.dateTime = dateFormatter.date(from: subItems[0])!
item.open = Double(subItems[1])!
item.high = Double(subItems[2])!
item.low = Double(subItems[3])!
item.close = Double(subItems[4])!
item.volume = Double(subItems[5])!
array.append(item)
}
return array
}
static open func loadThemeData() -> [SCSMultiPaneItem] {
let count = 250
let filePath = Bundle.main.path(forResource: "FinanceData", ofType: "txt")!
let data = try! String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
var items = data.components(separatedBy: "\n")
var subItems = [String]()
var array = [SCSMultiPaneItem]() /* capacity: count */
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
for i in 0..<count {
subItems = items[i].components(separatedBy: ",")
let item = SCSMultiPaneItem()
item.dateTime = dateFormatter.date(from: subItems[0])!
item.open = Double(subItems[1])!
item.high = Double(subItems[2])!
item.low = Double(subItems[3])!
item.close = Double(subItems[4])!
item.volume = Double(subItems[5])!
array.append(item)
}
return array
}
static open func loadData(into dataSeries: SCIXyDataSeriesProtocol, from fileName: String) {
let filePath = Bundle.main.path(forResource: fileName, ofType: "txt")!
let data = try! String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
let items = data.components(separatedBy: "\n")
for i in 0..<items.count {
dataSeries.appendX(SCIGeneric(i), y: SCIGeneric(Float(items[i])!))
}
}
static func getDampedSinewave(_ amplitude: Double, dampingFactor: Double, pointCount: Int32, freq: Int32) -> DoubleSeries {
return self.getDampedSinewave(0, amplitude: amplitude, phase: 0.0, dampingFactor: dampingFactor, pointCount: pointCount, freq: freq)
}
static func getDampedSinewave(_ pad: Int32, amplitude: Double, phase: Double, dampingFactor: Double, pointCount: Int32, freq: Int32) -> DoubleSeries {
let doubleSeries = DoubleSeries(capacity: pointCount)
for i in 0..<pad {
let time = 10 * Double(i) / Double(pointCount)
doubleSeries.addX(time, y: 0)
}
var i = pad
var j = 0
var mutableAmplitude = amplitude
while i < pointCount {
let time = 10.0 * Double(i) / Double(pointCount)
let wn = 2.0 * .pi / (Double(pointCount) / Double(freq))
let d: Double = mutableAmplitude * sin(Double(j) * wn + phase)
doubleSeries.addX(time, y: d)
mutableAmplitude *= (1.0 - dampingFactor)
i += 1
j += 1
}
return doubleSeries
}
static func getSinewave(_ amplitude: Double, phase: Double, pointCount: Int32, freq: Int32) -> DoubleSeries {
return self.getDampedSinewave(0, amplitude: amplitude, phase: phase, dampingFactor: 0, pointCount: pointCount, freq: freq)
}
static func getSinewave(_ amplitude: Double, phase: Double, pointCount: Int32) -> DoubleSeries {
return self.getSinewave(amplitude, phase: phase, pointCount: pointCount, freq: 10)
}
static func getNoisySinewave(_ amplitude: Double, phase: Double, pointCount: Int32, noiseAmplitude: Double) -> DoubleSeries {
let doubleSeries: DoubleSeries? = self.getSinewave(amplitude, phase: phase, pointCount: pointCount)
let yValues: SCIGenericType? = doubleSeries?.yValues
for i in 0..<pointCount {
let y = SCIGenericDoublePtr(yValues!)[Int(i)]
SCIGenericDoublePtr(yValues!)[Int(i)] = y + RandomUtil.nextDouble() * noiseAmplitude - noiseAmplitude * 0.5
}
return doubleSeries!
}
}
open class SCSMultiPaneItem {
var open = Double.nan
var high = Double.nan
var low = Double.nan
var close = Double.nan
var volume = Double.nan
var dateTime = Date()
}
open class SCSMcadPointItem {
var mcad = Double.nan
var signal = Double.nan
var divergence = Double.nan
}
class SCSMovingAverage {
var current: Double = 0.0
private var length: Int = 0
private var circIndex: Int = -1
private var filled: Bool = false
private var oneOverLength = Double.nan
private var circularBuffer: [Double]!
private var total: Double = 0.0
init(length: Int) {
self.length = length
oneOverLength = 1.0 / Double(length)
circularBuffer = [Double].init(repeating: 0.0, count: length)
}
func push(_ value: Double) -> SCSMovingAverage {
circIndex += 1
if circIndex == length {
circIndex = 0
}
let lostValue: Double = circIndex < circularBuffer.count ? Double(circularBuffer[circIndex]) : 0.0
circularBuffer[circIndex] = value
total += value
total -= lostValue
if !filled && circIndex != length - 1 {
current = Double.nan
return self
} else {
filled = true
}
current = total * oneOverLength
return self
}
func update(_ value: Double) {
let lostValue: Double = Double(circularBuffer[circIndex])
circularBuffer[circIndex] = (value)
// Maintain totals for Push function
total += value
total -= lostValue
// If not yet filled, just return. Current value should be double.NaN
if !filled {
current = Double.nan
return
}
// Compute the average
var average: Double = 0.0
for i in 0..<circularBuffer.count {
average += Double(circularBuffer[i])
}
current = average * oneOverLength
}
}
class SCSRandomPriceDataSource {
var updateData: OnNewData?
var newData: OnNewData?
private var timer: Timer?
private var Frequency: Double = 0.0
private var candleIntervalMinutes = 0
private var simulateDateGap = false
private var lastPriceBar: SCSMultiPaneItem!
private var initialPriceBar: SCSMultiPaneItem!
private var currentTime: Double = 0.0
private var updatesPerPrice = 0
private var currentUpdateCount = 0
private var openMarketTime = TimeInterval()
private var closeMarketTime = TimeInterval()
private var randomSeed = 0
private var timeInerval: Double = 0.0
init(candleIntervalMinutes: Int, simulateDateGap: Bool, timeInterval: Double, updatesPerPrice: Int, randomSeed: Int, startingPrice: Double, start startDate: Date) {
Frequency = 1.1574074074074073E-05
openMarketTime = 360
closeMarketTime = 720
self.candleIntervalMinutes = candleIntervalMinutes
self.simulateDateGap = simulateDateGap
self.updatesPerPrice = updatesPerPrice
self.timeInerval = timeInterval
self.initialPriceBar = SCSMultiPaneItem()
self.initialPriceBar.close = startingPrice
self.initialPriceBar.dateTime = startDate
self.lastPriceBar = SCSMultiPaneItem()
self.lastPriceBar.close = initialPriceBar.close
self.lastPriceBar.dateTime = initialPriceBar.dateTime
self.lastPriceBar.high = initialPriceBar.close
self.lastPriceBar.low = initialPriceBar.close
self.lastPriceBar.open = initialPriceBar.close
self.lastPriceBar.volume = 0
self.randomSeed = randomSeed
}
func startGeneratePriceBars() {
timer = Timer(timeInterval: timeInerval,
target: self,
selector: #selector(onTimerElapsed),
userInfo: nil,
repeats: true)
timer?.fire()
}
func stopGeneratePriceBars() {
if let timer = timer, timer.isValid {
timer.invalidate()
}
}
func isRunning() -> Bool {
if let timer = timer {
return timer.isValid
}
return false
}
func getNextData() -> SCSMultiPaneItem {
return getNextRandomPriceBar()
}
func getUpdateData() -> SCSMultiPaneItem {
let num: Double = lastPriceBar.close + (SCSDataManager.randomize(0, max: Double(randomSeed)) - 48) * (lastPriceBar.close / 1000.0)
let high: Double = num > lastPriceBar.high ? num : lastPriceBar.high
let low: Double = num < lastPriceBar.low ? num : lastPriceBar.low
let volumeInc = (SCSDataManager.randomize(0, max: Double(randomSeed)) * 3 + 2) * 0.5
self.lastPriceBar.high = high
self.lastPriceBar.low = low
self.lastPriceBar.close = num
self.lastPriceBar.volume += volumeInc
return lastPriceBar
}
func getNextRandomPriceBar() -> SCSMultiPaneItem {
let close: Double = lastPriceBar.close
let num: Double = (drand48() - 0.9) * initialPriceBar.close / 30.0
let num2: Double = drand48()
let num3: Double = initialPriceBar.close + initialPriceBar.close / 2.0 * sin(7.27220521664304E-06 * currentTime) + initialPriceBar.close / 16.0 * cos(7.27220521664304E-05 * currentTime) + initialPriceBar.close / 32.0 * sin(7.27220521664304E-05 * (10.0 + num2) * currentTime) + initialPriceBar.close / 64.0 * cos(7.27220521664304E-05 * (20.0 + num2) * currentTime) + num
let num4: Double = fmax(close, num3)
let num5: Double = drand48() * initialPriceBar.close / 100.0
let high: Double = num4 + num5
let num6: Double = fmin(close, num3)
let num7: Double = drand48() * initialPriceBar.close / 100.0
let low: Double = num6 - num7
let volume = Int(drand48() * 30000 + 20000)
let openTime = simulateDateGap ? self.emulateDateGap(lastPriceBar.dateTime) : lastPriceBar.dateTime
let closeTime = openTime.addingTimeInterval(TimeInterval(candleIntervalMinutes))
let candle = SCSMultiPaneItem()
candle.close = num3
candle.dateTime = closeTime
candle.high = high
candle.low = low
candle.volume = Double(volume)
candle.open = close
lastPriceBar = SCSMultiPaneItem()
lastPriceBar.close = candle.close
lastPriceBar.dateTime = candle.dateTime
lastPriceBar.high = candle.high
lastPriceBar.low = candle.low
lastPriceBar.open = candle.open
lastPriceBar.volume = candle.volume
currentTime += Double(candleIntervalMinutes)
return candle
}
func emulateDateGap(_ candleOpenTime: Date) -> Date {
var result = candleOpenTime
if candleOpenTime.timeIntervalSince1970 > closeMarketTime {
var dateTime = candleOpenTime
dateTime = dateTime.addingTimeInterval(500)
result = dateTime.addingTimeInterval(openMarketTime)
}
while result.timeIntervalSince1970 < 500 {
result = result.addingTimeInterval(500)
}
return result
}
@objc func onTimerElapsed() {
if currentUpdateCount < updatesPerPrice {
currentUpdateCount += 1
let updatedData = getUpdateData()
updateData!(updatedData)
} else {
self.currentUpdateCount = 0
let nextData = getNextData()
newData!(nextData)
}
}
func clearEventHandlers() {
}
func tick() -> SCSMultiPaneItem {
if currentUpdateCount < updatesPerPrice {
currentUpdateCount += 1
return getUpdateData()
} else {
self.currentUpdateCount = 0
return getNextData()
}
}
}
class SCSMarketDataService {
var startDate: Date!
var timeFrameMinutes = 0
var tickTimerIntervals = 0
var generator: SCSRandomPriceDataSource!
init(start startDate: Date, timeFrameMinutes: Int, tickTimerIntervals: Int) {
self.startDate = startDate
self.timeFrameMinutes = timeFrameMinutes
self.tickTimerIntervals = tickTimerIntervals
generator = SCSRandomPriceDataSource(candleIntervalMinutes: timeFrameMinutes,
simulateDateGap: true,
timeInterval: Double(tickTimerIntervals),
updatesPerPrice: 25,
randomSeed: 100,
startingPrice: 30,
start: startDate)
}
func getHistoricalData(_ numberBars: Int) -> [SCSMultiPaneItem] {
var prices = [SCSMultiPaneItem]()
for _ in 0..<numberBars {
prices.append(generator.getNextData())
}
return prices
}
func getNextBar() -> SCSMultiPaneItem {
return generator.tick()
}
}
|
mit
|
2021b5380433e12a46271f846d2ee4c9
| 37.72375 | 377 | 0.577908 | 4.088557 | false | false | false | false |
ffsantos92/smartgas
|
app/smartgas/District.swift
|
1
|
1981
|
//
// This file is part of SmartGas, an iOS app to find the best gas station nearby.
//
// (c) Fábio Santos <[email protected]>
// (c) Mateus Silva <[email protected]>
// (c) Fábio Marques <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
import Foundation
class District: NSObject, NSCoding {
var id: Int!
var name: String!
var municipalityId: Int!
init(id: Int, name: String) {
self.id = id
self.name = name
}
struct Const {
static let id = "id"
static let name = "name"
}
// MARK: NSCoding
func encodeWithCoder(coder: NSCoder) {
coder.encodeInteger(id, forKey: Const.id)
coder.encodeObject(name, forKey: Const.name)
}
required init?(coder decoder: NSCoder) {
id = decoder.decodeIntegerForKey(Const.id)
name = decoder.decodeObjectForKey(Const.name) as! String
}
static func saveMany (brands: [District]) -> Bool {
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let filePath = documentsPath.URLByAppendingPathComponent("Districts.data")
let path = filePath.path!
if NSKeyedArchiver.archiveRootObject(brands, toFile: path) {
return true
}
return false
}
static func loadAll() -> [District] {
var dataToRetrieve = [District]()
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let filePath = documentsPath.URLByAppendingPathComponent("Districts.data", isDirectory: false)
let path = filePath.path!
if let newData = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [District] {
dataToRetrieve = newData
}
return dataToRetrieve
}
}
|
mit
|
0689e56838945ab2043e4d3f8a055e61
| 28.537313 | 133 | 0.66094 | 4.407572 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Controller/UI/Login/view/snsLoginHistoryCell.swift
|
1
|
2397
|
//
// snsLoginHistoryCell.swift
// selluv-ios
//
// Created by 조백근 on 2016. 12. 9..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import AlamofireImage
class snsLoginHistoryCell: UICollectionViewCell {
@IBOutlet weak var snsThumbnail: UIImageView!
@IBOutlet weak var snsSymbol: UIImageView!
@IBOutlet weak var snsNickName: UILabel!
var email: String?
var type: JoinType?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let list = [self.snsThumbnail, self.snsSymbol]
_ = list.map() {
let image = $0
image?.layer.borderWidth = 1
image?.layer.masksToBounds = false
image?.layer.borderColor = UIColor.white.cgColor
image?.layer.cornerRadius = (image?.frame.height)!/2
image?.clipsToBounds = true
}
}
func binding(item: [String]) {
let sns = item.first
let name = item[2]
let path = item[1]
let mail = item.last
if sns != "email" {
Alamofire.request(path).responseImage { response in
log.debug(response.request)
log.debug(response.response)
if let image = response.result.value {
log.debug("image downloaded: \(image)")
self.snsThumbnail.image = image
}
}
} else {
self.snsThumbnail.image = UIImage(named: path)
}
if sns == "facebook" {
self.snsSymbol.image = UIImage(named: "login-badge-fb.png")
self.type = .facebook
} else if sns == "kakao" {
self.snsSymbol.image = UIImage(named: "login-badge-kakao.png")
self.type = .kakao
} else if sns == "naver" {
self.snsSymbol.image = UIImage(named: "login-badge-naver.png")
self.type = .naver
} else if sns == "email" {
self.snsSymbol.image = UIImage(named: "login-badge-mail.png")
self.type = .email
}
self.email = mail
self.snsNickName.text = name
}
}
|
mit
|
d827b27eefc74e848f0b7f270c0d3eed
| 28.121951 | 74 | 0.549832 | 4.318264 | false | false | false | false |
imex94/KCLTech-iOS-2015
|
Hackalendar/Hackalendar/Hackalendar/HCHackathonSerialization.swift
|
1
|
1526
|
//
// HCHackathonSerialization.swift
// Hackalendar
//
// Created by Alex Telek on 08/12/2015.
// Copyright © 2015 Alex Telek. All rights reserved.
//
import UIKit
class HCHackathonSerialization: NSObject {
class func serializeObject(hackathons: [HackathonItem]) -> Dictionary<String, AnyObject> {
var hackDict = Dictionary<String, AnyObject>()
var hackArray = Array<Dictionary<String, String>>()
for hackathon in hackathons {
var dict = Dictionary<String, String>()
dict["title"] = hackathon.title
dict["url"] = hackathon.url
dict["startDate"] = hackathon.startDate
dict["endDate"] = hackathon.endDate
dict["year"] = hackathon.year?.stringValue
dict["city"] = hackathon.city
dict["host"] = hackathon.host
dict["length"] = hackathon.length?.stringValue
dict["travel"] = hackathon.travel
dict["prize"] = hackathon.prize?.stringValue
dict["highSchoolers"] = hackathon.highSchoolers?.stringValue
dict["facebookURL"] = hackathon.facebookURL
dict["twitterURL"] = hackathon.twitterURL
dict["googlePlusURL"] = hackathon.googlePlusURL
dict["notes"] = hackathon.notes
dict["month"] = hackathon.month?.stringValue
hackArray.append(dict)
}
hackDict["hackathons"] = hackArray
return hackDict
}
}
|
mit
|
2bab33d0654a9c114d9000aeaeababd0
| 32.888889 | 94 | 0.588852 | 4.663609 | false | false | false | false |
iCodeForever/ifanr
|
ifanr/ifanr/Views/MainView/MainHeaderView.swift
|
1
|
1857
|
//
// MainHeaderView.swift
// ifanr
//
// Created by 梁亦明 on 16/7/12.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import Foundation
class MainHeaderView: UIView, Reusable {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black
let attributes = [NSFontAttributeName: UIFont.customFont_FZLTXIHJW(fontSize: 10)]
let labelWidth = (textArray.last! as NSString).boundingRect(with: CGSize(width: 60, height: self.height), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).width
for i in 0..<textArray.count {
let label = createLable(textArray[i])
// 计算label大小
label.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: labelWidth, height: self.height))
let x = CGFloat(i)*(UIConstant.SCREEN_WIDTH*0.5-labelWidth*0.5)+UIConstant.SCREEN_WIDTH*0.5
label.center = CGPoint(x: x, y: self.height*0.5)
}
}
override func layoutSubviews() {
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: --------------------------- Private Methods --------------------------
/**
创建Label
*/
fileprivate func createLable(_ text: String) -> UILabel {
let label = UILabel()
label.text = text
label.textColor = UIColor.white
label.font = UIFont.customFont_FZLTXIHJW(fontSize: 10)
label.textAlignment = .center
labelArray.append(label)
self.addSubview(label)
return label
}
//MARK: --------------------------- Getter and Setter --------------------------
var labelArray = [UILabel]()
let textArray = ["快讯", "首页", "玩物志", "Appso", "MindStore"]
}
|
mit
|
f837976b5ef73edc71b6fbfdd48b1eda
| 32.740741 | 191 | 0.583425 | 4.307329 | false | false | false | false |
MaximilianGoetzfried/MXStatusMenu
|
MXStatusMenu/App.swift
|
2
|
613
|
import Cocoa
// Visual Parameters
let BarWidth: CGFloat = 7.0
let GapBetweenBars: CGFloat = 6.0
let LeftMargin: CGFloat = 5.5
let RightMargin: CGFloat = 5.5
// Update interval in seconds
let UpdateInterval = 0.5
/// The maximum throughput per second that is used as the 100% mark for the network load
let MaximumNetworkThroughput = Network.Throughput(input: 1_258_291 /* Download: 1,2 MB/s */, output: 133_120 /* Upload: 120 Kb/s */)
/// Our app delegate only holds a reference to the StatusController, nothing more
class App: NSObject, NSApplicationDelegate {
let statusController = StatusController()
}
|
mit
|
70ec801df979e4101870aa88d74f3a1d
| 33.055556 | 132 | 0.747145 | 3.879747 | false | false | false | false |
shenhualxt/Tuan
|
Tuan/Deal/View/HMDealCell.swift
|
8
|
3418
|
//
// HMDealCell.swift
// Tuan
//
// Created by nero on 15/5/23.
// Copyright (c) 2015年 nero. All rights reserved.
//
protocol HMDealCellDelegate:class {
func dealCellDidClickCover(dealCell:HMDealCell?)
}
import UIKit
//@IBDesignable
class HMDealCell: UICollectionViewCell {
override func drawRect(rect: CGRect) {
UIImage(named: "bg_dealcell")?.drawInRect(rect)
}
weak var delegate:HMDealCellDelegate?
@IBOutlet weak var dealNewView: UIImageView!
@IBOutlet weak var imageView:UIImageView!
@IBOutlet weak var titleLabel:UILabel!
@IBOutlet weak var descLabel:UILabel!
@IBOutlet weak var currentPriceLabel:UILabel!
@IBOutlet weak var purchaseCountLabel:UILabel!
@IBOutlet weak var listPriceLabel:HMCenterLineLabel!
@IBOutlet weak var listPriceWidth: NSLayoutConstraint!
@IBOutlet weak var currentPriceWidth: NSLayoutConstraint!
@IBOutlet weak var check: UIImageView!
@IBOutlet weak var cover: UIButton!
@IBAction func coverClick() {
self.deal.checking = !self.deal.checking;
self.check.hidden = !self.check.hidden;
delegate?.dealCellDidClickCover(self)
}
var deal:HMDeal! {
willSet{
if newValue == nil {return }
// 图片
// 在使用kingfas设置图片是 由于是swiftapi 所以ios8 以下版本无法使用
if let imageurl = NSURL(string: newValue.image_url) {
imageView.kf_setImageWithURL(imageurl)
}
// 标题
titleLabel.text = newValue.title
// 描述
descLabel.text = newValue.desc
// 现价
currentPriceLabel.text = String(format: "¥%@",newValue.current_price)
// 1弥补小误差
// self.currentPriceWidth.constant = [self.currentPriceLabel.text sizeWithAttributes:@{NSFontAttributeName : self.currentPriceLabel.font}].width + 1;
// 原价
listPriceLabel.text = String(format: "¥%@", newValue.list_price)
// 1弥补小误差
// self.listPriceWidth.constant = [self.listPriceLabel.text sizeWithAttributes:@{NSFontAttributeName : self.listPriceLabel.font}].width + 1;
// 购买数
purchaseCountLabel.text = String(format: "已售出%d", newValue.purchase_count)
// 判断是否为最新的团购:发布日期 >= 今天的日期
// NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
var fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
if newValue.publish_date == nil {return }
if let publish_date = fmt.dateFromString(newValue.publish_date) {
// 之前发布的:今天日期 > 发布日期
self.dealNewView.hidden = NSDate() >= publish_date ?? NSDate() //([today compare:deal.publish_date] == NSOrderedDescending);/
}
// 设置编辑状态
if newValue.editing {
self.cover.hidden = false;
} else {
self.cover.hidden = true;
}
// 设置勾选状态
self.check.hidden = !newValue.checking;
}
}
}
|
mit
|
f0de360e408acf4c57a047b4df9867b3
| 34.065217 | 172 | 0.574706 | 4.359459 | false | false | false | false |
einsteinx2/iSub
|
Classes/Server Loading/SubsonicURLRequest.swift
|
1
|
5130
|
//
// File.swift
// iSub
//
// Created by Benjamin Baron on 1/13/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
fileprivate let defaultLoadingTimeout = 240.0
fileprivate let serverCheckTimeout = 15.0
enum SubsonicURLAction: String {
case getMusicFolders = "getMusicFolders"
case getIndexes = "getIndexes"
case getArtists = "getArtists"
case getAlbumList2 = "getAlbumList2"
case getPlaylists = "getPlaylists"
case getMusicDirectory = "getMusicDirectory"
case getArtist = "getArtist"
case getAlbum = "getAlbum"
case getPlaylist = "getPlaylist"
case createPlaylist = "createPlaylist"
case getCoverArt = "getCoverArt"
case stream = "stream"
case hls = "hls"
case ping = "ping"
case search2 = "search2"
case search3 = "search3"
case updatePlaylist = "updatePlaylist"
case getRandomSongs = "getRandomSongs"
case getSimilarSongs = "getSimilarSongs"
case getSimilarSongs2 = "getSimilarSongs2"
case getAlbumList = "getAlbumList"
var urlExtension: String {
return self == .hls ? "m3u8" : "view"
}
var timeout: TimeInterval {
switch self {
case .getPlaylist: return 3600.0
case .getCoverArt: return 30.0
case .ping: return serverCheckTimeout
default: return defaultLoadingTimeout
}
}
}
fileprivate func encodedParameter(_ value: Any) -> String {
if let value = value as? String {
return value.URLQueryParameterEncodedValue
} else {
return "\(value)"
}
}
extension URLRequest {
init?(subsonicAction: SubsonicURLAction, serverId: Int64, parameters: [String: Any]? = nil, fragment: String? = nil, byteOffset: Int = 0) {
var server: Server?
if serverId == Server.testServerId {
server = Server.testServer
} else {
server = ServerRepository.si.server(serverId: serverId)
}
if let server = server {
var baseUrl = server.url
if serverId == SavedSettings.si.currentServerId, let redirectUrl = SavedSettings.si.redirectUrlString {
baseUrl = redirectUrl
}
if server.password == "" {
log.debug("creating request for serverId: \(server.serverId) password is empty")
}
self.init(subsonicAction: subsonicAction,
baseUrl: baseUrl,
username: server.username,
password: server.password ?? "",
parameters: parameters,
fragment: fragment,
byteOffset: byteOffset,
basicAuth: server.basicAuth)
} else {
return nil
}
}
init(subsonicAction: SubsonicURLAction, baseUrl: String, username: String, password: String, parameters: [String: Any]? = nil, fragment: String? = nil, byteOffset: Int = 0, basicAuth: Bool = false) {
var urlString = "\(baseUrl)/rest/\(subsonicAction.rawValue).\(subsonicAction.urlExtension)"
// Generate a 32 character random salt
// Then use the Subsonic required md5(password + salt) function to generate the token.
let salt = String.random(32)
let token = (password + salt).md5.lowercased()
// Only support Subsonic version 5.3 and later
let version = "1.13.0"
// Setup the parameters
var parametersString = "?c=iSub&v=\(version)&u=\(username)&t=\(token)&s=\(salt)"
if let parameters = parameters {
for (key, value) in parameters {
if let value = value as? [Any] {
for subValue in value {
parametersString += "&\(key)=\(encodedParameter(subValue))"
}
} else {
parametersString += "&\(key)=\(encodedParameter(value))"
}
}
}
urlString += parametersString
// Add the fragment
if let fragment = fragment {
urlString += "#\(fragment)"
}
self.init(url: URL(string: urlString)!)
self.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
self.timeoutInterval = subsonicAction.timeout
self.httpMethod = "GET"
self.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
if byteOffset > 0 {
self.setValue("bytes=\(byteOffset)-", forHTTPHeaderField: "Range")
}
// Optional HTTP Basic Auth
if basicAuth {
let authString = "\(username):\(encodedParameter(password))"
if let authData = authString.data(using: .ascii) {
let authValue = "Basic \(authData.base64EncodedString())"
self.setValue(authValue, forHTTPHeaderField: "Authorization")
}
}
}
}
|
gpl-3.0
|
bcedd459156d2397eebf4ce7fd887e15
| 35.375887 | 203 | 0.563463 | 4.709826 | false | false | false | false |
catloafsoft/AudioKit
|
AudioKit/Common/Nodes/Effects/Filters/Band Pass Butterworth Filter/AKBandPassButterworthFilter.swift
|
1
|
4172
|
//
// AKBandPassButterworthFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// These filters are Butterworth second-order IIR filters. They offer an almost
/// flat passband and very good precision and stopband attenuation.
///
/// - parameter input: Input node to process
/// - parameter centerFrequency: Center frequency. (in Hertz)
/// - parameter bandwidth: Bandwidth. (in Hertz)
///
public class AKBandPassButterworthFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKBandPassButterworthFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var centerFrequencyParameter: AUParameter?
private var bandwidthParameter: AUParameter?
/// Center frequency. (in Hertz)
public var centerFrequency: Double = 2000 {
willSet(newValue) {
if centerFrequency != newValue {
centerFrequencyParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Bandwidth. (in Hertz)
public var bandwidth: Double = 100 {
willSet(newValue) {
if bandwidth != newValue {
bandwidthParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - parameter input: Input node to process
/// - parameter centerFrequency: Center frequency. (in Hertz)
/// - parameter bandwidth: Bandwidth. (in Hertz)
///
public init(
_ input: AKNode,
centerFrequency: Double = 2000,
bandwidth: Double = 100) {
self.centerFrequency = centerFrequency
self.bandwidth = bandwidth
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x62746270 /*'btbp'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKBandPassButterworthFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKBandPassButterworthFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKBandPassButterworthFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
centerFrequencyParameter = tree.valueForKey("centerFrequency") as? AUParameter
bandwidthParameter = tree.valueForKey("bandwidth") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.centerFrequencyParameter!.address {
self.centerFrequency = Double(value)
} else if address == self.bandwidthParameter!.address {
self.bandwidth = Double(value)
}
}
}
centerFrequencyParameter?.setValue(Float(centerFrequency), originator: token!)
bandwidthParameter?.setValue(Float(bandwidth), originator: token!)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
|
mit
|
07704b693ab71163928a069e6d19fbe3
| 32.645161 | 100 | 0.643097 | 5.397154 | false | false | false | false |
nRewik/ArtHIstory
|
ArtHistory/ArtHistory/ThumbnailImageTableViewCell.swift
|
1
|
2103
|
//
// ThumbnailImageTableViewCell.swift
// ArtHistory
//
// Created by Nutchaphon Rewik on 8/8/15.
// Copyright (c) 2015 Nutchaphon Rewik. All rights reserved.
//
import UIKit
class ThumbnailImageTableViewCell: UITableViewCell {
var thumbnailImage: UIImage?{
didSet{
thumbnailImageView?.image = thumbnailImage
// update ratio of image
[ratioConstraint_ImageVIew].forEach(thumbnailImageView.removeConstraint)
var ratio: CGFloat = 0.0
if let thumbnailImage = thumbnailImage{
ratio = thumbnailImage.size.width / thumbnailImage.size.height
}
ratioConstraint_ImageVIew = NSLayoutConstraint(item: thumbnailImageView, attribute: NSLayoutAttribute.Width, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Height, multiplier: ratio, constant: 0)
thumbnailImageView.addConstraint(ratioConstraint_ImageVIew)
}
}
var title: String?{
didSet{
titleLabel?.text = title
// layoutIfNeeded()
}
}
var subtitle: String?{
didSet{
descriptionLabel?.text = subtitle
}
}
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet var ratioConstraint_ImageVIew: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
contentView.layer.shadowColor = UIColor.blackColor().CGColor
contentView.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
contentView.layer.shadowRadius = 1.0
contentView.layer.shadowOpacity = 0.2
cardView.layer.cornerRadius = 2.5
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
041d13796793adf3a090d411100ecf9a
| 29.478261 | 219 | 0.629577 | 5.270677 | false | false | false | false |
bhajian/raspi-remote
|
Carthage/Checkouts/ios-sdk/Source/TradeoffAnalyticsV1/Models/Resolution.swift
|
1
|
7361
|
/**
* Copyright IBM Corporation 2016
*
* 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 Freddy
/// A resolution to a decision problem.
public struct Resolution: JSONDecodable {
/// The two-dimensional position of the option on the map polygon displayed by the
/// Tradeoff Analytics visualization.
public let map: Map?
/// Analytical data per option.
public let solutions: [Solution]
/// Used internally to initialize a `Resolution` model from JSON.
public init(json: JSON) throws {
map = try? json.decode("map")
solutions = try json.arrayOf("solutions", type: Solution.self)
}
}
/// The two-dimensional position of an option on the map
/// polygon displayed by the Tradeoff Analytics visualization.
public struct Map: JSONDecodable {
/// A representation of the vertices for the objectives and their positions on the map
/// visualization.
public let anchors: [Anchor]
/// A cell on the map visualization. Each cell in the array includes coordinates that
/// describe the position on the map of the glyphs for one or more listed options, which
/// are identified by their keys.
public let nodes: [MapNode]
/// Used internally to initialize a `Map` model from JSON.
public init(json: JSON) throws {
anchors = try json.arrayOf("anchors", type: Anchor.self)
nodes = try json.arrayOf("nodes", type: MapNode.self)
}
}
/// A representation of the vertices for an objective and its positions on the map visualization.
public struct Anchor: JSONDecodable {
/// Anchor point name.
public let name: String
/// Anchor point position.
public let position: MapNodeCoordinates
/// Used internally to initialize an `Anchor` model from JSON.
public init(json: JSON) throws {
name = try json.string("name")
position = try json.decode("position")
}
}
/// A cell on the map visualization.
public struct MapNode: JSONDecodable {
/// The position of the cell on the map visualization.
public let coordinates: MapNodeCoordinates
/// References to solutions (the keys for options) positioned on this cell.
public let solutionRefs: [String]
/// Used internally to initialize a `MapNode` model from JSON.
public init(json: JSON) throws {
coordinates = try json.decode("coordinates")
solutionRefs = try json.arrayOf("solution_refs", type: String.self)
}
}
/// The position of a cell on the map visualization.
public struct MapNodeCoordinates: JSONDecodable {
/// X-axis coordinate on the map visualization.
public let x: Double
/// Y-axis coordinate on the map visualization.
public let y: Double
/// Used internally to initialize a `MapNodeCoordinates` model from JSON.
public init(json: JSON) throws {
x = try json.double("x")
y = try json.double("y")
}
}
/// Analytical data for a particular option.
public struct Solution: JSONDecodable {
/// A list of references to solutions that shadow this solution.
public let shadowMe: [String]?
/// A list of references to solutions that are shadowed by this solution.
public let shadows: [String]?
/// The key that uniquely identifies the option in the decision problem.
public let solutionRef: String
/// The status of the option (i.e. `Front`, `Excluded`, `Incomplete`,
/// or `DoesNotMeetPreference`).
public let status: SolutionStatus
/// If the status is `Incomplete` or `DoesNotMeetPreference`, a description that provides
/// more information about the cause of the status.
public let statusCause: StatusCause?
/// Used internally to initialize a `Solution` model from JSON.
public init(json: JSON) throws {
shadowMe = try? json.arrayOf("shadow_me", type: String.self)
shadows = try? json.arrayOf("shadows", type: String.self)
solutionRef = try json.string("solution_ref")
statusCause = try? json.decode("status_cause")
guard let status = SolutionStatus(rawValue: try json.decode("status")) else {
throw JSON.Error.ValueNotConvertible(value: json, to: Solution.self)
}
self.status = status
}
}
/// The status of an option.
public enum SolutionStatus: String {
/// `Front` indicates that the option is included among the top options for the problem.
case Front = "FRONT"
/// `Excluded` indicates that another option is strictly better than the option.
case Excluded = "EXCLUDED"
/// `Incomplete` indicates that either the option's specification does not include a value
/// for one of the columns or its value for one of the columns lies outside the range specified
/// for the column. Only a column whose `isObjective` property is set to `true` can generate
/// this status.
case Incomplete = "INCOMPLETE"
/// `DoesNotMeetPreference` indicates that the option specifies a value for a `Categorical`
/// column that is not included in the column's preference.
case DoesNotMeetPreference = "DOES_NOT_MEET_PREFERENCE"
}
/// Additional information about the cause of an option's status.
public struct StatusCause: JSONDecodable {
/// An error code that specifies the cause of the option's status.
public let errorCode: TradeoffAnalyticsError
/// A description in English of the cause for the option's status.
public let message: String
/// An array of values used to describe the cause for the option's status. The strings
/// appear in the message field.
public let tokens: [String]
/// Used internally to initialize a `StatusCause` model from JSON.
public init(json: JSON) throws {
guard let errorCode = TradeoffAnalyticsError(rawValue: try json.string("error_code")) else {
throw JSON.Error.ValueNotConvertible(value: json, to: StatusCause.self)
}
self.errorCode = errorCode
message = try json.string("message")
tokens = try json.arrayOf("tokens", type: String.self)
}
}
/// An error that specifies the cause of an option's status.
public enum TradeoffAnalyticsError: String {
/// Indicates that a column for which the `isObjective` property is `true` is absent from
/// the option's specification.
case MissingObjectiveValue = "MISSING_OBJECTIVE_VALUE"
/// Indicates that the option's specifications defines a value that is outside of the range
/// specified for an objective.
case RangeMismatch = "RANGE_MISMATCH"
/// Indicates that a `Categorical` column value for the option is not in the preference
/// for that column.
case DoesNotMeetPreference = "DOES_NOT_MEET_PREFERENCE"
}
|
mit
|
a65f9569c65bcf8ee6286430a85196aa
| 36.365482 | 100 | 0.684418 | 4.566377 | false | false | false | false |
kousun12/RxSwift
|
RxExample/RxExample/Example.swift
|
9
|
1159
|
//
// Example.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
typealias Image = UIImage
#elseif os(OSX)
import Cocoa
import AppKit
typealias Image = NSImage
#endif
let MB = 1024 * 1024
func exampleError(error: String, location: String = "\(__FILE__):\(__LINE__)") -> NSError {
return NSError(domain: "ExampleError", code: -1, userInfo: [NSLocalizedDescriptionKey: "\(location): \(error)"])
}
extension String {
func toFloat() -> Float? {
let numberFormatter = NSNumberFormatter()
return numberFormatter.numberFromString(self)?.floatValue
}
func toDouble() -> Double? {
let numberFormatter = NSNumberFormatter()
return numberFormatter.numberFromString(self)?.doubleValue
}
}
func showAlert(message: String) {
#if os(iOS)
UIAlertView(title: "RxExample", message: message, delegate: nil, cancelButtonTitle: "OK").show()
#elseif os(OSX)
let alert = NSAlert()
alert.messageText = message
alert.runModal()
#endif
}
|
mit
|
33a5324a498f729d03b71eae24a2b2cb
| 24.217391 | 116 | 0.651424 | 4.261029 | false | false | false | false |
ronanrodrigo/Papu
|
Example/Tests/Tests.swift
|
1
|
1171
|
// https://github.com/Quick/Quick
import Quick
import Nimble
import Papu
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()
}
}
}
}
}
}
|
mit
|
a67d007a99089c339f40e0b30e93b72f
| 22.3 | 63 | 0.360515 | 5.443925 | false | false | false | false |
devcastid/iOS-Tutorials
|
Davcast-iOS/Pods/Material/Sources/NavigationBarView.swift
|
1
|
9223
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of Material 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
@objc(NavigationBarViewDelegate)
public protocol NavigationBarViewDelegate : MaterialDelegate {
optional func navigationBarViewDidChangeLayout(navigationBarView: NavigationBarView)
}
public class NavigationBarView : MaterialView {
/// Tracks the old frame size.
private var oldFrame: CGRect?
/// TitleView that holds the titleLabel and detailLabel.
public private(set) lazy var titleView: MaterialView = MaterialView()
/// Device status bar style.
public var statusBarStyle: UIStatusBarStyle = UIApplication.sharedApplication().statusBarStyle {
didSet {
UIApplication.sharedApplication().statusBarStyle = statusBarStyle
}
}
/// A preset wrapper around contentInset.
public var contentInsetPreset: MaterialEdgeInset = .None {
didSet {
contentInset = MaterialEdgeInsetToValue(contentInsetPreset)
}
}
/// A wrapper around grid.contentInset.
public var contentInset: UIEdgeInsets {
get {
return grid.contentInset
}
set(value) {
grid.contentInset = contentInset
reloadView()
}
}
/// A wrapper around grid.spacing.
public var spacing: CGFloat {
get {
return grid.spacing
}
set(value) {
grid.spacing = spacing
reloadView()
}
}
/// Title label.
public var titleLabel: UILabel? {
didSet {
if let v: UILabel = titleLabel {
titleView.addSubview(v)
}
reloadView()
}
}
/// Detail label.
public var detailLabel: UILabel? {
didSet {
if let v: UILabel = detailLabel {
titleView.addSubview(v)
}
reloadView()
}
}
/// Left side UIControls.
public var leftControls: Array<UIControl>? {
didSet {
reloadView()
}
}
/// Right side UIControls.
public var rightControls: Array<UIControl>? {
didSet {
reloadView()
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
}
/// A convenience initializer.
public convenience init() {
self.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 64))
}
/**
A convenience initializer with parameter settings.
- Parameter titleLabel: UILabel for the title.
- Parameter detailLabel: UILabel for the details.
- Parameter leftControls: An Array of UIControls that go on the left side.
- Parameter rightControls: An Array of UIControls that go on the right side.
*/
public convenience init?(titleLabel: UILabel? = nil, detailLabel: UILabel? = nil, leftControls: Array<UIControl>? = nil, rightControls: Array<UIControl>? = nil) {
self.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 64))
prepareProperties(titleLabel, detailLabel: detailLabel, leftControls: leftControls, rightControls: rightControls)
}
public override func layoutSubviews() {
super.layoutSubviews()
// General alignment.
if UIApplication.sharedApplication().statusBarOrientation.isLandscape {
grid.contentInset.top = 8
// TitleView alignment.
if let v: UILabel = titleLabel {
if let d: UILabel = detailLabel {
v.grid.rows = 7
d.grid.rows = 5
titleView.grid.spacing = 4
titleView.grid.contentInset.top = -3
} else {
v.grid.rows = 12
titleView.grid.spacing = 0
titleView.grid.contentInset.top = 0
}
}
height = 44
} else {
grid.contentInset.top = 20
// TitleView alignment.
if let v: UILabel = titleLabel {
if let d: UILabel = detailLabel {
v.grid.rows = 7
d.grid.rows = 5
titleView.grid.spacing = 4
titleView.grid.contentInset.top = -3
} else {
v.grid.rows = 12
titleView.grid.spacing = 0
titleView.grid.contentInset.top = 0
}
}
height = 64
}
// Column adjustment.
width = UIScreen.mainScreen().bounds.width
grid.axis.columns = Int(width / 48)
if frame.origin.x != oldFrame!.origin.x || frame.origin.y != oldFrame!.origin.y || frame.width != oldFrame!.width || frame.height != oldFrame!.height {
(delegate as? NavigationBarViewDelegate)?.navigationBarViewDidChangeLayout?(self)
oldFrame = frame
}
reloadView()
}
public override func didMoveToSuperview() {
super.didMoveToSuperview()
reloadView()
}
public override func intrinsicContentSize() -> CGSize {
if UIApplication.sharedApplication().statusBarOrientation.isLandscape {
return CGSizeMake(UIScreen.mainScreen().bounds.width, 44)
} else {
return CGSizeMake(UIScreen.mainScreen().bounds.width, 64)
}
}
/// Reloads the view.
public func reloadView() {
layoutIfNeeded()
// clear constraints so new ones do not conflict
removeConstraints(constraints)
for v in subviews {
if v != titleView {
v.removeFromSuperview()
}
}
// Size of single grid column.
let g: CGFloat = width / CGFloat(0 < grid.axis.columns ? grid.axis.columns : 1)
grid.views = []
titleView.grid.columns = grid.axis.columns
// leftControls
if let v: Array<UIControl> = leftControls {
for c in v {
let w: CGFloat = c.intrinsicContentSize().width
if let b: UIButton = c as? UIButton {
b.contentEdgeInsets = UIEdgeInsetsZero
}
c.grid.columns = 0 == g ? 1 : Int(ceil(w / g))
titleView.grid.columns -= c.grid.columns
addSubview(c)
grid.views?.append(c)
}
}
grid.views?.append(titleView)
// rightControls
if let v: Array<UIControl> = rightControls {
for c in v {
let w: CGFloat = c.intrinsicContentSize().width
if let b: UIButton = c as? UIButton {
b.contentEdgeInsets = UIEdgeInsetsZero
}
c.grid.columns = 0 == g ? 1 : Int(ceil(w / g))
titleView.grid.columns -= c.grid.columns
addSubview(c)
grid.views?.append(c)
}
}
titleView.grid.columns -= titleView.grid.offset.columns
grid.reloadLayout()
titleView.grid.views = []
titleView.grid.axis.rows = 6
if let v: UILabel = titleLabel {
titleView.grid.views?.append(v)
}
if let v: UILabel = detailLabel {
titleView.grid.views?.append(v)
}
titleView.grid.reloadLayout()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
public override func prepareView() {
super.prepareView()
oldFrame = frame
grid.spacing = 0
grid.axis.inherited = false
grid.contentInset.left = 0
grid.contentInset.bottom = 0
grid.contentInset.right = 0
depth = .Depth1
prepareTitleView()
}
/// Prepares the titleView.
public func prepareTitleView() {
titleView.backgroundColor = nil
titleView.grid.axis.direction = .Vertical
addSubview(titleView)
}
/**
Used to trigger property changes that initializers avoid.
- Parameter titleLabel: UILabel for the title.
- Parameter detailLabel: UILabel for the details.
- Parameter leftControls: An Array of UIControls that go on the left side.
- Parameter rightControls: An Array of UIControls that go on the right side.
*/
internal func prepareProperties(titleLabel: UILabel?, detailLabel: UILabel?, leftControls: Array<UIControl>?, rightControls: Array<UIControl>?) {
self.titleLabel = titleLabel
self.detailLabel = detailLabel
self.leftControls = leftControls
self.rightControls = rightControls
}
}
|
mit
|
f3820aca743652517a8f6f8c7afa685f
| 27.912226 | 163 | 0.712241 | 3.850939 | false | false | false | false |
zqqf16/SYM
|
SYM/UI/DsymViewController.swift
|
1
|
7554
|
// The MIT License (MIT)
//
// Copyright (c) 2017 - present zqqf16
//
// 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 Cocoa
import Combine
protocol DsymTableCellViewDelegate: AnyObject {
func didClickSelectButton(_ cell: DsymTableCellView, sender: NSButton)
func didClickRevealButton(_ cell: DsymTableCellView, sender: NSButton)
}
class DsymTableCellView: NSTableCellView {
@IBOutlet var image: NSImageView!
@IBOutlet var title: NSTextField!
@IBOutlet var uuid: NSTextField!
@IBOutlet var path: NSTextField!
@IBOutlet var actionButton: NSButton!
weak var delegate: DsymTableCellViewDelegate?
var binary: Binary!
var dsym: DsymFile?
func updateUI() {
title.stringValue = binary.name
uuid.stringValue = binary.uuid ?? ""
if let path = dsym?.path {
self.path.stringValue = path
actionButton.title = NSLocalizedString("Reveal", comment: "Reveal in Finder")
} else {
path.stringValue = NSLocalizedString("dsym_file_not_found", comment: "Dsym file not found")
actionButton.title = NSLocalizedString("Import", comment: "Import a dSYM file")
}
}
@IBAction func didClickActionButton(_ sender: NSButton) {
if dsym?.path != nil {
delegate?.didClickRevealButton(self, sender: sender)
} else {
delegate?.didClickSelectButton(self, sender: sender)
}
}
}
class DsymViewController: NSViewController {
@IBOutlet var tableView: NSTableView!
@IBOutlet var tableViewHeight: NSLayoutConstraint!
@IBOutlet var downloadButton: NSButton!
@IBOutlet var progressBar: NSProgressIndicator!
private var binaries: [Binary] = [] {
didSet {
reloadData()
}
}
private var dsymFiles: [String: DsymFile] = [:] {
didSet {
reloadData()
}
}
private var dsymStorage = Set<AnyCancellable>()
private var taskCancellable: AnyCancellable?
var dsymManager: DsymManager? {
didSet {
dsymStorage.forEach { cancellable in
cancellable.cancel()
}
dsymManager?.$binaries
.receive(on: DispatchQueue.main)
.assign(to: \.binaries, on: self)
.store(in: &dsymStorage)
dsymManager?.$dsymFiles
.receive(on: DispatchQueue.main)
.assign(to: \.dsymFiles, on: self)
.store(in: &dsymStorage)
}
}
private func reloadData() {
guard tableView != nil else {
return
}
tableView.reloadData()
updateViewHeight()
}
private func dsymFile(forBinary binary: Binary) -> DsymFile? {
if let uuid = binary.uuid {
return dsymManager?.dsymFile(withUuid: uuid)
}
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
updateViewHeight()
downloadButton.isEnabled = dsymManager?.crash != nil
}
override func viewDidDisappear() {
super.viewDidDisappear()
taskCancellable?.cancel()
dsymStorage.forEach { cancellable in
cancellable.cancel()
}
}
func bind(task: DsymDownloadTask?) {
taskCancellable?.cancel()
guard let downloadTask = task else {
return
}
taskCancellable = Publishers
.CombineLatest(downloadTask.$status, downloadTask.$progress)
.receive(on: DispatchQueue.main)
.sink { status, progress in
self.update(status: status, progress: progress)
}
}
// MARK: UI
private func updateViewHeight() {
tableViewHeight.constant = min(CGFloat(70 * binaries.count), 520.0)
}
@IBAction func didClickDownloadButton(_: NSButton) {
if let crashInfo = dsymManager?.crash {
DsymDownloader.shared.download(crashInfo: crashInfo, fileURL: nil)
}
}
}
extension DsymViewController: NSTableViewDelegate, NSTableViewDataSource {
func numberOfRows(in _: NSTableView) -> Int {
return binaries.count
}
func tableView(_ tableView: NSTableView, viewFor _: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: nil) as? DsymTableCellView
cell?.delegate = self
let binary = binaries[row]
cell?.binary = binary
cell?.dsym = dsymFile(forBinary: binary)
cell?.updateUI()
return cell
}
func tableView(_: NSTableView, shouldSelectRow _: Int) -> Bool {
return false
}
}
extension DsymViewController: DsymTableCellViewDelegate {
func didClickSelectButton(_ cell: DsymTableCellView, sender _: NSButton) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
openPanel.begin { [weak openPanel] result in
guard result == .OK, let url = openPanel?.url else {
return
}
self.dsymManager?.assign(cell.binary!, dsymFileURL: url)
}
}
func didClickRevealButton(_ cell: DsymTableCellView, sender _: NSButton) {
if let path = cell.dsym?.path {
let url = URL(fileURLWithPath: path)
NSWorkspace.shared.activateFileViewerSelecting([url])
}
}
}
extension DsymViewController {
func update(status: DsymDownloadTask.Status, progress: DsymDownloadTask.Progress) {
switch status {
case .running:
downloadButton.isEnabled = false
progressBar.isHidden = false
case .canceled:
progressBar.isHidden = true
downloadButton.isEnabled = true
case .failed:
progressBar.isHidden = true
downloadButton.isEnabled = true
case .success:
progressBar.isHidden = true
case .waiting:
progressBar.isHidden = false
progressBar.isIndeterminate = true
progressBar.startAnimation(nil)
downloadButton.isEnabled = false
}
if progress.percentage == 0 {
progressBar.isIndeterminate = true
} else {
progressBar.isIndeterminate = false
progressBar.doubleValue = Double(progress.percentage)
}
}
}
|
mit
|
4b5254318b1536ff5d6815bd925da5e7
| 31.9869 | 136 | 0.634763 | 5.052843 | false | false | false | false |
edx/edx-app-ios
|
Source/StartupViewController.swift
|
1
|
16023
|
//
// StartupViewController.swift
// edX
//
// Created by Michael Katz on 5/16/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
private let CornerRadius:CGFloat = 0.0
private let BottomBarMargin:CGFloat = 20.0
private let PortraitBottomBarHeight:CGFloat = 90.0
private let LandscapeBottomBarHeight:CGFloat = 75.0
class StartupViewController: UIViewController, InterfaceOrientationOverriding {
typealias Environment = OEXRouterProvider & OEXConfigProvider & OEXAnalyticsProvider & OEXStylesProvider
private let logoImageView = UIImageView()
private let searchView = UIView()
private let messageLabel = UILabel()
private lazy var searchViewTitle = UILabel()
fileprivate let environment: Environment
private let bottomBar: BottomBarView
private let imageContainer = UIView()
private var infoMessage: String {
get {
let programDiscoveryEnabled = environment.config.discovery.program.isEnabled
if programDiscoveryEnabled {
return Strings.Startup.infoMessageText(programsText: Strings.Startup.infoMessageProgramText)
}
else {
return Strings.Startup.infoMessageText(programsText: "")
}
}
}
init(environment: Environment) {
self.environment = environment
bottomBar = BottomBarView(environment: environment)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupLogo()
setupMessageLabel()
setupSearchView()
setupBottomBar()
setupExploreCoursesButton()
view.backgroundColor = environment.styles.standardBackgroundColor()
let tapGesture = UITapGestureRecognizer()
tapGesture.addAction { [weak self] _ in
self?.view.endEditing(true)
}
view.addGestureRecognizer(tapGesture)
addObservers()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
environment.analytics.trackScreen(withName: OEXAnalyticsScreenLaunch)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
bottomBar.updateContraints()
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
// MARK: - View Setup
private func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if view.frame.size.height - (searchView.frame.origin.y + searchView.frame.size.height) < keyboardSize.height {
let difference = keyboardSize.height - (view.frame.size.height - (searchView.frame.origin.y + searchView.frame.size.height)) + StandardVerticalMargin
view.frame.origin.y = -difference
}
}
}
private func keyboardWillHide() {
view.frame.origin.y = 0
}
private func addObservers() {
NotificationCenter.default.oex_addObserver(observer: self, name: UIResponder.keyboardDidShowNotification.rawValue) { (notification, observer, _) in
observer.keyboardWillShow(notification: notification)
}
NotificationCenter.default.oex_addObserver(observer: self, name: UIResponder.keyboardWillHideNotification.rawValue) { (_, observer, _) in
observer.keyboardWillHide()
}
}
private func setupLogo() {
let logo = UIImage(named: "logo")
logoImageView.image = logo
logoImageView.contentMode = .scaleAspectFit
logoImageView.isAccessibilityElement = false
// In iOS 13+ voice over trying to read the possible text of the accessibility element when the accessibility element is the image.
// To overcome this issue, the logo image is placed in a container and accessibility set on that container
imageContainer.addSubview(logoImageView)
imageContainer.accessibilityLabel = environment.config.platformName()
imageContainer.isAccessibilityElement = true
imageContainer.accessibilityIdentifier = "StartUpViewController:logo-image-view"
imageContainer.accessibilityHint = Strings.accessibilityImageVoiceOverHint
view.addSubview(imageContainer)
}
private func setupMessageLabel() {
let labelStyle = OEXTextStyle(weight: .semiBold, size: .xxLarge, color: environment.styles.primaryBaseColor())
messageLabel.numberOfLines = 0
messageLabel.attributedText = labelStyle.attributedString(withText: infoMessage)
messageLabel.accessibilityIdentifier = "StartUpViewController:message-label"
view.addSubview(messageLabel)
messageLabel.snp.makeConstraints { make in
make.top.equalTo(logoImageView.snp.bottom).offset(3 * StandardVerticalMargin)
make.leading.equalTo(logoImageView)
make.trailing.equalTo(safeTrailing).offset(-2 * StandardHorizontalMargin)
}
}
private func setupSearchView() {
let courseEnrollmentEnabled = environment.config.discovery.course.isEnabled
guard courseEnrollmentEnabled else { return }
view.addSubview(searchView)
view.addSubview(searchViewTitle)
let borderStyle = BorderStyle(cornerRadius: .Size(CornerRadius), width: .Size(1), color: environment.styles.neutralLight())
searchView.applyBorderStyle(style: borderStyle)
searchView.snp.makeConstraints { make in
make.top.equalTo(searchViewTitle.snp.bottom).offset(StandardVerticalMargin)
make.leading.equalTo(messageLabel)
make.trailing.equalTo(messageLabel)
make.height.equalTo(45)
}
let searchIcon = Icon.Discovery.imageWithFontSize(size: 17)
let searchImageView = UIImageView()
searchImageView.image = searchIcon
searchImageView.tintColor = environment.styles.primaryBaseColor()
searchView.addSubview(searchImageView)
searchImageView.snp.makeConstraints { make in
make.leading.equalTo(StandardHorizontalMargin)
make.centerY.equalTo(searchView)
make.width.equalTo(15)
make.height.equalTo(15)
}
let textStyle = OEXTextStyle(weight: .normal, size: .large, color: environment.styles.primaryBaseColor())
let searchTextField = UITextField()
searchTextField.accessibilityIdentifier = "StartUpViewController:search-textfield"
searchTextField.delegate = self
searchTextField.attributedPlaceholder = textStyle.attributedString(withText: Strings.Startup.searchPlaceholderText)
searchTextField.textColor = environment.styles.primaryBaseColor()
searchTextField.returnKeyType = .search
searchTextField.defaultTextAttributes = environment.styles.textFieldStyle(with: .large, color: environment.styles.primaryBaseColor()).attributes.attributedKeyDictionary()
searchView.addSubview(searchTextField)
searchTextField.snp.makeConstraints { make in
make.leading.equalTo(searchImageView.snp.trailing).offset(StandardHorizontalMargin)
make.trailing.equalTo(searchView).offset(-StandardHorizontalMargin)
make.centerY.equalTo(searchView)
}
let labelStyle = OEXTextStyle(weight: .semiBold, size: .large, color: environment.styles.primaryBaseColor())
searchViewTitle.attributedText = labelStyle.attributedString(withText: Strings.Startup.searchTitleText)
setConstraints()
}
private func setConstraints() {
let isiPhone5OrLess = isVerticallyCompact() && UIScreen.main.bounds.height <= 320
imageContainer.snp.remakeConstraints { make in
make.leading.equalTo(safeLeading).offset(2 * StandardHorizontalMargin)
if isiPhone5OrLess {
make.top.equalTo(view).offset(2 * StandardVerticalMargin)
}
else {
make.centerY.equalTo(view.snp.bottom).dividedBy(6.0)
}
make.width.equalTo((logoImageView.image?.size.width ?? 0) / 2)
make.height.equalTo((logoImageView.image?.size.height ?? 0) / 2)
}
logoImageView.snp.remakeConstraints { make in
make.center.edges.equalTo(imageContainer)
}
let courseEnrollmentEnabled = environment.config.discovery.course.isEnabled
guard courseEnrollmentEnabled else { return }
let offSet: CGFloat = isVerticallyCompact() ? 2 : 6
searchViewTitle.snp.remakeConstraints { make in
make.top.equalTo(messageLabel.snp.bottom).offset(offSet * StandardVerticalMargin)
make.leading.equalTo(messageLabel)
make.trailing.equalTo(messageLabel)
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateViewConstraints()
}
override func updateViewConstraints() {
super.updateViewConstraints()
setConstraints()
}
private func setupExploreCoursesButton() {
let courseEnrollmentEnabled = environment.config.discovery.course.isEnabled
guard courseEnrollmentEnabled else { return }
let style = OEXTextStyle(weight: .normal, size: .large, color: environment.styles.primaryBaseColor())
let exploreButton = UIButton(type: .system)
exploreButton.setAttributedTitle(style.attributedString(withText: Strings.Startup.exploreCourseTitle), for: .normal)
exploreButton.oex_addAction({ [weak self] _ in
self?.showCourses(with: nil)
self?.environment.analytics.trackExploreAllCourses()
}, for: .touchUpInside)
view.addSubview(exploreButton)
exploreButton.snp.makeConstraints { make in
make.leading.equalTo(searchView)
make.top.equalTo(searchView.snp.bottom).offset(StandardVerticalMargin / 2)
}
let lineView = UIView()
lineView.backgroundColor = environment.styles.primaryBaseColor()
lineView.isAccessibilityElement = false
view.addSubview(lineView)
lineView.snp.makeConstraints { make in
make.top.equalTo(exploreButton.snp.bottom).inset(StandardVerticalMargin/2)
make.height.equalTo(1)
make.leading.equalTo(exploreButton)
make.width.equalTo(exploreButton)
}
}
private func setupBottomBar() {
view.addSubview(bottomBar)
bottomBar.snp.makeConstraints { make in
make.bottom.equalTo(view)
make.leading.equalTo(safeLeading)
make.trailing.equalTo(safeTrailing)
}
}
fileprivate func showCourses(with searchQuery: String?) {
let bottomBar = BottomBarView(environment: environment)
environment.router?.showCourseCatalog(fromController: nil, bottomBar: bottomBar, searchQuery: searchQuery)
}
}
public class BottomBarView: UIView, NSCopying {
typealias Environment = OEXRouterProvider & OEXStylesProvider
private var environment : Environment?
private let bottomBar = TZStackView()
private let signInButton = UIButton()
private let registerButton = UIButton()
init(frame: CGRect = CGRect.zero, environment:Environment?) {
super.init(frame:frame)
self.environment = environment
makeBottomBar()
addObserver()
}
func addObserver() {
NotificationCenter.default.oex_addObserver(observer: self, name: NOTIFICATION_DYNAMIC_TEXT_TYPE_UPDATE) {(_, observer, _) in
observer.updateContraints()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func copy(with zone: NSZone? = nil) -> Any {
let copy = BottomBarView(environment: environment)
return copy
}
private func makeBottomBar() {
bottomBar.backgroundColor = environment?.styles.standardBackgroundColor()
let signInBorderStyle = BorderStyle(cornerRadius: .Size(CornerRadius), width: .Size(1), color: environment?.styles.neutralBase())
signInButton.applyBorderStyle(style: signInBorderStyle)
signInButton.accessibilityIdentifier = "StartUpViewController:sign-in-button"
let signinTextStyle = OEXTextStyle(weight: .semiBold, size: .large, color: environment?.styles.secondaryBaseColor())
signInButton.setAttributedTitle(signinTextStyle.attributedString(withText: Strings.signInText), for: .normal)
signInButton.oex_addAction({ [weak self] _ in
self?.showLogin()
}, for: .touchUpInside)
registerButton.backgroundColor = environment?.styles.secondaryBaseColor()
registerButton.applyBorderStyle(style: BorderStyle(cornerRadius: .Size(CornerRadius), width: .Size(0), color: environment?.styles.secondaryBaseColor()))
registerButton.accessibilityIdentifier = "StartUpViewController:register-button"
let registerTextStyle = OEXTextStyle(weight: .semiBold, size: .large, color: environment?.styles.neutralWhite())
registerButton.setAttributedTitle(registerTextStyle.attributedString(withText: Strings.registerText), for: .normal)
let signUpEvent = OEXAnalytics.registerEvent(name: AnalyticsEventName.UserRegistrationClick.rawValue, displayName: AnalyticsDisplayName.CreateAccount.rawValue)
registerButton.oex_addAction({ [weak self] _ in
self?.showRegistration()
}, for: .touchUpInside, analyticsEvent: signUpEvent)
bottomBar.spacing = 10
bottomBar.addArrangedSubview(registerButton)
bottomBar.layoutMarginsRelativeArrangement = true
bottomBar.addArrangedSubview(signInButton)
addSubview(bottomBar)
updateContraints()
}
fileprivate func updateContraints() {
bottomBar.axis = .horizontal
bottomBar.snp.remakeConstraints { make in
make.edges.equalTo(self)
if UIDevice.current.orientation.isLandscape {
make.height.equalTo(LandscapeBottomBarHeight)
}
else {
make.height.equalTo(PortraitBottomBarHeight)
}
}
signInButton.snp.remakeConstraints { make in
make.top.equalTo(bottomBar).offset(BottomBarMargin)
make.bottom.equalTo(bottomBar).offset(-BottomBarMargin)
make.trailing.equalTo(bottomBar).offset(-BottomBarMargin)
make.width.equalTo(95)
}
registerButton.snp.remakeConstraints { make in
make.top.equalTo(bottomBar).offset(BottomBarMargin)
make.bottom.equalTo(bottomBar).offset(-BottomBarMargin)
make.leading.equalTo(bottomBar).offset(BottomBarMargin)
make.trailing.equalTo(signInButton.snp.leading).offset(-BottomBarMargin)
}
}
//MARK: - Actions
func showLogin() {
environment?.router?.showLoginScreen(from: firstAvailableUIViewController(), completion: nil)
}
func showRegistration() {
environment?.router?.showSignUpScreen(from: firstAvailableUIViewController(), completion: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension StartupViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
environment.analytics.trackCourseSearch(search: textField.text ?? "", action: "landing_screen")
showCourses(with: textField.text)
textField.text = nil
return true
}
}
|
apache-2.0
|
07e2786ce164c9f328d07766b1c71651
| 39.664975 | 178 | 0.684309 | 5.353157 | false | false | false | false |
fortmarek/Supl
|
Supl/SetUpViewController.swift
|
1
|
11273
|
//
// SetUpViewController.swift
// Supl
//
// Created by Marek Fořt on 16.02.16.
// Copyright © 2016 Marek Fořt. All rights reserved.
//
import UIKit
import SwiftSpinner
import MessageUI
class SetUpViewController: UIViewController, MFMailComposeViewControllerDelegate {
@IBOutlet weak var professorStudentSegment: UISegmentedControl!
@IBOutlet weak var schoolTextField: UITextField!
@IBOutlet weak var classTextField: UITextField!
@IBOutlet weak var getStartedButton: UIButton!
@IBOutlet weak var emailButtonBottomLayout: NSLayoutConstraint!
@IBOutlet weak var suplLabel: UILabel!
@IBOutlet weak var emailButton: UIButton!
let defaults = UserDefaults.standard
var constraint = CGFloat(0)
var schoolOrigin = CGFloat(0)
override func viewDidLoad() {
super.viewDidLoad()
//Keyboard Notifications
NotificationCenter.default.addObserver(self, selector: #selector(keyboardNotification(_:)), name:NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
//Keyboard Editing ends when tapped outside of textfield
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
if let clasString = defaults.value(forKey: "class") as? String , clasString != "" {
classTextField.text = clasString
}
if let schoolString = defaults.value(forKey: "schoolUrl") as? String , schoolString != "" {
schoolTextField.text = schoolString
}
if let segmentIndex = defaults.value(forKey: "segmentIndex") as? Int {
professorStudentSegment.selectedSegmentIndex = segmentIndex
}
professorStudentSegment.addTarget(self, action: #selector(segmentChanged), for: .valueChanged)
schoolTextField.addTarget(self, action: #selector(goToNextField), for: .editingDidEndOnExit)
classTextField.addTarget(self, action: #selector(saveData), for: .editingDidEndOnExit)
getStartedButton.backgroundColor = UIColor.clear
getStartedButton.layer.cornerRadius = 5
getStartedButton.layer.borderWidth = 1
getStartedButton.layer.borderColor = UIColor(hue: 0, saturation: 0, brightness: 1.0, alpha: 1.0).cgColor
let height = self.view.frame.size.height
let yButton = emailButton.frame.origin.y
let heightButton = emailButton.frame.height
let yLabel = suplLabel.frame.origin.y
let constraintSize = (height - (yButton - yLabel + heightButton)) / 2
emailButtonBottomLayout.constant = constraintSize
constraint = constraintSize
self.view.layoutIfNeeded()
schoolOrigin = schoolTextField.frame.origin.y
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLayoutSubviews() {
initTextField("http://old.gjk.cz/suplovani.php", textField: schoolTextField)
if professorStudentSegment.selectedSegmentIndex == 0 {
initTextField("R6.A", textField: classTextField)
classTextField.autocapitalizationType = .allCharacters
}
else {
initTextField("Příjmení jméno", textField: classTextField)
classTextField.autocapitalizationType = .words
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func getStartedButtonTapped(_ sender: UIButton) {
let _ = saveData()
}
func segmentChanged() {
if professorStudentSegment.selectedSegmentIndex == 0 {
initTextField("R6.A", textField: classTextField)
classTextField.autocapitalizationType = .allCharacters
}
else {
initTextField("Příjmení Jméno", textField: classTextField)
classTextField.autocapitalizationType = .words
}
}
func initTextField(_ placeholder: String, textField: UITextField) {
//Placeholder
let attributes = [NSForegroundColorAttributeName : UIColor(hue: 0, saturation: 0.0, brightness: 1.0, alpha: 0.6)]
let attributedString = NSAttributedString(string: placeholder, attributes: attributes)
textField.attributedPlaceholder = attributedString
textField.borderStyle = .roundedRect
}
func saveData() -> Bool {
DispatchQueue.main.async(execute: {
SwiftSpinner.show("Načítání")
})
guard
let school = schoolTextField.text , school != "",
var clas = classTextField.text , clas != ""
else {
showMark("Vyplňte všechna pole")
return false
}
clas = clas.removeExcessiveSpaces
let dataController = DataController()
if let oldSchool = defaults.string(forKey: "schoolUrl") {
if oldSchool != school {
postSchool(school, clas: clas, oldSchool: oldSchool)
}
else {
if let oldClas = defaults.string(forKey: "class") {
let segmentIndex = defaults.integer(forKey: "segmentIndex")
if let isUrlRight = defaults.value(forKey: "isUrlRight") as? Bool , isUrlRight == true &&
clas != oldClas {
dataController.postProperty(clas, school: school)
dataController.deleteProperty(oldClas, school: school)
}
else if segmentIndex != professorStudentSegment.selectedSegmentIndex {
dataController.deleteProperty(clas, school: school)
self.defaults.set(professorStudentSegment.selectedSegmentIndex, forKey: "segmentIndex")
dataController.postProperty(clas, school: school)
}
}
else {
if let isUrlRight = defaults.value(forKey: "isUrlRight") as? Bool , isUrlRight == true {
dataController.postProperty(clas, school: school)
}
}
self.showMark("Povedlo se")
}
}
else {
postSchool(school, clas: clas, oldSchool: "")
}
defaults.setValue(clas, forKey: "class")
defaults.setValue(school, forKey: "schoolUrl")
defaults.set(professorStudentSegment.selectedSegmentIndex, forKey: "segmentIndex")
return false
}
func postSchool(_ school: String, clas: String, oldSchool: String) {
let dataController = DataController()
//When school changes, clas should as well (change of properties ...)
if let oldClas = defaults.value(forKey: "class") as? String {
dataController.deleteProperty(oldClas, school: oldSchool)
}
dataController.postSchool(school, completion: {
result in
if result == "Povedlo se" {
self.defaults.set(true, forKey: "isUrlRight")
dataController.postProperty(clas, school: school)
}
else {
self.defaults.set(false, forKey: "isUrlRight")
}
self.showMark(result)
})
}
func showMark(_ message: String) {
DispatchQueue.main.async(execute: {
SwiftSpinner.show(message, animated: false)
let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
SwiftSpinner.hide()
if message == "Povedlo se" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Navigation")
self.present(vc, animated: true, completion: nil)
}
}
})
}
func keyboardNotification(_ notification: Notification) {
guard let userInfo = (notification as NSNotification).userInfo else {return}
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let frameHeight = self.view.frame.height
let keyboardVerticalPosition = endFrame.origin.y
let layout = frameHeight - keyboardVerticalPosition
let isKeyboardHidden = layout == 0
emailButtonBottomLayout?.constant = isKeyboardHidden ? constraint : layout + 20
if layout + 20 > schoolOrigin - 20 + constraint && isKeyboardHidden == false {
emailButtonBottomLayout?.constant = schoolOrigin - 20 + constraint
}
UIView.animate(withDuration: TimeInterval(0), animations: { self.view.layoutIfNeeded() })
}
func dismissKeyboard() {
view.endEditing(true)
}
func goToNextField() {
classTextField.becomeFirstResponder()
}
@IBAction func emailButtonTapped(_ sender: UIButton) {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["[email protected]"])
mail.setSubject("Supl")
guard
let url = schoolTextField.text,
let clas = classTextField.text
else {
mail.setMessageBody("<p>Mám problémy s přihlášením, mohli byste mi pomoct?</p>", isHTML: true)
return
}
mail.setMessageBody("<p>Mám problémy s přihlášením. Zadal jsem url \(url) a třídu \(clas), ale nepodařilo se mi přihlásit.</p>", isHTML: true)
present(mail, animated: true, completion: nil)
} else {
// show failure alert
presentAlert()
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
func presentAlert() {
// Push notifications are disabled in setting by user.
let alertController = UIAlertController(title: "Mail", message: "V nastavení účtů si zapněte 'Pošta'", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Nastavení", style: .default) { (_) -> Void in
let settingsUrl = URL(string: "prefs:root=ACCOUNT_SETTINGS")
if let url = settingsUrl {
UIApplication.shared.openURL(url)
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Zrušit", style: .default, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
|
mit
|
d50eadbf0690a5bf9bbe0edec77b1ec3
| 37.071186 | 164 | 0.602707 | 5.109645 | false | false | false | false |
faimin/Tropos
|
Sources/Tropos/Controllers/AcknowledgementsParser.swift
|
2
|
924
|
import Foundation
struct AcknowledgementsParser {
let propertyList: [String: Any]
init?(fileURL: URL) {
if let plist = NSDictionary(contentsOf: fileURL) as? [String: Any] {
self.propertyList = plist
} else {
return nil
}
}
func displayString() -> String {
let acknowledgements = propertyList["PreferenceSpecifiers"] as? [[String: String]] ?? []
return acknowledgements.reduce("") { string, acknowledgement in
string + displayStringForAcknowledgement(acknowledgement)
}
}
private func displayStringForAcknowledgement(_ acknowledgement: [String: String]) -> String {
let appendNewline: (String) -> String = { "\($0)\n" }
let title = acknowledgement["Title"].map(appendNewline) ?? ""
let footer = acknowledgement["FooterText"].map(appendNewline) ?? ""
return title + footer
}
}
|
mit
|
0e56e81f473529d373ca975893aba670
| 32 | 97 | 0.62013 | 4.941176 | false | false | false | false |
benlangmuir/swift
|
test/Interop/SwiftToCxx/enums/swift-enum-implementation.swift
|
1
|
12646
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Enums -clang-header-expose-public-decls -emit-clang-header-path %t/enums.h
// RUN: %FileCheck %s < %t/enums.h
// RUN: %check-interop-cxx-header-in-clang(%t/enums.h -Wno-unused-private-field -Wno-unused-function)
public enum E {
case x(Double)
case y(UnsafeRawPointer?)
case z(S)
case w(i: Int)
case auto(UnsafeMutableRawPointer)
case foobar
}
public struct S {
public var x: Int64
public init(x: Int64) {
print("S.init()")
self.x = x
}
}
// CHECK: class E final {
// CHECK: enum class cases {
// CHECK-NEXT: x,
// CHECK-NEXT: y,
// CHECK-NEXT: z,
// CHECK-NEXT: w,
// CHECK-NEXT: auto_,
// CHECK-NEXT: foobar
// CHECK-NEXT: };
// CHECK-EMPTY:
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions" // allow use of inline static data member
// CHECK-NEXT: inline const static struct { // impl struct for case x
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::x;
// CHECK-NEXT: }
// CHECK-NEXT: inline E operator()(double val) const;
// CHECK-NEXT: } x;
// CHECK-NEXT: inline bool isX() const;
// CHECK-NEXT: inline double getX() const;
// CHECK-EMPTY:
// CHECK-NEXT: inline const static struct { // impl struct for case y
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::y;
// CHECK-NEXT: }
// CHECK-NEXT: inline E operator()(void const * _Nullable val) const;
// CHECK-NEXT: } y;
// CHECK-NEXT: inline bool isY() const;
// CHECK-NEXT: inline void const * _Nullable getY() const;
// CHECK-EMPTY:
// CHECK-NEXT: inline const static struct { // impl struct for case z
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::z;
// CHECK-NEXT: }
// CHECK-NEXT: inline E operator()(const S &val) const;
// CHECK-NEXT: } z;
// CHECK-NEXT: inline bool isZ() const;
// CHECK-NEXT: inline S getZ() const;
// CHECK-EMPTY:
// CHECK-NEXT: inline const static struct { // impl struct for case w
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::w;
// CHECK-NEXT: }
// CHECK-NEXT: inline E operator()(swift::Int val) const;
// CHECK-NEXT: } w;
// CHECK-NEXT: inline bool isW() const;
// CHECK-NEXT: inline swift::Int getW() const;
// CHECK-EMPTY:
// CHECK-NEXT: inline const static struct { // impl struct for case auto
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::auto_;
// CHECK-NEXT: }
// CHECK-NEXT: inline E operator()(void * _Nonnull val) const;
// CHECK-NEXT: } auto_;
// CHECK-NEXT: inline bool isAuto_() const;
// CHECK-NEXT: inline void * _Nonnull getAuto_() const;
// CHECK-EMPTY:
// CHECK-NEXT: inline const static struct { // impl struct for case foobar
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::foobar;
// CHECK-NEXT: }
// CHECK-NEXT: inline E operator()() const;
// CHECK-NEXT: } foobar;
// CHECK-NEXT: inline bool isFoobar() const;
// CHECK-EMPTY:
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-NEXT: inline operator cases() const {
// CHECK-NEXT: switch (_getEnumTag()) {
// CHECK-NEXT: case 0: return cases::x;
// CHECK-NEXT: case 1: return cases::y;
// CHECK-NEXT: case 2: return cases::z;
// CHECK-NEXT: case 3: return cases::w;
// CHECK-NEXT: case 4: return cases::auto_;
// CHECK-NEXT: case 5: return cases::foobar;
// CHECK-NEXT: default: abort();
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK: private:
// CHECK: inline char * _Nonnull _destructiveProjectEnumData() {
// CHECK-NEXT: auto metadata = _impl::$s5Enums1EOMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: const auto *enumVWTable = reinterpret_cast<swift::_impl::EnumValueWitnessTable *>(vwTable);
// CHECK-NEXT: enumVWTable->destructiveProjectEnumData(_getOpaquePointer(), metadata._0);
// CHECK-NEXT: return _getOpaquePointer();
// CHECK-NEXT: }
// CHECK-NEXT: inline void _destructiveInjectEnumTag(unsigned tag) {
// CHECK-NEXT: auto metadata = _impl::$s5Enums1EOMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: const auto *enumVWTable = reinterpret_cast<swift::_impl::EnumValueWitnessTable *>(vwTable);
// CHECK-NEXT: enumVWTable->destructiveInjectEnumTag(_getOpaquePointer(), tag, metadata._0);
// CHECK-NEXT: }
// CHECK-NEXT: inline unsigned _getEnumTag() const {
// CHECK-NEXT: auto metadata = _impl::$s5Enums1EOMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: const auto *enumVWTable = reinterpret_cast<swift::_impl::EnumValueWitnessTable *>(vwTable);
// CHECK-NEXT: return enumVWTable->getEnumTag(_getOpaquePointer(), metadata._0);
// CHECK-NEXT: }
// CHECK-NEXT: using _impl_x = decltype(x);
// CHECK-NEXT: using _impl_y = decltype(y);
// CHECK-NEXT: using _impl_z = decltype(z);
// CHECK-NEXT: using _impl_w = decltype(w);
// CHECK-NEXT: using _impl_auto = decltype(auto_);
// CHECK-NEXT: using _impl_foobar = decltype(foobar);
// CHECK: };
// CHECK-EMPTY:
// CHECK-NEXT: namespace _impl {
// CHECK-EMPTY:
// CHECK-NEXT: class _impl_E {
// CHECK-NEXT: public:
// CHECK: static inline void initializeWithTake(char * _Nonnull destStorage, char * _Nonnull srcStorage) {
// CHECK-NEXT: auto metadata = _impl::$s5Enums1EOMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: vwTable->initializeWithTake(destStorage, srcStorage, metadata._0);
// CHECK-NEXT: }
// CHECK: namespace Enums {
// CHECK: inline E E::_impl_x::operator()(double val) const {
// CHECK-NEXT: auto result = E::_make();
// CHECK-NEXT: memcpy(result._getOpaquePointer(), &val, sizeof(val));
// CHECK-NEXT: result._destructiveInjectEnumTag(0);
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline bool E::isX() const {
// CHECK-NEXT: return *this == E::x;
// CHECK-NEXT: }
// CHECK-NEXT: inline double E::getX() const {
// CHECK-NEXT: if (!isX()) abort();
// CHECK-NEXT: alignas(E) unsigned char buffer[sizeof(E)];
// CHECK-NEXT: auto *thisCopy = new(buffer) E(*this);
// CHECK-NEXT: char * _Nonnull payloadFromDestruction = thisCopy->_destructiveProjectEnumData();
// CHECK-NEXT: double result;
// CHECK-NEXT: memcpy(&result, payloadFromDestruction, sizeof(result));
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline E E::_impl_y::operator()(void const * _Nullable val) const {
// CHECK-NEXT: auto result = E::_make();
// CHECK-NEXT: memcpy(result._getOpaquePointer(), &val, sizeof(val));
// CHECK-NEXT: result._destructiveInjectEnumTag(1);
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline bool E::isY() const {
// CHECK-NEXT: return *this == E::y;
// CHECK-NEXT: }
// CHECK-NEXT: inline void const * _Nullable E::getY() const {
// CHECK-NEXT: if (!isY()) abort();
// CHECK-NEXT: alignas(E) unsigned char buffer[sizeof(E)];
// CHECK-NEXT: auto *thisCopy = new(buffer) E(*this);
// CHECK-NEXT: char * _Nonnull payloadFromDestruction = thisCopy->_destructiveProjectEnumData();
// CHECK-NEXT: void const * _Nullable result;
// CHECK-NEXT: memcpy(&result, payloadFromDestruction, sizeof(result));
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline E E::_impl_z::operator()(const S &val) const {
// CHECK-NEXT: auto result = E::_make();
// CHECK-NEXT: alignas(S) unsigned char buffer[sizeof(S)];
// CHECK-NEXT: auto *valCopy = new(buffer) S(val);
// CHECK-NEXT: swift::_impl::implClassFor<S>::type::initializeWithTake(result._getOpaquePointer(), swift::_impl::implClassFor<S>::type::getOpaquePointer(*valCopy));
// CHECK-NEXT: result._destructiveInjectEnumTag(2);
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline bool E::isZ() const {
// CHECK-NEXT: return *this == E::z;
// CHECK-NEXT: }
// CHECK-NEXT: inline S E::getZ() const {
// CHECK-NEXT: if (!isZ()) abort();
// CHECK-NEXT: alignas(E) unsigned char buffer[sizeof(E)];
// CHECK-NEXT: auto *thisCopy = new(buffer) E(*this);
// CHECK-NEXT: char * _Nonnull payloadFromDestruction = thisCopy->_destructiveProjectEnumData();
// CHECK-NEXT: return swift::_impl::implClassFor<S>::type::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: swift::_impl::implClassFor<S>::type::initializeWithTake(result, payloadFromDestruction);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline E E::_impl_w::operator()(swift::Int val) const {
// CHECK-NEXT: auto result = E::_make();
// CHECK-NEXT: memcpy(result._getOpaquePointer(), &val, sizeof(val));
// CHECK-NEXT: result._destructiveInjectEnumTag(3);
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline bool E::isW() const {
// CHECK-NEXT: return *this == E::w;
// CHECK-NEXT: }
// CHECK-NEXT: inline swift::Int E::getW() const {
// CHECK-NEXT: if (!isW()) abort();
// CHECK-NEXT: alignas(E) unsigned char buffer[sizeof(E)];
// CHECK-NEXT: auto *thisCopy = new(buffer) E(*this);
// CHECK-NEXT: char * _Nonnull payloadFromDestruction = thisCopy->_destructiveProjectEnumData();
// CHECK-NEXT: swift::Int result;
// CHECK-NEXT: memcpy(&result, payloadFromDestruction, sizeof(result));
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline E E::_impl_auto::operator()(void * _Nonnull val) const {
// CHECK-NEXT: auto result = E::_make();
// CHECK-NEXT: memcpy(result._getOpaquePointer(), &val, sizeof(val));
// CHECK-NEXT: result._destructiveInjectEnumTag(4);
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline bool E::isAuto_() const {
// CHECK-NEXT: return *this == E::auto_;
// CHECK-NEXT: }
// CHECK-NEXT: inline void * _Nonnull E::getAuto_() const {
// CHECK-NEXT: if (!isAuto_()) abort();
// CHECK-NEXT: alignas(E) unsigned char buffer[sizeof(E)];
// CHECK-NEXT: auto *thisCopy = new(buffer) E(*this);
// CHECK-NEXT: char * _Nonnull payloadFromDestruction = thisCopy->_destructiveProjectEnumData();
// CHECK-NEXT: void * _Nonnull result;
// CHECK-NEXT: memcpy(&result, payloadFromDestruction, sizeof(result));
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline E E::_impl_foobar::operator()() const {
// CHECK-NEXT: auto result = E::_make();
// CHECK-NEXT: result._destructiveInjectEnumTag(5);
// CHECK-NEXT: return result;
// CHECK-NEXT: }
// CHECK-NEXT: inline bool E::isFoobar() const {
// CHECK-NEXT: return *this == E::foobar;
// CHECK-NEXT: }
|
apache-2.0
|
b762881710fc5eb3b0c25ad4d29b3a03
| 47.826255 | 233 | 0.646766 | 3.36151 | false | false | false | false |
curoo/IOSKeychain
|
ConfidoIOS/KeychainProtocol.swift
|
3
|
9870
|
//
// KeychainProtocol.swift
// ConfidoIOS
//
// Created by Rudolph van Graan on 11/09/2015.
//
//
import Foundation
public protocol KeyChainAttributeStorage {
var attributes : [String : AnyObject] { get }
subscript(attribute: String) -> AnyObject? { get }
}
extension KeyChainAttributeStorage where Self : KeyChainAttributeStorage {
public subscript(attribute: String) -> AnyObject? {
return attributes[attribute]
}
}
// MARK: KeychainMatchable
// Indicates that items in the IOS keychain of securityClass can matched with keychainMatchPropertyValues()
public protocol KeychainMatchable {
/**
Returns the properties to pass to SecItemCopyMatching() to match IOS keychain items with
:returns: a dictionary of IOS Keychain values (See Apple Documentation)
*/
func keychainMatchPropertyValues() -> [ String: AnyObject ]
var securityClass: SecurityClass { get }
}
// MARK: KeychainFindable
// Marks that the item provides a findInKeychain() method that returns matching keychain items
public protocol KeychainFindable {
associatedtype QueryType : KeychainMatchable
associatedtype ResultType : KeychainItem
static func findInKeychain(_ matchingProperties: QueryType) throws -> ResultType?
}
// This is used to flag specific classes to use the generic findInKeychain() below, otherwise the method needs ot be written by hand
public protocol GenerateKeychainFind : KeychainFindable {
}
extension KeychainFindable where Self : KeychainFindable, Self : GenerateKeychainFind {
public static func findInKeychain(_ matchingProperties: QueryType) throws -> ResultType? {
let keychainItem = try Keychain.fetchItem(matchingDescriptor: matchingProperties)
if let result = keychainItem as? ResultType {
return result
}
throw KeychainError.mismatchedResultType(returnedType: type(of: keychainItem).self, declaredType: QueryType.self)
}
}
// MARK: KeychainMatching
public protocol KeychainMatching {
func keychainMatchPropertyValues() -> KeychainDescriptor
}
extension KeychainItem {
public func keychainMatchPropertyValues() -> KeychainDescriptor {
return KeychainDescriptor(keychainItem: self)
}
}
// MARK: KeychainAddable
// Indicates that the item can be added to the IOS keychain
public protocol KeychainAddable {
associatedtype KeychainClassType : KeychainItem, KeychainFindable
/**
Adds the item to the IOS keychain
:returns: an instance of KeychainClassType
*/
func addToKeychain() throws -> KeychainClassType?
}
//TODO: The two extensions above should be replaced with a generic extension similar to this
//extension KeychainAddable where Self : KeychainAddable, Self : SecItemAddable {
// public func addToKeychain<T>() throws -> T? {
// return addToKeychain(self)
// }
//}
// MARK: SecItemAddable
// Generic Protocol to mark that the item can be added to the IOS Keychain
public protocol SecItemAddable : KeyChainAttributeStorage {
@discardableResult func secItemAdd() throws -> AnyObject?
}
extension SecItemAddable where Self : SecItemAddable, Self : KeychainMatchable {
@discardableResult public func secItemAdd() throws -> AnyObject? {
var item : KeyChainPropertiesData = [ : ]
item += self.attributes
item[String(kSecClass)] = SecurityClass.kSecClass(securityClass)
let itemRef: AnyObject? = try SecurityWrapper.secItemAdd(item)
return itemRef
}
}
// MARK: KeychainItemClass
public protocol KeychainItemClass {
var securityClass: SecurityClass { get }
}
// -MARK: KeychainCommonClassProperties
/**
Properties for Keychain Items of class kSecClassKey
*/
public protocol KeychainCommonClassProperties : KeyChainAttributeStorage {
var itemAccessGroup: String? { get}
//TODO: rename itemLabel to label
var itemLabel: String? { get }
var itemAccessible: Accessible? { get }
/**
@constant kSecAttrAccessControl Specifies a dictionary key whose value
is SecAccessControl instance which contains access control conditions
for item.
*/
var itemAccessControl: SecAccessControl? { get }
/**
@constant kSecAttrTokenID Specifies a dictionary key whose presence
indicates that item is backed by external token. Value of this attribute
is CFStringRef uniquely identifying containing token. When this attribute
is not present, item is stored in internal keychain database.
Note that once item is created, this attribute cannot be changed - in other
words it is not possible to migrate existing items to, from or between tokens.
Currently the only available value for this attribute is
kSecAttrTokenIDSecureEnclave, which indicates that item (private key) is
backed by device's Secure Enclave.
*/
var itemTokenID: String? { get }
}
extension KeychainCommonClassProperties where Self : KeychainCommonClassProperties {
public var itemLabel: String? {
get { return attributes[String(kSecAttrLabel)] as? String }
}
public var itemAccessGroup: String? {
get { return attributes[String(kSecAttrAccessGroup)] as? String }
}
public var itemAccessible: Accessible? {
get {
let accessible = attributes[String(kSecAttrAccessible)] as? String
if let accessible = accessible {
return Accessible(rawValue: accessible)
}
return nil
}
}
public var itemAccessControl: SecAccessControl? {
get {
if let valueRef: AnyObject = attributes[String(kSecAttrAccessControl)] {
if CFGetTypeID(valueRef) == SecAccessControlGetTypeID() {
return (valueRef as! SecAccessControl)
}
}
return nil
}
}
public var itemTokenID: String? {
get {
return attributes[String(kSecAttrTokenID)] as? String
}
}
}
// MARK: KeychainItemMetaData
public protocol KeychainItemMetaData : KeyChainAttributeStorage {
var itemCreationDate: Date? { get }
var itemModificationDate: Date? { get }
}
extension KeychainItemMetaData where Self : KeychainItemMetaData {
public var itemCreationDate: Date? {
get { return attributes[String(kSecAttrCreationDate)] as? Date }
}
public var itemModificationDate: Date? {
get { return attributes[String(kSecAttrModificationDate)] as? Date }
}
}
// MARK: KeychainKeyClassProperties
/**
Properties for Keychain Items of class kSecClassKey
*/
public protocol KeychainKeyClassProperties {
var keySize: Int { get }
var keyPermanent: Bool { get }
var keyClass: KeyClass { get }
var keyAppTag: String? { get }
}
/**
Injects IOS Keychain kSecClassKey properties into conforming items
*/
extension KeychainKeyClassProperties where Self : KeychainKeyClassProperties, Self : KeyChainAttributeStorage {
public var keyAppTag: String? {
get { return attributes[String(kSecAttrApplicationTag)] as? String }
}
public var keyAppLabelString: String? {
get {
if let data = attributes[String(kSecAttrApplicationLabel)] as? Data {
return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String
} else {
return nil
}
}
}
public var keyAppLabelData: Data? {
get {
if let data = attributes[String(kSecAttrApplicationLabel)] as? Data {
return data
} else {
return nil
}
}
}
public var keyClass: KeyClass {
get {
return KeyClass.keyClass(attributes[String(kSecAttrKeyClass)])
}
}
// There is a bug in the Key Chain. You send KeyType as a String (kSecAttrKeyTypeRSA), but what is returned is an NSNumber
public var keyType: KeyType? {
get {
if let intValue = attributes[String(kSecAttrKeyType)] as? Int {
switch intValue {
case 42: return KeyType.rsa
case 73: return KeyType.elypticCurve
default : return nil
}
} else if let stringValue = attributes[String(kSecAttrKeyType)] as? String {
return KeyType.init(rawValue: stringValue)
}
return nil
}
}
public var keySize: Int {
get {
return (attributes[String(kSecAttrKeySizeInBits)] as? NSNumber)!.intValue
}
}
public var keyPermanent: Bool {
get {
return (attributes[String(kSecAttrIsPermanent)] as? NSNumber)?.boolValue ?? false
}
}
}
// MARK: KeychainCertificateClassProperties
/**
Properties for Keychain Items of class kSecClassCertificate
*/
public protocol KeychainCertificateClassProperties {
var subjectX509Data: Data { get }
var issuerX509Data: Data { get }
var serialNumberX509Data: Data { get }
var subjectKeyID: AnyObject { get }
var publicKeyHash: AnyObject { get }
}
/**
Injects IOS Keychain kSecClassCertificate properties into conforming items
*/
extension KeychainCertificateClassProperties where Self : KeychainCertificateClassProperties, Self : KeyChainAttributeStorage {
public var subjectX509Data: Data {
get { return attributes[kSecAttrSubject as String] as! Data }
}
public var issuerX509Data: Data {
get { return attributes[kSecAttrIssuer as String] as! Data }
}
public var serialNumberX509Data: Data {
get { return attributes[kSecAttrSerialNumber as String] as! Data }
}
public var subjectKeyID: AnyObject {
get { return attributes[kSecAttrSubjectKeyID as String]! }
}
public var publicKeyHash: AnyObject {
get { return attributes[kSecAttrPublicKeyHash as String]! }
}
}
|
mit
|
ab63f667e4b54a97dfebaf8df711bea7
| 30.736334 | 132 | 0.687234 | 4.92515 | false | false | false | false |
talentsparkio/UIViewAnimateWithDuration
|
UIViewAnimateWithDuration/BackgroundImageExampleViewController.swift
|
1
|
937
|
//
// BackgroundImageExampleViewController.swift
// UIViewAnimateWithDuration
//
// Created by Nick Chen on 8/30/15.
// Copyright © 2015 Nick Chen. All rights reserved.
//
import UIKit
class BackgroundImageExampleViewController: UIViewController {
@IBOutlet weak var dialogView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let scale = CGAffineTransformMakeScale(0.25, 0.25)
let translate = CGAffineTransformMakeTranslation(0, 600)
dialogView.transform = CGAffineTransformConcat(scale, translate)
UIView.animateWithDuration(1.0, animations: {
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.dialogView.transform = CGAffineTransformConcat(scale, translate)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
bsd-3-clause
|
e03f1a8e1433b0ec67e6bb0b98bb0047
| 28.25 | 81 | 0.696581 | 5.171271 | false | false | false | false |
VojtaStavik/ProtocolUI
|
ProtocolUITests/TitleShadowColorForStateProtocolTest.swift
|
1
|
1618
|
//
// TitleShadowColorForStateProtocolTest.swift
// ProtocolUI
//
// Created by STRV on 20/08/15.
// Copyright © 2015 Vojta Stavik. All rights reserved.
//
import XCTest
@testable import ProtocolUI
extension TitleShadowColorForState {
var pTitleShadowColorForState : [(UIControlState, UIColor)] { return TitleShadowColorForStateProtocolTest.testValue }
}
class TitleShadowColorForStateProtocolTest: XCTestCase {
typealias CurrentTestProtocol = TitleShadowColorForState
typealias CurrentTestValueType = [(UIControlState, UIColor)]
static let color1 = UIColor(red: 0.1, green: 0.2, blue: 0.3, alpha: 0.4)
static let color2 = UIColor(red: 0.2, green: 0.3, blue: 0.4, alpha: 0.5)
static let testValue : CurrentTestValueType = [
(UIControlState.Normal, TitleShadowColorForStateProtocolTest.color1), (UIControlState.Highlighted, TitleShadowColorForStateProtocolTest.color2)
]
func testUIButton() {
class TestView : UIButton, CurrentTestProtocol { }
let test1 = TestView()
test1.applyProtocolUIAppearance()
XCTAssertEqual(test1.titleShadowColorForState(.Normal), self.dynamicType.color1)
XCTAssertEqual(test1.titleShadowColorForState(.Highlighted), self.dynamicType.color2)
let test2 = TestView()
test2.prepareForInterfaceBuilder()
XCTAssertEqual(test2.titleShadowColorForState(.Normal), self.dynamicType.color1)
XCTAssertEqual(test2.titleShadowColorForState(.Highlighted), self.dynamicType.color2)
}
}
|
mit
|
e18f75ebb53b5c9856c80057503965c1
| 32.708333 | 151 | 0.701917 | 4.755882 | false | true | false | false |
soffes/valio
|
Valio/SectionHeaderView.swift
|
1
|
1590
|
//
// SectionHeaderView.swift
// Valio
//
// Created by Sam Soffes on 6/6/14.
// Copyright (c) 2014 Sam Soffes. All rights reserved.
//
import UIKit
class SectionHeaderView: UIView {
// MARK: - Properties
lazy var titleLabel: UILabel = {
let label = UILabel()
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.font = UIFont(name: "Avenir", size: 18)
label.textColor = UIColor(red: 0.514, green: 0.525, blue: 0.541, alpha: 1)
return label
}()
lazy var lineView: UIView = {
let view = UIView()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
view.backgroundColor = UIColor(red: 0.906, green: 0.914, blue: 0.918, alpha: 1)
return view
}()
// MARK: - Initialiers
convenience init() {
self.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 1, alpha: 0.95)
addSubview(titleLabel)
addSubview(lineView)
let views = [
"titleLabel": titleLabel,
"lineView": lineView
]
let metrics = [
"verticalMargin": 8
]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[titleLabel]|", options: nil, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(verticalMargin)-[titleLabel]-(verticalMargin)-[lineView(1)]|", options: nil, metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[lineView]|", options: nil, metrics: metrics, views: views))
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
mit
|
f88164f251b92d559d7c33bc3d6e265b
| 25.065574 | 179 | 0.701887 | 3.785714 | false | false | false | false |
digice/ios-dvm-boilerplate
|
Device/DeviceData.swift
|
1
|
2244
|
//
// DeviceData.swift
// DVM-Boilerplate
//
// Created by Digices LLC on 3/30/17.
// Copyright © 2017 Digices LLC. All rights reserved.
//
class DeviceData : NSObject, NSCoding {
// MARK: - Properties
// unique device identifier
let uuid : String
// optional device name
var name : String?
// optional device token
var token : String?
// creates a default object
override init() {
self.uuid = UUID().uuidString
}
// MARK: - NSCoding Methods
// creates object from userdefaults
required init?(coder aDecoder: NSCoder) {
self.uuid = aDecoder.decodeObject(forKey: "uuid") as! String
let n = aDecoder.decodeObject(forKey: "name") as! String
if n != "Unnamed Device" {
self.name = n
}
let t = aDecoder.decodeObject(forKey: "token") as! String
if t != "nil" {
self.token = t
}
}
// stores object in defaults
func encode(with aCoder: NSCoder) {
aCoder.encode(self.uuid, forKey: "uuid")
// conditionally store device name
if let n = self.name {
aCoder.encode(n, forKey: "name")
} else {
aCoder.encode("Unnamed Device", forKey: "name")
}
// conditionally store device name
if let t = self.token {
aCoder.encode(t, forKey: "token")
} else {
aCoder.encode("nil", forKey: "token")
}
}
// MARK: - Custom Methods
// returns a string to use as the body of an API request
func httpBody() -> String {
// initialize empty dictionary
var params : [String:String] = [:]
// define params
params["i"] = self.uuid
if let n = self.name {
params["n"] = n
}
if let t = self.token {
params["t"] = t
}
// build string
var returnStr = ""
var i = 1
let c = params.count
for (key, value) in params {
returnStr.append("\(key)=\(value)")
if i < c {
returnStr.append("&")
}
i += 1
}
return returnStr
}
// update local properties from a dictionary, i.e. from an API response
func updateFromDict(dict: [String:String]) {
if let t = dict["token"] {
self.token = t
}
if let n = dict["name"] {
self.name = n
}
}
}
|
mit
|
9d05c4ca599d14f2c1d06500c13c38b9
| 18.504348 | 73 | 0.570218 | 3.860585 | false | false | false | false |
blue42u/swift-t
|
stc/tests/571-range-2.swift
|
4
|
958
|
import assert;
import io;
main {
float x[];
x = [1.0:2.0];
assertEqual(x[0], 1.0, "x[0]");
assertEqual(x[1], 2.0, "x[1]");
assertEqual(size(x), 2, "len(x)");
trace("x", repr(x));
foreach y in [1.0:10.0] {
printf("y=%f", y);
}
y_range = [1.0:10.0];
assertEqual(size(y_range), 10, "size(y)");
assertEqual(y_range[0], 1.0, "y[0]");
assertEqual(y_range[9], 10.0, "y[9]");
foreach z in [0:1004.9:7.5] {
printf("z=%f", z);
}
z_range = [0:1004.9:7.5];
assertEqual(size(z_range), 134, "size(z)");
assertEqual(z_range[0], 0.0, "z[0]");
assertEqual(z_range[20], 150.0, "z[20]");
foreach a in [95.5:95.51:0.1] {
printf("a=%f", a);
}
a_range = [95.5:95.51:0.1];
assertEqual(size(a_range), 1, "size(a)");
assertEqual(a_range[0], 95.5, "a[0]");
foreach b in [0:-1.0] {
assert(false, "Range loop should not run");
}
b_range = [0:-1.0];
assertEqual(size(b_range), 0, "size(b)");
}
|
apache-2.0
|
b5b2d5afc2c24ee0186e208019749f63
| 18.958333 | 47 | 0.522965 | 2.31401 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Utility/Interpolatable/InterpolatableExtensions.swift
|
1
|
5350
|
//
// InterpolatableExtensions.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import Foundation
import CoreGraphics
extension Vector1D: Interpolatable {
func interpolateTo(_ to: Vector1D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Vector1D {
return value.interpolateTo(to.value, amount: amount).vectorValue
}
}
extension Vector2D: Interpolatable {
func interpolateTo(_ to: Vector2D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Vector2D {
return pointValue.interpolateTo(to.pointValue, amount: CGFloat(amount), spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent).vector2dValue
}
}
extension Vector3D: Interpolatable {
func interpolateTo(_ to: Vector3D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Vector3D {
if spatialInTangent != nil || spatialOutTangent != nil {
// TODO Support third dimension spatial interpolation
let point = pointValue.interpolateTo(to.pointValue, amount: amount, spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent)
return Vector3D(x: point.x,
y: point.y,
z: CGFloat(z.interpolateTo(to.z, amount: amount)))
}
return Vector3D(x: x.interpolateTo(to.x, amount: amount),
y: y.interpolateTo(to.y, amount: amount),
z: z.interpolateTo(to.z, amount: amount))
}
}
extension Color: Interpolatable {
/// Initialize a new color with Hue Saturation and Value
init(h: Double, s: Double, v: Double, a: Double) {
let i = floor(h * 6)
let f = h * 6 - i
let p = v * (1 - s);
let q = v * (1 - f * s)
let t = v * (1 - (1 - f) * s)
switch (i.truncatingRemainder(dividingBy: 6)) {
case 0:
self.r = v
self.g = t
self.b = p
case 1:
self.r = q
self.g = v
self.b = p
case 2:
self.r = p
self.g = v
self.b = t
case 3:
self.r = p
self.g = q
self.b = v
case 4:
self.r = t
self.g = p
self.b = v
case 5:
self.r = v
self.g = p
self.b = q
default:
self.r = 0
self.g = 0
self.b = 0
}
self.a = a
}
/// Hue Saturation Value of the color.
var hsva: (h: Double, s: Double, v: Double, a: Double) {
let maxValue = max(r, g, b)
let minValue = min(r, g, b)
var h: Double, s: Double, v: Double = maxValue
let d = maxValue - minValue
s = maxValue == 0 ? 0 : d / maxValue;
if (maxValue == minValue) {
h = 0; // achromatic
} else {
switch (maxValue) {
case r: h = (g - b) / d + (g < b ? 6 : 0)
case g: h = (b - r) / d + 2
case b: h = (r - g) / d + 4
default: h = maxValue
}
h = h / 6
}
return (h: h, s: s, v: v, a: a)
}
init(y: Double, u: Double, v: Double, a: Double) {
// From https://www.fourcc.org/fccyvrgb.php
self.r = y + 1.403 * v
self.g = y - 0.344 * u
self.b = y + 1.770 * u
self.a = a
}
var yuv: (y: Double, u: Double, v: Double, a: Double) {
/// From https://www.fourcc.org/fccyvrgb.php
let y = 0.299 * r + 0.587 * g + 0.114 * b
let u = -0.14713 * r - 0.28886 * g + 0.436 * b
let v = 0.615 * r - 0.51499 * g - 0.10001 * b
return (y: y, u: u, v: v, a: a)
}
func interpolateTo(_ to: Color, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Color {
return Color(r: r.interpolateTo(to.r, amount: amount),
g: g.interpolateTo(to.g, amount: amount),
b: b.interpolateTo(to.b, amount: amount),
a: a.interpolateTo(to.a, amount: amount))
}
}
extension CurveVertex: Interpolatable {
func interpolateTo(_ to: CurveVertex, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> CurveVertex {
return CurveVertex(point: point.interpolate(to.point, amount: amount),
inTangent: inTangent.interpolate(to.inTangent, amount: amount),
outTangent: outTangent.interpolate(to.outTangent, amount: amount))
}
}
extension BezierPath: Interpolatable {
func interpolateTo(_ to: BezierPath, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> BezierPath {
var newPath = BezierPath()
for i in 0..<min(elements.count, to.elements.count) {
let fromVertex = elements[i].vertex
let toVertex = to.elements[i].vertex
newPath.addVertex(fromVertex.interpolateTo(toVertex, amount: amount, spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent))
}
return newPath
}
}
extension TextDocument: Interpolatable {
func interpolateTo(_ to: TextDocument, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> TextDocument {
if amount == 1 {
return to
}
return self
}
}
extension Array: Interpolatable where Element == Double {
func interpolateTo(_ to: Array<Element>, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Array<Element> {
var returnArray = [Double]()
for i in 0..<self.count {
returnArray.append(self[i].interpolateTo(to[i], amount: amount))
}
return returnArray
}
}
|
mit
|
6c3d7bce1df52c369539b9fd78139fa8
| 30.470588 | 163 | 0.608224 | 3.476283 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/PasscodeLockController.swift
|
1
|
19040
|
//
// PasscodeLockController.swift
// TelegramMac
//
// Created by keepcoder on 10/01/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import Postbox
import SwiftSignalKit
import LocalAuthentication
import BuildConfig
private class TouchIdContainerView : View {
fileprivate let button: TitleButton = TitleButton()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(button)
button.scaleOnClick = true
button.autohighlight = false
button.style = ControlStyle(font: .medium(.title), foregroundColor: .white, backgroundColor: theme.colors.accent, highlightColor: theme.colors.accent)
button.set(font: .medium(.title), for: .Normal)
button.set(color: .white, for: .Normal)
button.set(text: strings().passcodeUseTouchId, for: .Normal)
button.set(image: theme.icons.passcodeTouchId, for: .Normal)
button.layer?.cornerRadius = 18
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
_ = button.sizeToFit(NSMakeSize(16, 0), NSMakeSize(0, 36), thatFit: true)
button.centerX(y: frame.height - button.frame.height)
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
let (text, layout) = TextNode.layoutText(NSAttributedString.initialize(string: strings().passcodeOr, color: theme.chatServiceItemTextColor, font: .normal(.title)), theme.colors.background, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .center)
let f = focus(text.size)
layout.draw(NSMakeRect(f.minX, 0, f.width, f.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor)
ctx.setFillColor(theme.chatServiceItemTextColor.cgColor)
ctx.fill(NSMakeRect(0, floorToScreenPixels(backingScaleFactor, f.height / 2), f.minX - 10, .borderSize))
ctx.setFillColor(theme.chatServiceItemTextColor.cgColor)
ctx.fill(NSMakeRect(f.maxX + 10, floorToScreenPixels(backingScaleFactor, f.height / 2), f.minX - 10, .borderSize))
}
}
final class PasscodeField : NSSecureTextField {
override func resignFirstResponder() -> Bool {
(self.delegate as? PasscodeLockView)?.controlTextDidBeginEditing(Notification(name: NSControl.textDidChangeNotification))
return super.resignFirstResponder()
}
override func becomeFirstResponder() -> Bool {
(self.delegate as? PasscodeLockView)?.controlTextDidEndEditing(Notification(name: NSControl.textDidChangeNotification))
return super.becomeFirstResponder()
}
}
class PasscodeLockView : Control, NSTextFieldDelegate {
private let backgroundView: BackgroundView = BackgroundView(frame: .zero)
private let visualEffect: NSVisualEffectView = NSVisualEffectView(frame: .zero)
fileprivate let nameView:TextView = TextView()
let input:PasscodeField
private let nextButton:ImageButton = ImageButton()
private var hasTouchId:Bool = false
private let touchIdContainer:TouchIdContainerView = TouchIdContainerView(frame: NSMakeRect(0, 0, 240, 76))
fileprivate let logoutTextView:TextView = TextView()
let value:ValuePromise<String> = ValuePromise(ignoreRepeated: false)
var logoutImpl:() -> Void = {}
fileprivate var useTouchIdImpl:() -> Void = {}
private let inputContainer: View = View()
private var fieldState: SearchFieldState = .Focus
required init(frame frameRect: NSRect) {
input = PasscodeField(frame: NSZeroRect)
input.stringValue = ""
backgroundView.useSharedAnimationPhase = false
super.init(frame: frameRect)
addSubview(backgroundView)
// addSubview(visualEffect)
visualEffect.state = .active
visualEffect.blendingMode = .withinWindow
autoresizingMask = [.width, .height]
self.backgroundColor = .clear
nextButton.autohighlight = false
nextButton.set(background: theme.colors.accentIcon, for: .Normal)
nextButton.set(image: theme.icons.passcodeLogin, for: .Normal)
nextButton.setFrameSize(26, 26)
nextButton.scaleOnClick = true
nextButton.layer?.cornerRadius = nextButton.frame.height / 2
nameView.userInteractionEnabled = false
nameView.isSelectable = false
addSubview(nextButton)
// addSubview(nameView)
addSubview(inputContainer)
addSubview(logoutTextView)
addSubview(touchIdContainer)
input.isBordered = false
input.usesSingleLineMode = true
input.isBezeled = false
input.focusRingType = .none
input.delegate = self
input.drawsBackground = false
nameView.disableBackgroundDrawing = true
logoutTextView.disableBackgroundDrawing = true
inputContainer.backgroundColor = theme.colors.grayBackground
inputContainer.layer?.cornerRadius = .cornerRadius
inputContainer.addSubview(input)
let attr = NSMutableAttributedString()
_ = attr.append(string: strings().passcodeEnterPasscodePlaceholder, color: theme.colors.grayText, font: .medium(17))
//attr.setAlignment(.center, range: attr.range)
input.placeholderAttributedString = attr
input.cell?.usesSingleLineMode = true
input.cell?.wraps = false
input.cell?.isScrollable = true
input.font = .normal(.title)
input.textView?.insertionPointColor = theme.colors.grayText
input.sizeToFit()
input.target = self
input.action = #selector(checkPasscode)
nextButton.set(handler: { [weak self] _ in
self?.checkPasscode()
}, for: .SingleClick)
touchIdContainer.button.set(handler: { [weak self] _ in
self?.useTouchIdImpl()
}, for: .SingleClick)
updateLocalizationAndTheme(theme: theme)
layout()
}
var containerBgColor: NSColor {
switch theme.controllerBackgroundMode {
case .gradient:
return theme.chatServiceItemColor
case .background:
return theme.chatServiceItemColor
default:
if theme.chatBackground == theme.chatServiceItemColor {
return theme.colors.grayBackground
}
}
return theme.chatServiceItemColor
}
var secondaryColor: NSColor {
switch theme.controllerBackgroundMode {
case .gradient:
return theme.chatServiceItemTextColor
case .background:
return theme.chatServiceItemTextColor
default:
if theme.chatBackground == theme.chatServiceItemColor {
return theme.colors.text
}
}
return theme.chatServiceItemTextColor
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
let theme = theme as! TelegramPresentationTheme
backgroundColor = theme.colors.background
input.backgroundColor = .clear
input.textView?.insertionPointColor = secondaryColor;
input.textColor = secondaryColor
inputContainer.background = containerBgColor
backgroundView.backgroundMode = theme.controllerBackgroundMode
let placeholder = NSMutableAttributedString()
_ = placeholder.append(string: strings().passcodeEnterPasscodePlaceholder, color: theme.chatServiceItemTextColor, font: .normal(.title))
input.placeholderAttributedString = placeholder
if #available(macOS 10.14, *) {
visualEffect.material = .underWindowBackground
} else {
visualEffect.material = theme.colors.isDark ? .ultraDark : .light
}
let logoutAttr = parseMarkdownIntoAttributedString(strings().passcodeLostDescription, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: .normal(.text), textColor: theme.chatServiceItemTextColor), bold: MarkdownAttributeSet(font: .bold(.text), textColor: theme.chatServiceItemTextColor), link: MarkdownAttributeSet(font: .bold(.text), textColor: secondaryColor == theme.chatServiceItemTextColor ? theme.chatServiceItemTextColor : theme.colors.link), linkAttribute: { contents in
return (NSAttributedString.Key.link.rawValue, inAppLink.callback(contents, {_ in}))
}))
logoutTextView.isSelectable = false
let logoutLayout = TextViewLayout(logoutAttr, alignment: .center)
logoutLayout.interactions = TextViewInteractions(processURL:{ [weak self] _ in
self?.logoutImpl()
})
logoutLayout.measure(width: frame.width - 40)
if theme.bubbled {
logoutLayout.generateAutoBlock(backgroundColor: theme.chatServiceItemColor)
}
logoutTextView.set(layout: logoutLayout)
let layout = TextViewLayout(.initialize(string: strings().passlockEnterYourPasscode, color: theme.chatServiceItemTextColor, font: .medium(17)), alignment: .center)
layout.measure(width: frame.width - 40)
if theme.bubbled {
layout.generateAutoBlock(backgroundColor: theme.chatServiceItemColor)
}
nameView.update(layout)
}
override func mouseMoved(with event: NSEvent) {
}
func controlTextDidChange(_ obj: Notification) {
change(state: fieldState, animated: true)
backgroundView.doAction()
}
func controlTextDidBeginEditing(_ obj: Notification) {
change(state: .Focus, animated: true)
input.textView?.insertionPointColor = secondaryColor
}
func controlTextDidEndEditing(_ obj: Notification) {
window?.makeFirstResponder(input)
input.textView?.insertionPointColor = secondaryColor
}
private func change(state: SearchFieldState, animated: Bool) {
self.fieldState = state
switch state {
case .Focus:
input._change(size: NSMakeSize(inputContainer.frame.width - 20, input.frame.height), animated: animated)
input._change(pos: NSMakePoint(10, input.frame.minY), animated: animated)
nextButton.change(opacity: 1, animated: animated)
nextButton._change(pos: NSMakePoint(inputContainer.frame.maxX + 10, nextButton.frame.minY), animated: animated)
case .None:
input.sizeToFit()
let f = inputContainer.focus(input.frame.size)
input._change(pos: NSMakePoint(f.minX, input.frame.minY), animated: animated)
nextButton.change(opacity: 0, animated: animated)
nextButton._change(pos: NSMakePoint(inputContainer.frame.maxX - nextButton.frame.width, nextButton.frame.minY), animated: animated)
}
}
@objc func checkPasscode() {
value.set(input.stringValue)
}
func update(hasTouchId: Bool) {
self.hasTouchId = hasTouchId
if hasTouchId {
showTouchIdUI()
} else {
hideTouchIdUI()
}
input.stringValue = ""
needsLayout = true
}
func updateAndSetValue() {
self.value.set(self.input.stringValue)
self.backgroundView.doAction()
}
private func showTouchIdUI() {
touchIdContainer.isHidden = false
}
private func hideTouchIdUI() {
touchIdContainer.isHidden = true
}
override func layout() {
super.layout()
backgroundView.frame = bounds
backgroundView.updateLayout(size: frame.size, transition: .immediate)
visualEffect.frame = bounds
inputContainer.setFrameSize(200, 36)
input.setFrameSize(inputContainer.frame.width - 20, input.frame.height)
input.center()
inputContainer.layer?.cornerRadius = inputContainer.frame.height / 2
logoutTextView.resize(frame.width - 40, blockColor: theme.chatServiceItemColor)
nameView.resize(frame.width - 40, blockColor: theme.chatServiceItemColor)
inputContainer.center()
inputContainer.setFrameOrigin(NSMakePoint(inputContainer.frame.minX - (nextButton.frame.width + 10) / 2, inputContainer.frame.minY))
touchIdContainer.centerX(y: inputContainer.frame.maxY + 10)
nextButton.setFrameOrigin(inputContainer.frame.maxX + 10, inputContainer.frame.minY + (inputContainer.frame.height - nextButton.frame.height) / 2)
nameView.centerX(y: inputContainer.frame.minY - nameView.frame.height - 10)
logoutTextView.centerX(y: frame.height - logoutTextView.frame.height - 10)
change(state: fieldState, animated: false)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class PasscodeLockController: ModalViewController {
let accountManager: AccountManager<TelegramAccountManagerTypes>
private let useTouchId: Bool
private let appearanceDisposable = MetaDisposable()
private let disposable:MetaDisposable = MetaDisposable()
private let valueDisposable = MetaDisposable()
private let logoutDisposable = MetaDisposable()
private let _doneValue:Promise<Bool> = Promise(false)
private let laContext = LAContext()
var doneValue:Signal<Bool, NoError> {
return _doneValue.get()
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
}
private let updateCurrectController: ()->Void
private let logoutImpl:() -> Signal<Never, NoError>
init(_ accountManager: AccountManager<TelegramAccountManagerTypes>, useTouchId: Bool, logoutImpl:@escaping()->Signal<Never, NoError> = { .complete() }, updateCurrectController: @escaping()->Void) {
self.accountManager = accountManager
self.logoutImpl = logoutImpl
self.useTouchId = useTouchId
self.updateCurrectController = updateCurrectController
super.init(frame: NSMakeRect(0, 0, 350, 350))
self.bar = .init(height: 0)
}
override var isVisualEffectBackground: Bool {
return false
}
override var isFullScreen: Bool {
return true
}
override var background: NSColor {
return self.containerBackground
}
private var genericView:PasscodeLockView {
return self.view as! PasscodeLockView
}
private func checkNextValue(_ passcode: String) {
let appEncryption = AppEncryptionParameters(path: accountManager.basePath.nsstring.deletingLastPathComponent)
appEncryption.applyPasscode(passcode)
if appEncryption.decrypt() != nil {
self._doneValue.set(.single(true))
self.close()
} else {
genericView.input.shake()
}
}
override func windowDidBecomeKey() {
super.windowDidBecomeKey()
if NSApp.isActive {
// callTouchId()
}
}
override func windowDidResignKey() {
super.windowDidResignKey()
if !NSApp.isActive {
// invalidateTouchId()
}
}
func callTouchId() {
if laContext.canUseBiometric {
laContext.evaluatePolicy(.applicationPolicy, localizedReason: strings().passcodeUnlockTouchIdReason) { (success, evaluateError) in
if (success) {
Queue.mainQueue().async {
self._doneValue.set(.single(true))
self.close()
}
}
}
}
}
override var cornerRadius: CGFloat {
return 0
}
func invalidateTouchId() {
laContext.invalidate()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.updateCurrectController()
}
override func viewDidLoad() {
super.viewDidLoad()
appearanceDisposable.set(appearanceSignal.start(next: { [weak self] appearance in
self?.updateLocalizationAndTheme(theme: appearance.presentation)
}))
genericView.logoutImpl = { [weak self] in
guard let window = self?.window else { return }
confirm(for: window, information: strings().accountConfirmLogoutText, successHandler: { [weak self] _ in
guard let `self` = self else { return }
_ = showModalProgress(signal: self.logoutImpl(), for: window).start(completed: { [weak self] in
delay(0.2, closure: { [weak self] in
self?.close()
})
})
})
}
genericView.useTouchIdImpl = { [weak self] in
self?.callTouchId()
}
valueDisposable.set((genericView.value.get() |> deliverOnMainQueue).start(next: { [weak self] value in
self?.checkNextValue(value)
}))
genericView.update(hasTouchId: useTouchId)
readyOnce()
}
override var closable: Bool {
return false
}
override func escapeKeyAction() -> KeyHandlerResult {
return .invoked
}
override func returnKeyAction() -> KeyHandlerResult {
self.genericView.updateAndSetValue()
return .invoked
}
override func firstResponder() -> NSResponder? {
if !(window?.firstResponder is NSText) {
return genericView.input
}
let editor = self.window?.fieldEditor(true, for: genericView.input)
if window?.firstResponder != editor {
return genericView.input
}
return editor
}
override var containerBackground: NSColor {
return theme.colors.background.withAlphaComponent(1.0)
}
override var handleEvents: Bool {
return true
}
override var handleAllEvents: Bool {
return true
}
override var responderPriority: HandlerPriority {
return .supreme
}
override var shouldCloseAllTheSameModals: Bool {
return false
}
deinit {
disposable.dispose()
logoutDisposable.dispose()
valueDisposable.dispose()
appearanceDisposable.dispose()
self.window?.removeAllHandlers(for: self)
}
override func viewClass() -> AnyClass {
return PasscodeLockView.self
}
}
|
gpl-2.0
|
1ce862fa3fb3f19057e1521e9d630161
| 33.806216 | 499 | 0.639109 | 5.113887 | false | false | false | false |
renatoguarato/cidadaoalerta
|
apps/ios/cidadaoalerta/cidadaoalerta/ViewController.swift
|
1
|
3165
|
//
// ViewController.swift
// cidadaoalerta
//
// Created by Renato Guarato on 11/03/16.
// Copyright © 2016 Renato Guarato. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let section = ["Despesas", "Receitas", "Convênios", "Sanções", "Servidores", "CEPIM", "Imóveis Funcionais"]
let items = [["Recursos registrados (mensais): R$ 17.230.389.176.818,80", "Quantidade de informações registradas: 2.110.034.573"],
["Dados atualizados em: 7 de Março de 2016", "Recursos envolvidos: 14.002.041.307.201,60", "Quantidade de informações registradas: 97.807"],
["Dados atualizados em: 28 de Fevereiro de 2016", "Recursos envolvidos: R$ 1.117.827.701.503,73", "Quantidade de informações registradas: 468.893"],
["Dados atualizados em: 8 de Março de 2016 (CEIS e CNEP) e 1 de Março de 2016 (servidores punidos)", "Quantidade de informações registradas CEIS: 12.229", "Quantidade de informações registradas CNEP: 1", "Quantidade de informações registradas: 3.568 (servidores punidos)"],
["Dados atualizados em: 31 de Janeiro de 2016 (servidores) e 1 de Março de 2016 (servidores punidos)", "Quantidade de informações registradas: 1.173.179 (servidores)", "Quantidade de informações registradas: 3.568 (servidores punidos)"],
["Dados atualizados em: 7 de Março de 2016", "Quantidade de informações registradas: 3.100"],
["Dados atualizados em: 2 de Fevereiro de 2016", "Quantidade de informações registradas: 2.865"]]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 160.0
self.automaticallyAdjustsScrollViewInsets = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let sectionArrays = self.section as [String]? {
return sectionArrays[section]
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.section.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items[section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath)
cell.textLabel?.text = self.items[indexPath.section][indexPath.row]
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
return cell
}
}
|
gpl-3.0
|
84c96be3701264eaec49697b7416fffe
| 40.25 | 281 | 0.678788 | 3.958333 | false | false | false | false |
jtwp470/my-programming-learning-book
|
swift/Basic_syntax.playground/Contents.swift
|
1
|
5342
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
str = "こんにちは"
str = str + "Swift"
// 変数
var num: Int = 3
var hel: String = "Hello"
// Int型を宣言してみる
var test: Int
// println(test) // 初期化されていないので実行できない
test = 4
println(test)
// 型推論
var age = 55
// 定数を宣言する場合はlet
let limit = 50
// limit = 100 // 定数なので変更不可
// StringとCharacter
var name = "太郎"
var char: Character = "あ"
// var char = "あいう" // エラーになる
// 型推論のときはデフォルトでStringと判定される
// 文字列に値を埋め込む式展開
// \(値)という形
var year = 2015
var s = "今年は\(year)年"
// 計算式の結果も埋め込むことができる
var heisei = 27
println("平成\(heisei)年は\(heisei + 1988)年です")
// 論理値
var isTrue: Bool = true
// タプル
var person1: (String, Int) = ("田中二郎", 55)
var person2 = ("田中二郎", 55) // 型推論
// タプルの値を変数に展開する
var (name1, age1) = person1
println(name1)
// いずれかの値が不要な場合
var (_, age2) = person1
// 添字アクセス
var name3 = person1.0
var age3 = person1.1
// タプルの要素に名前付け
var person4 = (name: "田中二郎", age: 55)
var name4 = person4.name
var age4 = person4.age
// 条件判断if
// 基本的にはC言語と同じ. 条件に()がいらない
age = 20
if age == 20 {
println("20歳です");
} else if age > 30 {
println("三十路ですね")
} else {
println("お疲れ様")
}
// switch文
// これも基本的にはC言語と同じだが, breakはいらない
// 省略してもっと便利な機能があるWhere句を用いる.これによって更に細かな条件判断ができる
age = 20
switch age {
case let n where age < 20:
println("\(n)歳は未成年です")
case let n where age == 20:
println("\(n)歳はちょうど成人です")
case let n where age > 20:
println("\(n)歳は成人です")
default:
break
}
// 繰返しの制御構造
var sum = 0
for var i = 1; i <= 10; i++ {
sum += i
}
println(sum)
// for-in文
// クローズドレンジ: a...b aからbまでの数値をイテレート
// ハーフクローズドレンジ: a..<b aからb未満までの数値をイテレート
sum = 0
for num in 1...10 {
sum += num
}
println(sum)
var i = 0
sum = 0
while i <= 10 {
sum += i
i++
}
println(sum)
// オプショナル型: 値が存在しているしていないという2つの状態を持つことができる
var num: Int?
num = 3
num = nil
// オプショナル値をアンラップする
var n: Int? = 4
// var sum = n + 1 // エラーになる
// アンラップして取り出す方法
sum = n! + 4
// 自動的にアンラップする
var n1: Int! = 4
sum = num + 1 // 自動的にアンラップしてくれる
// オプショナルバインディング
// 使用時にnilであるとエラーになるのでオプショナル値を安全に利用できるようにするための書式
var nn: Int? = 3
sum = 0
if let n = nn {
sum = 5 + n
} else {
println("値がありません")
}
// オプショナルチェイニング
// オプショナル型の値の最後に?を記述すると複数のメソッドやプロパティをピリオドで鎖のように連結して実行できる
/*
* 自作の関数を作成する
*/
// 引数と戻り値のない関数
func hello1() {
println("こんにちは")
}
// 戻り値を返す
func hello2() -> String {
return "こんにちは"
}
var helloStr2 = hello2() // 実行例
// 引数を指定する
func hello3(fName: String, lName: String) -> String {
return "こんにちは \(lName + fName)さん"
}
var helloStr3 = hello3("一郎", "田中")
// 外部引数名
func hello4(firstName fName: String, lastName lName: String) -> String {
return "こんにちは \(lName + fName)さん"
}
// 呼び出すとき
var helloStr4 = hello4(firstName: "一郎", lastName: "田中")
// 外部引数名と内部引数名を同じにする
// こんなときは外部引数名を書かずに引数名に#をつければよい.
func hello5(#fName: String, #lName: String) -> String {
return "こんにちは \(lName + fName)さん"
}
var helloStr5 = hello5(fName: "一郎", lName: "田中")
// 引数のデフォルト値と可変長引数
// 外部引数名
func hello6(firstName fName: String, lastName lName: String, greeting: String = "こんにちは") -> String {
return "\(greeting) \(lName + fName)さん"
}
var helloStr6 = hello6(firstName: "一郎", lastName: "田中", greeting: "こんばんは")
// 任意の数の引数を渡す
func sumAll(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
var sum1 = sumAll(1,2,3)
var sum2 = sumAll(8, 4, 5, 2, 1)
// 複数の値を返す (戻り値はタプル)
func maxMin(n1: Double, n2: Double) -> (maxValues: Double, minValue: Double) {
var maxVal = max(n1, n2)
var minVal = min(n1, n2)
return (maxVal, minVal)
}
var (max1, min1) = maxMin(1.4, 3.0)
// クロージャ lambda式てきなもの
var sums = { (num1: Int, num2: Int) -> Int in
return num1 + num2
}
var num3 = sums(4, 5)
|
unlicense
|
f03568423ad15b59df4dd0ec6bc81187
| 17.844221 | 100 | 0.636 | 2.092634 | false | false | false | false |
WhatsTaste/WTImagePickerController
|
Vendor/Controllers/WTPreviewViewController.swift
|
1
|
20844
|
//
// WTPreviewViewController.swift
// WTImagePickerController
//
// Created by Jayce on 2017/2/8.
// Copyright © 2017年 WhatsTaste. All rights reserved.
//
import UIKit
import Photos
protocol WTPreviewViewControllerDelegate: class {
func previewViewControllerDidFinish(_ controller: WTPreviewViewController)
func previewViewController(_ controller: WTPreviewViewController, canSelectAsset asset: PHAsset) -> Bool
func previewViewController(_ controller: WTPreviewViewController, didSelectAsset asset: PHAsset)
func previewViewController(_ controller: WTPreviewViewController, didDeselectAsset asset: PHAsset)
func previewViewController(_ controller: WTPreviewViewController, didChangeOriginal original: Bool)
func previewViewController(_ controller: WTPreviewViewController, didEditWithResult result: WTEditingResult, forAsset asset: PHAsset)
}
public let WTPreviewViewControllerMargin: CGFloat = 10
private let reuseIdentifier = "Cell"
private let controlsViewHeight: CGFloat = 44
class WTPreviewViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, WTEditingViewControllerDelegate, WTPreviewControlsViewDelegate {
convenience init(assets: [PHAsset], editedResults: [String: WTEditingResult]? = nil) {
self.init(nibName: nil, bundle: nil)
self.assets = assets
if let results = editedResults {
self.editedResults = results
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
edgesForExtendedLayout = .all
automaticallyAdjustsScrollViewInsets = false
navigationItem.title = WTIPLocalizedString("Preview")
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: navigationIndicatorView)
view.backgroundColor = UIColor.white
view.addSubview(collectionView)
view.addSubview(controlsView)
view.addConstraint(NSLayoutConstraint.init(item: collectionView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: -WTPreviewViewControllerMargin))
view.addConstraint(NSLayoutConstraint.init(item: view, attribute: .right, relatedBy: .equal, toItem: collectionView, attribute: .right, multiplier: 1, constant: -WTPreviewViewControllerMargin))
view.addConstraint(NSLayoutConstraint.init(item: collectionView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: view, attribute: .bottom, relatedBy: .equal, toItem: collectionView, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: controlsView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: view, attribute: .right, relatedBy: .equal, toItem: controlsView, attribute: .right, multiplier: 1, constant: 0))
if #available(iOS 11.0, *) {
view.addConstraint(NSLayoutConstraint.init(item: view.safeAreaLayoutGuide, attribute: .bottom, relatedBy: .equal, toItem: controlsView, attribute: .bottom, multiplier: 1, constant: 0))
} else {
view.addConstraint(NSLayoutConstraint.init(item: view, attribute: .bottom, relatedBy: .equal, toItem: controlsView, attribute: .bottom, multiplier: 1, constant: 0))
}
controlsView.addConstraint(NSLayoutConstraint.init(item: controlsView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: controlsViewHeight))
updateSelections(atIndex: index)
controlsView.originalActionView.isSelected = original
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard assets.count > 0 else {
return
}
collectionView.collectionViewLayout.invalidateLayout()
if shouldScrollToCurrentIndex {
shouldScrollToCurrentIndex = false
} else {
return
}
if let index = index {
collectionView.scrollToItem(at: IndexPath.init(item: index, section: 0), at: .left, animated: false)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isTranslucent = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.isTranslucent = false
}
override var prefersStatusBarHidden: Bool {
return statusBarHidden
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return assets.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: WTPreviewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! WTPreviewCell
// Configure the cell
let asset = assets[indexPath.item]
// print(#function + "\(indexPath.item):" + asset.localIdentifier)
cell.backgroundColor = view.backgroundColor
cell.representedAssetIdentifier = asset.localIdentifier
cell.singleTapHandler = { [weak self] in
if self == nil {
return
}
self?.toggleHidden()
}
var requestID = self.requestIDs[indexPath.item] ?? 0
let progress = progresses[indexPath.item] ?? 0
// print(#function + ":\(indexPath.item) Using:" + "\(progress)")
cell.contentButton.isHidden = !(failedFlags[indexPath.item] ?? false)
cell.progressView.isHidden = !(requestID != 0)
cell.progressView.progress = progress
if let image = editedImages[asset.localIdentifier] {
cell.contentImageView.image = image
} else {
cell.contentImageView.image = degradedImages[indexPath.item] ?? nil
if requestID == 0 {
// print(#function + ":\(indexPath.item) Downloading begins")
let request = {
requestID = PHImageManager.default().requestFullScreenImage(for: asset, allowsDegraded: true, resultHandler: { [weak self, weak cell, weak asset] (image, info) in
// print(#function + ":\(indexPath.item) Downloading ends with image size" + "\(String(describing: image?.size))")
guard self != nil else {
return
}
self?.requestIDs[indexPath.item] = 0
self?.progresses[indexPath.item] = nil
var degradedImage: UIImage?
var finalImage: UIImage?
if image == nil {
self?.failedFlags[indexPath.item] = true
} else {
self?.failedFlags[indexPath.item] = nil
if (info?[PHImageResultIsDegradedKey] as? NSNumber)?.boolValue ?? false {
let size = CGSize(width: self!.view.bounds.width, height: self!.view.bounds.width)
degradedImage = image!.fitSize(size)
finalImage = degradedImage
} else {
finalImage = image
}
}
self?.degradedImages[indexPath.item] = degradedImage
if cell?.representedAssetIdentifier == asset?.localIdentifier {
cell?.progressView.isHidden = true
cell?.contentButton.isHidden = !(image == nil)
cell?.contentImageView.image = finalImage
}
}, progressHandler: { [weak self, weak cell, weak asset] progress in
guard self != nil else {
return
}
let progressValue = CGFloat(max(progress, 0))
// print(#function + ":\(indexPath.item) Downloading:" + "\(progressValue)")
self?.progresses[indexPath.item] = progressValue
if cell?.representedAssetIdentifier == asset?.localIdentifier {
cell?.progressView.isHidden = false
cell?.progressView.progress = progressValue
}
})
self.requestIDs[indexPath.item] = requestID
}
cell.contentButtonHandler = { (_) in
request()
}
request()
}
}
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let someCell = cell as? WTPreviewCell {
someCell.contentScrollView.zoomScale = someCell.contentScrollView.minimumZoomScale
}
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = floor(collectionView.bounds.width)
let height = floor(collectionView.bounds.height)
let size = CGSize(width: width, height: height)
// print(size)
return size
}
// MARK: UIScrollViewDelegate
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
updateSelections()
}
// MARK: WTEditingViewControllerDelegate
func editingViewController(_ controller: WTEditingViewController, didFinishWithResult result: WTEditingResult, forAsset asset: PHAsset?) {
guard let someAsset = asset else { return }
editedResults[someAsset.localIdentifier] = result
// print(#function + "\(editedResult!.frame)")
if selectedIdentifiers.index(of: someAsset.localIdentifier) == nil {
selectedIdentifiers.append(someAsset.localIdentifier)
}
editedImages[someAsset.localIdentifier] = result.image
if let indexPath = currentIndexPath() {
updateSelections(atIndex: indexPath.item)
collectionView.reloadItems(at: [indexPath])
}
delegate?.previewViewController(self, didEditWithResult: result, forAsset: someAsset)
}
// MARK: WTPreviewControlsViewDelegate
func previewControlsViewDidEdit(_ view: WTPreviewControlsView) {
if let indexPath = currentIndexPath() {
guard indexPath.item < assets.count else {
return
}
let asset = assets[indexPath.item]
let transition:((UIImage) -> Void) = { (image) in
let destinationViewController = WTEditingViewController(image: image, asset: asset, originalResult: self.editedResults[asset.localIdentifier])
destinationViewController.delegate = self
self.navigationController?.pushViewController(destinationViewController, animated: true)
}
PHImageManager.default().requestFullScreenImage(for: asset, allowsDegraded: false, resultHandler: { (image, _) in
guard image != nil else {
return
}
transition(image!)
})
}
}
func previewControlsViewDidSelectOriginal(_ view: WTPreviewControlsView) {
original = !original
delegate?.previewViewController(self, didChangeOriginal: original)
updateSelections()
}
func previewControlsViewDidFinish(_ view: WTPreviewControlsView) {
if selectedIdentifiers.count == 0 {
if let indexPath = currentIndexPath() {
guard indexPath.item < self.assets.count else {
return
}
let asset = self.assets[indexPath.item]
selectedIdentifiers.append(asset.localIdentifier)
delegate?.previewViewController(self, didSelectAsset: asset)
updateSelections(atIndex: indexPath.item)
collectionView.reloadItems(at: [indexPath])
}
}
_ = navigationController?.popViewController(animated: true)
delegate?.previewViewControllerDidFinish(self)
}
// MARK: - Private
@objc private func navigationSelectAction(_ sender: WTSelectionIndicatorView) {
if let indexPath = currentIndexPath() {
let asset = assets[indexPath.item]
if let index = selectedIdentifiers.index(of: asset.localIdentifier) {
// print(#function + "\(index)")
selectedIdentifiers.remove(at: index)
navigationIndicatorView.isSelected = false
delegate?.previewViewController(self, didDeselectAsset: asset)
} else {
if delegate?.previewViewController(self, canSelectAsset: asset) ?? false {
selectedIdentifiers.append(asset.localIdentifier)
navigationIndicatorView.isSelected = true
delegate?.previewViewController(self, didSelectAsset: asset)
}
}
}
}
func updateSelections(atIndex currentIndex: Int? = nil) {
var asset: PHAsset?
if let index = currentIndex {
guard index < assets.count else {
return
}
asset = assets[index]
} else if let indexPath = currentIndexPath() {
guard indexPath.item < assets.count else {
return
}
asset = assets[indexPath.item]
}
if let someAsset = asset {
// navigationItem.title = someAsset.localIdentifier
if selectedIdentifiers.index(of: someAsset.localIdentifier) != nil {
navigationIndicatorView.isSelected = true
} else {
navigationIndicatorView.isSelected = false
}
if !original {
controlsView.originalActionView.contentLabel.text = WTIPLocalizedString("Original")
} else {
controlsView.originalActionView.contentLabel.text = WTIPLocalizedString("Original") + "--"
PHImageManager.default().requestOriginalImage(for: someAsset, resultHandler: { [weak self] (image, _) in
DispatchQueue.global().async {
guard self != nil else {
return
}
guard image != nil else {
return
}
if let data = UIImagePNGRepresentation(image!) {
var result = ""
let step: Double = pow(2, 10)
let count = Double(data.count)
if count < step {
result = String(format: "(%.0fB)", count)
} else if count < pow(step, 2) {
result = String(format: "(%.0fK)", count / step)
} else {
result = String(format: "(%.2fM)", count / pow(step, 2))
}
// print(#function + result)
guard result.lengthOfBytes(using: .utf8) > 0 else {
return
}
DispatchQueue.main.async {
guard self != nil else {
return
}
self!.controlsView.originalActionView.contentLabel.text = self!.WTIPLocalizedString("Original") + result
}
}
}
})
}
}
}
func currentIndexPath() -> IndexPath? {
let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.bounds.size)
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
let visibleIndexPath = collectionView.indexPathForItem(at: visiblePoint)
return visibleIndexPath
}
func toggleHidden() {
statusBarHidden = !statusBarHidden
setNeedsStatusBarAppearanceUpdate()
navigationController?.setNavigationBarHidden(statusBarHidden, animated: true)
view.backgroundColor = statusBarHidden ? UIColor.black : UIColor.white
controlsView.setHidden(statusBarHidden, animated: true)
collectionView.reloadData()
collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: - Properties
weak public var delegate: WTPreviewViewControllerDelegate?
public var tintColor: UIColor? {
didSet {
navigationIndicatorView.tintColor = tintColor
controlsView.tintColor = tintColor
}
}
public var index: Int?
public var pickLimit: Int!
public var original = false {
didSet {
self.controlsView.originalActionView.isSelected = original
}
}
public var selectedIdentifiers = [String]() {
didSet {
self.controlsView.doneBadgeActionView.badge = selectedIdentifiers.count
}
}
public var editedImages = [String: UIImage]()
public var editedResults = [String: WTEditingResult]()
private var assets: [PHAsset]!
lazy private var requestIDs: [Int: PHImageRequestID] = {
let dictionry = [Int: PHImageRequestID]()
return dictionry
}()
lazy private var degradedImages: [Int: UIImage] = {
let dictionry = [Int: UIImage]()
return dictionry
}()
lazy private var failedFlags: [Int: Bool] = {
let dictionry = [Int: Bool]()
return dictionry
}()
private var progresses = [Int: CGFloat]()
private var shouldScrollToCurrentIndex = true
private var statusBarHidden = false
lazy private var navigationIndicatorView: WTSelectionIndicatorView = {
let view = WTSelectionIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
view.translatesAutoresizingMaskIntoConstraints = true
view.backgroundColor = UIColor.clear
view.tintColor = self.tintColor
view.isUserInteractionEnabled = true
view.style = .checkmark
view.insets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
view.addTarget(self, action: #selector(navigationSelectAction(_:)), for: .touchUpInside)
return view
}()
lazy private var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.sectionInset = .zero
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.white
collectionView.alwaysBounceHorizontal = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(WTPreviewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
return collectionView
}()
lazy private var controlsView: WTPreviewControlsView = {
let view = WTPreviewControlsView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
view.delegate = self
view.tintColor = self.tintColor
view.doneBadgeActionView.badge = self.selectedIdentifiers.count
return view
}()
}
|
mit
|
9f0df5e6613547eb780e37e2f20ea2f7
| 44.306522 | 225 | 0.602994 | 5.821508 | false | false | false | false |
linhaosunny/smallGifts
|
小礼品/小礼品/Classes/Module/Classify/Controllers/StrategyViewController.swift
|
1
|
5026
|
//
// StrategyViewController.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/21.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
import SnapKit
import QorumLogs
fileprivate let cellColumns = 2
fileprivate let columnCellHeight:CGFloat = 250.0
fileprivate let cellScale:CGFloat = 2
class StrategyViewController: UIViewController {
//MARK: 属性
fileprivate let strategyIdentifier = "strategyCell"
fileprivate let strategyClassifyIdentifier = "strategyClassifyCell"
fileprivate let sectionIdentifier = "strategySectionCell"
//MARK: 懒加载
lazy var mainView:UICollectionView = { () -> UICollectionView in
let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: StrategyCollectionViewFlowLayout())
view.backgroundColor = UIColor.white
view.showsVerticalScrollIndicator = false
view.showsHorizontalScrollIndicator = false
view.delegate = self
view.dataSource = self
view.register(StrategyColumnViewCell.self, forCellWithReuseIdentifier: self.strategyIdentifier)
view.register(StrategyClassifyViewCell.self, forCellWithReuseIdentifier: self.strategyClassifyIdentifier)
view.register(StrategySectionView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: self.sectionIdentifier)
return view
}()
//MARK: 系统方法
override func viewDidLoad() {
super.viewDidLoad()
setupStrategyView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupStrategyViewSubView()
}
//MARK: 私有方法
private func setupStrategyView() {
view.backgroundColor = UIColor.white
view.addSubview(mainView)
}
private func setupStrategyViewSubView() {
mainView.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
}
}
}
//MARK: 布局样式
class StrategyCollectionViewFlowLayout:UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
minimumLineSpacing = margin
minimumInteritemSpacing = margin * 0.5
scrollDirection = .vertical
itemSize = CGSize(width: collectionView!.bounds.width, height: columnCellHeight)
headerReferenceSize = CGSize(width: ScreenWidth, height: 44)
sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
}
}
//MARK: 代理方法
extension StrategyViewController:UICollectionViewDelegate,UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 6
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: strategyIdentifier, for: indexPath) as! StrategyColumnViewCell
cell.delegate = self
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: strategyClassifyIdentifier, for: indexPath) as! StrategyClassifyViewCell
cell.viewModel = StrategyClassifyViewCellViewModel(withModel: StrategyClassifyViewCellDataModel())
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let section = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: sectionIdentifier, for: indexPath) as! StrategySectionView
section.delegate = self
return section
}
}
//MARK: 代理方法 -> StrategyColumnViewCellDelegate
extension StrategyViewController:StrategyColumnViewCellDelegate {
func strategyColumnViewCellDidSelectItemAt(withCell cell: StrategyColumnViewCell, indexPath: IndexPath) {
if indexPath.item == cell.items - 1 {
QL1("\(indexPath.section)")
navigationController?.pushViewController(AllClassifyViewController(), animated: true)
}else{
QL2("\(indexPath.section)")
navigationController?.pushViewController(ClassifySingleListViewController(), animated: true)
}
}
}
//MARK: 代理方法 -> StrategyColumnViewCellDelegate
extension StrategyViewController:StrategySectionViewDelegate {
func strategySectionViewRightButtonClick() {
navigationController?.pushViewController(AllClassifyViewController(), animated: true)
}
}
|
mit
|
88177f7d137de3ce4b2d47394273e29f
| 35.109489 | 195 | 0.714372 | 5.772462 | false | false | false | false |
CPRTeam/CCIP-iOS
|
Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift
|
3
|
1320
|
//
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public struct BlockModeOption: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
static let none = BlockModeOption(rawValue: 1 << 0)
static let initializationVectorRequired = BlockModeOption(rawValue: 1 << 1)
static let paddingRequired = BlockModeOption(rawValue: 1 << 2)
static let useEncryptToDecrypt = BlockModeOption(rawValue: 1 << 3)
}
|
gpl-3.0
|
b72a1abbdff15e73377234392d961b1a
| 47.851852 | 217 | 0.758908 | 4.396667 | false | false | false | false |
pushuhengyang/dyzb
|
DYZB/DYZB/Classes/Home首页/Views/PageTitleView.swift
|
1
|
6619
|
//
// PageTitleView.swift
// DYZB
//
// Created by xuwenhao on 16/11/12.
// Copyright © 2016年 xuwenhao. All rights reserved.
//
/*
1 标题颜色渐变 滑块可滑动
2 点击 移动
3 接口传出来
*/
import UIKit
//点击协议
protocol PageTitleDelegate :class{
func pageTitleView(pagetitleView : PageTitleView ,didselectIndex : NSInteger) ;
}
private let kNormalRGB : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectRGB : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
private let kDeltaRGB = (kSelectRGB.0 - kNormalRGB.0, kSelectRGB.1 - kNormalRGB.1, kSelectRGB.2 - kNormalRGB.2)
private let kNormalTitleColor = UIColor(red: 85/255.0, green: 85/255.0, blue: 85/255.0, alpha: 1.0)
private let kSelectTitleColor = UIColor(red: 255.0/255.0, green: 128/255.0, blue: 0/255.0, alpha: 1.0)
class PageTitleView: UIView,PageContentDelegate {
var isScroEnable :Bool
var titleArry : [String]
let bottomLineHight :CGFloat = 2;
var titleLableArry = [UILabel]()
var titleLong = [CGFloat]();
var cureIndex : Int = 0;
init(frame :CGRect, isScroEnable : Bool ,titles : [String]){
self.isScroEnable = isScroEnable;
self.titleArry = titles;
titleLableArry = [UILabel]();
super.init(frame: frame);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var scroView : UIScrollView = {
let scroV = UIScrollView.init(frame: self.bounds);
scroV.showsHorizontalScrollIndicator = false;
scroV.bounces = false;
scroV.scrollsToTop = false;
return scroV;
}();
private lazy var scroLine : UIView = {
let scroLine = UIView();
scroLine.backgroundColor = kNormalTitleColor;
return scroLine;
}()
func setUpUI() {
addSubview(scroView);
setUpTitleLable();
setupBottomLine();
}
private func setUpTitleLable(){
let titleY :CGFloat = 0;
let titleH = bounds.height - bottomLineHight;
let count = titleArry.count;
cureIndex = 0;
for (index,titile) in titleArry.enumerated() {
let lable = UILabel();
lable.text = titile;
lable.tag = index+100;
lable.textAlignment = .center;
lable.font = UIFont.systemFont(ofSize: 16);
titleLableArry
.append(lable);
var titleW :CGFloat = 0;
var titleX :CGFloat = 0;
if !isScroEnable {
titleW = bounds.width / CGFloat(count);
titleX = CGFloat(index) * titleW;
}else{
let size = (titile as NSString).boundingRect(with: CGSize.init(width: Double(MAXFLOAT), height: 0.0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : lable.font], context: nil).size;
titleW = size.width;
if (index != 0) {
titleX = (titleLableArry[index-1].frame.maxX);
}
}
lable.frame = CGRect.init(x:titleX , y: titleY, width: titleW, height: titleH)
scroView.addSubview(lable);
lable.isUserInteractionEnabled = true;
let tapGe = UITapGestureRecognizer.init(target: self
, action: #selector(self.tapGes(tap:)))
lable.addGestureRecognizer(tapGe)
}
}
private func setupBottomLine(){
let bottomLine = UIView();
bottomLine.frame = CGRect.init(x: 0, y: bounds.height-bottomLineHight, width: bounds.width, height: bottomLineHight);
bottomLine.backgroundColor = UIColor.clear;
addSubview(bottomLine);
//添加滑块
addSubview(scroLine);
guard let firstLabel = titleLableArry.first else {
return
}
let lineX = firstLabel.frame.origin.x;
let lineY = bounds.height - bottomLineHight;
let lineW = firstLabel.frame.width;
let lineH = bottomLineHight;
scroLine.frame = CGRect.init(x: lineX, y: lineY, width: lineW, height: lineH);
scroLine.backgroundColor = kSelectTitleColor;
firstLabel.textColor = kSelectTitleColor;
}
weak var delegate : PageTitleDelegate?
func tapGes (tap :UITapGestureRecognizer ){
guard let view = tap.view else {
return
}
let index = view.tag-100
scrollToIndex(index: index);
delegate?.pageTitleView(pagetitleView: self, didselectIndex: index)
}
private func scrollToIndex(index: Int){
let newLable = titleLableArry[index];
let oldLable = titleLableArry[cureIndex]
newLable.textColor = kSelectTitleColor;
oldLable.textColor = kNormalTitleColor;
let scroLineEndX = newLable.frame.minX;
let scroLindW = newLable.frame.width;
UIView.animate(withDuration: 0.2, animations: {
self.scroLine.frame.origin.x = scroLineEndX;
self.scroLine.frame.size.width = scroLindW;
})
cureIndex = index;
}
func contentViewScro(contentView: PageContentView, soutIndex: Int, tarIndex: Int, progress: CGFloat) {
let sourLable = titleLableArry[soutIndex];
let targeLable = titleLableArry[tarIndex];
let moveMargin = targeLable.frame.origin.x - sourLable.frame.origin.x;
var newPross = progress;
scroLine.frame.origin.x = sourLable.frame.origin.x + moveMargin * progress;
if(soutIndex == tarIndex){
newPross = 1.0;
}else{
sourLable.textColor = UIColor.init(red: (kSelectRGB.0 - kDeltaRGB.0 * newPross) / 255.0, green: (kSelectRGB.1 - kDeltaRGB.1 * newPross) / 255.0, blue: (kSelectRGB.2 - kDeltaRGB.2 * newPross) / 255.0, alpha: 1.0)
}
targeLable.textColor = UIColor.init(red: (kNormalRGB.0 + kDeltaRGB.0 * newPross)/255.0, green: (kNormalRGB.1 + kDeltaRGB.1 * newPross)/255.0, blue: (kNormalRGB.2 + kDeltaRGB.2 * newPross)/255.0, alpha: 1.0)
}
}
|
mit
|
d1f12867689e928cd18eda19b83562d5
| 27.154506 | 223 | 0.565244 | 4.262508 | false | false | false | false |
tuanan94/FRadio-ios
|
SwiftRadio/Libraries/Spring/TransitionManager.swift
|
1
|
3782
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class TransitionManager: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
@objc var isPresenting = true
@objc var duration = 0.3
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
if isPresenting {
toView.frame = container.bounds
toView.transform = CGAffineTransform(translationX: 0, y: container.frame.size.height)
container.addSubview(fromView)
container.addSubview(toView)
SpringAnimation.springEaseInOut(duration: duration) {
fromView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
fromView.alpha = 0.5
toView.transform = CGAffineTransform.identity
}
}
else {
// 1. Rotating will change the bounds
// 2. we have to properly reset toView
// to the actual container's bounds, at
// the same time take consideration of
// previous transformation when presenting
let transform = toView.transform
toView.transform = CGAffineTransform.identity
toView.frame = container.bounds
toView.transform = transform
container.addSubview(toView)
container.addSubview(fromView)
SpringAnimation.springEaseInOut(duration: duration) {
fromView.transform = CGAffineTransform(translationX: 0, y: fromView.frame.size.height)
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}
}
delay(delay: duration, closure: {
transitionContext.completeTransition(true)
})
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
@objc public func animationController(forPresentedController presented: UIViewController, presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
}
|
mit
|
60bcbbbabfcdf713b8e1db0f5a40e6dd
| 42.976744 | 210 | 0.69064 | 5.661677 | false | false | false | false |
silence0201/Swift-Study
|
Learn/10.属性和下标/结构体静态属性.playground/section-1.swift
|
1
|
549
|
struct Account {
var amount: Double = 0.0 // 账户金额
var owner: String = "" //账户名
static var interestRate: Double = 0.0668 //利率
static var staticProp: Double {
return interestRate * 1_000_000
}
var instanceProp: Double {
return Account.interestRate * amount
}
}
//访问静态属性
print(Account.staticProp)
var myAccount = Account()
//访问实例属性
myAccount.amount = 1_000_000
//访问实例属性
print(myAccount.instanceProp)
|
mit
|
0fefce1199addb60eaaa0af72a281ebc
| 18.038462 | 50 | 0.593939 | 3.639706 | false | false | false | false |
silence0201/Swift-Study
|
AdvancedSwift/可选值/A Tour of Optional Techniques - Optional map.playgroundpage/Contents.swift
|
1
|
3085
|
/*:
### Optional `map`
Let's say we have an array of characters, and we want to turn the first
character into a string:
*/
//#-editable-code
let characters: [Character] = ["a", "b", "c"]
String(characters[0])
//#-end-editable-code
/*:
However, if `characters` could be empty, we can use an `if let` to create the
string only if the array is non empty:
*/
//#-editable-code
var firstCharAsString: String? = nil
if let char = characters.first {
firstCharAsString = String(char)
}
//#-end-editable-code
/*:
So now, if the characters array contains at least one element,
`firstCharAsString` will contain that element as a `String`. But if it doesn't,
`firstCharAsString` will be `nil`.
This pattern — take an optional, and transform it if it isn't `nil` — is common
enough that there's a method on optionals to do this. It's called `map`, and it
takes a closure that represents how to transform the contents of the optional.
Here's the above function, rewritten using `map`:
*/
//#-editable-code
let firstChar = characters.first.map { String($0) }
//#-end-editable-code
/*:
This `map` is, of course, very similar to the `map` on arrays or other
sequences. But instead of operating on a sequence of values, it operates on just
one: the possible one inside the optional. You can think of optionals as being a
collection of either zero or one values, with `map` either doing nothing to zero
values or transforming one.
Given the similarities, the implementation of optional `map` looks a lot like
collection `map`:
*/
//#-editable-code
extension Optional {
func map_sample_impl<U>(transform: (Wrapped) -> U) -> U? {
if let value = self {
return transform(value)
}
return nil
}
}
//#-end-editable-code
/*:
An optional `map` is especially nice when you already want an optional result.
Suppose you wanted to write another variant of `reduce` for arrays. Instead of
taking an initial value, it uses the first element in the array (in some
languages, this might be called `reduce1`, but we'll call it `reduce` and rely
on overloading):
Because of the possibility that the array might be empty, the result needs to be
optional — without an initial value, what else could it be? You might write it
like this:
*/
//#-editable-code
extension Array {
func reduce(_ nextPartialResult: (Element, Element) -> Element) -> Element? {
// first will be nil if the array is empty
guard let fst = first else { return nil }
return dropFirst().reduce(fst, nextPartialResult)
}
}
//#-end-editable-code
/*:
You can use it like this:
*/
//#-editable-code
[1, 2, 3, 4].reduce(+)
//#-end-editable-code
/*:
Since optional `map` returns `nil` if the optional is `nil`, `reduce` could be
rewritten using a single `return` statement (and no `guard`):
*/
//#-editable-code
extension Array {
func reduce_alt(_ nextPartialResult: (Element, Element) -> Element)
-> Element?
{
return first.map {
dropFirst().reduce($0, nextPartialResult)
}
}
}
//#-end-editable-code
|
mit
|
a4a4cdadfbc193b1b6b79ee3ddfcf303
| 26.008772 | 81 | 0.690809 | 3.801235 | false | false | false | false |
jtsmrd/Intrview
|
ViewControllers/SpotlightOverlayVC.swift
|
1
|
2447
|
//
// SpotlightOverlayVC.swift
// SnapInterview
//
// Created by JT Smrdel on 1/3/17.
// Copyright © 2017 SmrdelJT. All rights reserved.
//
import UIKit
protocol SpotlightOverlayVCDelegate {
func recordButtonTapped(isRecording: Bool)
func cancelAction()
}
class SpotlightOverlayVC: UIViewController {
// MARK: Outlets
@IBOutlet weak var questionNoteLabel: UILabel!
@IBOutlet weak var timeRemainingLabel: UILabel!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var cancelButton: CustomButton!
// MARK: Variables
var delegate: SpotlightOverlayVCDelegate!
var expireTimer = Timer()
var counter = 60
var notes: String!
// MARK: View Functions
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
timeRemainingLabel.text = String(counter)
questionNoteLabel.text = notes
counter = 60
recordButton.setTitle("Record", for: .normal)
cancelButton.isEnabled = true
cancelButton.alpha = 1
}
// MARK: Actions
@IBAction func cancelButtonAction(_ sender: Any) {
delegate.cancelAction()
}
@IBAction func recordButtonAction(_ sender: Any) {
if recordButton.tag == 1 {
delegate.recordButtonTapped(isRecording: false)
recordButton.tag = 2
startTimer()
recordButton.setTitle("Stop Recording", for: .normal)
cancelButton.isEnabled = false
cancelButton.alpha = 0.5
}
else {
delegate.recordButtonTapped(isRecording: true)
recordButton.tag = 1
expireTimer.invalidate()
}
}
private func startTimer() {
expireTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(SpotlightOverlayVC.updateTimeRemainingLabel), userInfo: nil, repeats: true)
expireTimer.fire()
}
@objc func updateTimeRemainingLabel() {
if counter == 0 {
expireTimer.invalidate()
delegate.recordButtonTapped(isRecording: true)
}
else {
DispatchQueue.main.async {
self.timeRemainingLabel.text = String(self.counter)
}
counter -= 1
}
}
}
|
mit
|
fdd370048e1dfaa3d93bbbae388f5e31
| 25.301075 | 169 | 0.603434 | 5.022587 | false | false | false | false |
xudafeng/ios-app-bootstrap
|
ios-app-bootstrap/components/AlertViewController.swift
|
1
|
1813
|
//
// AlertViewController.swift
// ios-app-bootstrap
//
// Created by xdf on 16/12/2016.
// Copyright © 2016 open source. All rights reserved.
//
import UIKit
class AlertViewController: UIViewController {
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
func tapped(){
print("tapped")
}
func initView() {
navigationItem.title = Utils.Path.basename(#file)
view.backgroundColor = UIColor.white
button.backgroundColor = Utils.getRGB(Const.COLOR_1)
button.setTitle("show", for: UIControl.State())
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.cornerRadius = 2
button.titleLabel!.font = UIFont(name: "Helvetica",size: 12)
button.addTarget(self, action: #selector(AlertViewController.show(_:)), for: .touchUpInside)
view.addSubview(button)
let views:Dictionary<String, AnyObject>=["button": button]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[button(<=20)]-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-120-[button]-120-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: views))
showAlert()
}
@objc func show(_ sender: UIButton) {
showAlert()
}
func showAlert() {
let alertView = UIAlertView()
alertView.title = Const.TITLE
alertView.message = Const.TITLE
alertView.addButton(withTitle: "no")
alertView.addButton(withTitle: "yes")
alertView.cancelButtonIndex = 0
alertView.show()
}
}
|
mit
|
96299492e7022d1a88abebedbbe39731
| 30.789474 | 178 | 0.635762 | 4.884097 | false | false | false | false |
kapilbhalla/letsTweetAgain
|
letsTweetAgain/Tweet.swift
|
1
|
3780
|
//
// Tweet.swift
// letsTweetAgain
//
// Created by Bhalla, Kapil on 4/16/17.
// Copyright © 2017 Bhalla, Kapil. All rights reserved.
//
import UIKit
class Tweet: NSObject {
var isTweet: Bool = true
var tweetId: Int = 0
var isYourFavorited: Bool = false
var isYourRetweet: Bool = false
var text: String?
var retweetCount: Int = 0
var likesCount: Int = 0
var timeStamp: Date?
var screenName: String?
var retweetName: String?
var user: NSDictionary?
var containedUser: User?
var profileImageURL: String?
var userName: String?
var id: NSNumber?
init (tweetDictionary: NSDictionary){
print (tweetDictionary)
isYourRetweet = (tweetDictionary["retweeted"] as? Bool) ?? false
isYourFavorited = (tweetDictionary["favorited"] as? Bool) ?? false
id = tweetDictionary["id"] as? NSNumber
user = tweetDictionary["user"] as? NSDictionary
containedUser = User(userDictionary: user!)
profileImageURL = user?["profile_image_url_https"] as? String
let timeStampString = tweetDictionary["created_at"] as? String
if let timeStampStringUnwrapped = timeStampString {
let timeStampFormatter = DateFormatter()
timeStampFormatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
timeStamp = timeStampFormatter.date(from: timeStampStringUnwrapped)
}
let retweetedStatus = tweetDictionary.value(forKeyPath: "retweeted_status") as? NSDictionary
if retweetedStatus != nil {
//this is retweet
isTweet = false
//text
text = tweetDictionary.value(forKeyPath: "retweeted_status.text") as? String
//retweetCount
retweetCount = (tweetDictionary.value(forKeyPath: "retweeted_status.retweet_count") as? Int) ?? 0
//favoriteCount
likesCount = (tweetDictionary.value(forKeyPath: "retweeted_status.favorite_count") as? Int) ?? 0
//name
userName = (tweetDictionary.value(forKeyPath: "retweeted_status.user.name") as? String)!
//screen name
screenName = "@" + (tweetDictionary.value(forKeyPath: "retweeted_status.user.screen_name") as? String)!
//profile url
profileImageURL = tweetDictionary.value(forKeyPath: "retweeted_status.user.profile_image_url_https") as? String
//retweet name
retweetName = tweetDictionary.value(forKeyPath: "user.name") as? String
} else {
//this is tweet
//text
text = tweetDictionary["text"] as? String
//retweetCount
retweetCount = (tweetDictionary["retweet_count"] as? Int) ?? 0
//favoriteCount
likesCount = (tweetDictionary["favourite_count"] as? Int) ?? 0
//name
userName = tweetDictionary.value(forKeyPath: "user.name") as? String
//screen name
screenName = "@" + (tweetDictionary.value(forKeyPath: "user.screen_name") as? String)!
//profile url
profileImageURL = tweetDictionary.value(forKeyPath: "user.profile_image_url_https") as? String
}
}
// create a static class function to return an array of tweets given a array of dictionaries
class func tweetsWithArray( tweetDictionaries: [NSDictionary]) -> [Tweet] {
var tweets = [Tweet]()
for aDictionary in tweetDictionaries {
let tweet = Tweet(tweetDictionary: aDictionary)
tweets.append(tweet)
}
return tweets
}
}
|
apache-2.0
|
596444dff6d2d28cfb43d8c9f3e92028
| 33.354545 | 123 | 0.595131 | 4.820153 | false | false | false | false |
banxi1988/BXPhotoViewer
|
Pod/Classes/BXPhotoViewerViewController.swift
|
1
|
1902
|
//
// BXPhotoViewerViewController.swift
// Pods
//
// Created by Haizhen Lee on 15/11/19.
//
//
import UIKit
public class BXPhotoViewerViewController: UIPageViewController {
var photos:[BXPhotoViewable]
public init(photos:[BXPhotoViewable] = []){
self.photos = photos
super.init(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
}
required public init?(coder: NSCoder) {
self.photos = []
super.init(coder: coder)
}
public override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
if let photo = photos.first{
let firstVC = BXPhotoViewController(photo: photo)
setViewControllers([firstVC], direction: .Forward, animated: true, completion: nil)
}
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: UIPageViewControllerDataSource
extension BXPhotoViewerViewController: UIPageViewControllerDataSource{
public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let photoVC = (viewController as? BXPhotoViewController) else {
return nil
}
if photoVC.page < (photos.count - 1){
return photoViewControllerOfPage(photoVC.page + 1)
}
return nil
}
func photoViewControllerOfPage(page:Int) -> BXPhotoViewController{
let vc = BXPhotoViewController(photo: photos[page])
vc.page = page
return vc
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let photoVC = (viewController as? BXPhotoViewController) else {
return nil
}
if photoVC.page > 0{
return photoViewControllerOfPage(photoVC.page - 1)
}
return nil
}
}
|
mit
|
e90aafda38a7ee7a0ad7fe8c430b1493
| 26.970588 | 166 | 0.721872 | 4.88946 | false | false | false | false |
qiuncheng/study-for-swift
|
YLQRCode/YLQRCode/YLQRCodeHelper/YLGenerateQRCode.swift
|
1
|
2422
|
//
// GenerateQRCode.swift
// YLQRCode
//
// Created by yolo on 2017/1/20.
// Copyright © 2017年 Qiuncheng. All rights reserved.
//
import UIKit
import CoreImage
struct YLGenerateQRCode {
static func beginGenerate(text: String, withLogo: Bool = false, completion: CompletionHandler<UIImage?>) {
let strData = text.data(using: .utf8)
let qrFilter = CIFilter(name: "CIQRCodeGenerator")
qrFilter?.setValue(strData, forKey: "inputMessage")
qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
if let ciImage = qrFilter?.outputImage {
let size = CGSize(width: 260, height: 260)
let context = CIContext(options: nil)
var cgImage = context.createCGImage(ciImage, from: ciImage.extent)
UIGraphicsBeginImageContext(size)
let cgContext = UIGraphicsGetCurrentContext()
cgContext?.interpolationQuality = .none
cgContext?.scaleBy(x: 1.0, y: -1.0)
cgContext?.draw(cgImage!, in: cgContext!.boundingBoxOfClipPath)
if withLogo {
let image = YLGenerateQRCode.getBorderImage(image: #imageLiteral(resourceName: "29"))
if let podfileCGImage = image?.cgImage {
cgContext?.draw(podfileCGImage, in: cgContext!.boundingBoxOfClipPath.insetBy(dx: (size.width - 34.0) * 0.5, dy: (size.height - 34.0) * 0.5))
}
}
let codeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
completion(codeImage)
cgImage = nil
return
}
completion(nil)
}
static func getBorderImage(image: UIImage) -> UIImage? {
let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.borderWidth = 2.0
imageView.image = image
var currentImage: UIImage? = nil
UIGraphicsBeginImageContext(CGSize(width: 34.0, height: 34.0))
if let context = UIGraphicsGetCurrentContext() {
imageView.layer.render(in: context)
currentImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return currentImage
}
}
|
mit
|
dffc92f89402de15cd5de0c44c93863b
| 36.215385 | 160 | 0.604382 | 4.94683 | false | false | false | false |
apple/swift-nio-http2
|
Sources/NIOHTTP2PerformanceTester/HPACKHeaderCanonicalFormBenchmark.swift
|
1
|
1597
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOHPACK
final class HPACKHeaderCanonicalFormBenchmark {
private let headers: HPACKHeaders
init(_ test: Test) {
switch test {
case .noTrimming:
self.headers = ["key": "no,trimming"]
case .trimmingWhitespace:
self.headers = ["key": " some , trimming "]
case .trimmingWhitespaceFromShortStrings:
self.headers = ["key": " smallString ,whenStripped"]
case .trimmingWhitespaceFromLongStrings:
self.headers = ["key": " moreThan15CharactersWithAndWithoutWhitespace ,anotherValue"]
}
}
enum Test {
case noTrimming
case trimmingWhitespace
case trimmingWhitespaceFromShortStrings
case trimmingWhitespaceFromLongStrings
}
}
extension HPACKHeaderCanonicalFormBenchmark: Benchmark {
func setUp() throws { }
func tearDown() { }
func run() throws -> Int {
var count = 0
for _ in 0..<100_000 {
count &+= self.headers[canonicalForm: "key"].count
}
return count
}
}
|
apache-2.0
|
9ef7d7592e45c8c477b3b7ceab8339b2
| 28.574074 | 97 | 0.572949 | 4.990625 | false | true | false | false |
belkhadir/Beloved
|
Beloved/Friend.swift
|
1
|
1515
|
//
// Friend.swift
// Beloved
//
// Created by Anas Belkhadir on 18/01/2016.
// Copyright © 2016 Anas Belkhadir. All rights reserved.
//
import Foundation
import CoreData
class Friend: NSManagedObject{
struct Keys {
static let username = "username"
static let PosterPath = "poster_path"
static let uid = "uid"
}
@NSManaged var username: String?
@NSManaged var posterPath: String?
@NSManaged var uid: String?
@NSManaged var currentUser: CurrentUserConnected?
@NSManaged var messages: [Message]
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(parameter: [String: AnyObject], context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Friend", inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
username = parameter[Keys.username] as? String
posterPath = parameter[Keys.PosterPath] as? String
uid = parameter[Keys.uid] as? String
}
//
// var posterImage: UIImage? {
//
// get {
// return TheMovieDB.Caches.imageCache.imageWithIdentifier(posterPath)
// }
//
// set {
// TheMovieDB.Caches.imageCache.storeImage(newValue, withIdentifier: posterPath!)
// }
// }
}
|
mit
|
a0c739ac764db02a011acffefe0bfbf9
| 27.584906 | 113 | 0.646631 | 4.560241 | false | false | false | false |
tjw/swift
|
test/decl/init/resilience.swift
|
6
|
1884
|
// RUN: %target-swift-frontend -typecheck -swift-version 4 -verify -enable-resilience %s -DRESILIENT
// RUN: %target-swift-frontend -typecheck -swift-version 5 -verify -enable-resilience %s -DRESILIENT
// There should be no errors when run without resilience enabled.
// RUN: %target-swift-frontend -typecheck -swift-version 4 %s
// RUN: %target-swift-frontend -typecheck -swift-version 5 %s
// Animal is not @_fixed_layout, so we cannot define an @inlinable
// designated initializer
public struct Animal {
public let name: String // expected-note 3 {{declared here}}
@inlinable public init(name: String) {
self.name = name // expected-error {{'let' property 'name' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
}
@inline(__always) public init(dog: String) {
self.name = dog // expected-error {{'let' property 'name' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
}
@_transparent public init(cat: String) {
self.name = cat // expected-error {{'let' property 'name' may not be initialized directly; use "self.init(...)" or "self = ..." instead}}
}
// This is OK
@inlinable public init(cow: String) {
self.init(name: cow)
}
// This is OK
@inlinable public init(other: Animal) {
self = other
}
}
public class Widget {
public let name: String
public init(nonInlinableName name: String) {
self.name = name
}
@inlinable public init(name: String) {
// expected-error@-1 {{initializer for class 'Widget' is '@inlinable' and must delegate to another initializer}}
self.name = name
}
@inlinable public convenience init(goodName name: String) {
// This is OK
self.init(nonInlinableName: name)
}
}
public protocol Gadget {
init()
}
extension Gadget {
@inlinable public init(unused: Int) {
// This is OK
self.init()
}
}
|
apache-2.0
|
3758d19e11ecfbb52ab74bef42484925
| 28.904762 | 142 | 0.670913 | 3.738095 | false | false | false | false |
harryzjm/SwipeMenu
|
Example-iOS/ViewController.swift
|
1
|
1247
|
//
// ViewController.swift
// Sample
//
// Created by Magic on 9/5/2016.
// Copyright © 2016 Magic. All rights reserved.
//
import UIKit
import SwipeMenu
class ViewController: UIViewController {
var menu: SwipeMenu = SwipeMenu()
let names = ["Apple", "Microsoft", "Facebook", "Twitter", "Github", "Tencent"]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .random
menu.dataSource = self
menu.delegate = self
view.addSubview(menu)
}
}
extension ViewController: SwipeMenuDataSource, SwipeMenuDelegate {
func numberOfItems(in menu: SwipeMenu) -> Int {
return names.count
}
func menu(_ menu: SwipeMenu, titleForRow row: Int) -> String {
return names[row]
}
func menu(_ menu: SwipeMenu, indicatorIconForRow row: Int) -> UIImage {
return UIImage(named: names[row])!
}
func menu(_ menu: SwipeMenu, didSelectRow row: Int) {
print("Select Row: ", row)
view.backgroundColor = .random
}
}
extension UIColor {
class var random: UIColor {
return UIColor(hue: CGFloat(arc4random_uniform(255)) / 255, saturation: 1, brightness: 1, alpha: 1)
}
}
|
mit
|
b1cdc7ac2f13b06c5234a1bf3a010b1f
| 23.431373 | 107 | 0.620385 | 4.167224 | false | false | false | false |
mightydeveloper/swift
|
stdlib/public/core/BridgeObjectiveC.swift
|
7
|
16556
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
/// A Swift Array or Dictionary of types conforming to
/// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or
/// NSDictionary, respectively. The elements of the resulting NSArray
/// or NSDictionary will be the result of calling `_bridgeToObjectiveC`
/// on each elmeent of the source container.
public protocol _ObjectiveCBridgeable {
typealias _ObjectiveCType : AnyObject
/// Return true iff instances of `Self` can be converted to
/// Objective-C. Even if this method returns `true`, A given
/// instance of `Self._ObjectiveCType` may, or may not, convert
/// successfully to `Self`; for example, an `NSArray` will only
/// convert successfully to `[String]` if it contains only
/// `NSString`s.
@warn_unused_result
static func _isBridgedToObjectiveC() -> Bool
// _getObjectiveCType is a workaround: right now protocol witness
// tables don't include associated types, so we can not find
// '_ObjectiveCType.self' from them.
/// Must return `_ObjectiveCType.self`.
@warn_unused_result
static func _getObjectiveCType() -> Any.Type
/// Convert `self` to Objective-C.
@warn_unused_result
func _bridgeToObjectiveC() -> _ObjectiveCType
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for forced downcasting (e.g.,
/// via as), and may defer complete checking until later. For
/// example, when bridging from `NSArray` to `Array<Element>`, we can defer
/// the checking for the individual elements of the array.
///
/// - parameter result: The location where the result is written. The optional
/// will always contain a value.
static func _forceBridgeFromObjectiveC(
source: _ObjectiveCType,
inout result: Self?
)
/// Try to bridge from an Objective-C object of the bridged class
/// type to a value of the Self type.
///
/// This conditional bridging operation is used for conditional
/// downcasting (e.g., via as?) and therefore must perform a
/// complete conversion to the value type; it cannot defer checking
/// to a later time.
///
/// - parameter result: The location where the result is written.
///
/// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant
/// information is provided for the convenience of the runtime's `dynamic_cast`
/// implementation, so that it need not look into the optional representation
/// to determine success.
static func _conditionallyBridgeFromObjectiveC(
source: _ObjectiveCType,
inout result: Self?
) -> Bool
}
//===--- Bridging for metatypes -------------------------------------------===//
/// A stand-in for a value of metatype type.
///
/// The language and runtime do not yet support protocol conformances for
/// structural types like metatypes. However, we can use a struct that contains
/// a metatype, make it conform to to _ObjectiveCBridgeable, and its witness table
/// will be ABI-compatible with one that directly provided conformance to the
/// metatype type itself.
public struct _BridgeableMetatype: _ObjectiveCBridgeable {
internal var value: AnyObject.Type
public typealias _ObjectiveCType = AnyObject
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return AnyObject.self
}
public func _bridgeToObjectiveC() -> AnyObject {
return value
}
public static func _forceBridgeFromObjectiveC(
source: AnyObject,
inout result: _BridgeableMetatype?
) {
result = _BridgeableMetatype(value: source as! AnyObject.Type)
}
public static func _conditionallyBridgeFromObjectiveC(
source: AnyObject,
inout result: _BridgeableMetatype?
) -> Bool {
if let type = source as? AnyObject.Type {
result = _BridgeableMetatype(value: type)
return true
}
result = nil
return false
}
}
//===--- Bridging facilities written in Objective-C -----------------------===//
// Functions that must discover and possibly use an arbitrary type's
// conformance to a given protocol. See ../runtime/Metadata.cpp for
// implementations.
//===----------------------------------------------------------------------===//
/// Attempt to convert `x` to its Objective-C representation.
///
/// - If `T` is a class type, it is alaways bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, `T` conforms to `_ObjectiveCBridgeable`:
/// + if `T._isBridgedToObjectiveC()` returns `false`, then the
/// result is empty;
/// + otherwise, returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, the result is empty.
@warn_unused_result
public func _bridgeToObjectiveC<T>(x: T) -> AnyObject? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return unsafeBitCast(x, AnyObject.self)
}
return _bridgeNonVerbatimToObjectiveC(x)
}
@warn_unused_result
public func _bridgeToObjectiveCUnconditional<T>(x: T) -> AnyObject {
let optResult: AnyObject? = _bridgeToObjectiveC(x)
_precondition(optResult != nil,
"value failed to bridge from Swift type to a Objective-C type")
return optResult!
}
/// Same as `_bridgeToObjectiveCUnconditional`, but autoreleases the
/// return value if `T` is bridged non-verbatim.
@warn_unused_result
func _bridgeToObjectiveCUnconditionalAutorelease<T>(x: T) -> AnyObject
{
if _fastPath(_isClassOrObjCExistential(T.self)) {
return unsafeBitCast(x, AnyObject.self)
}
guard let bridged = _bridgeNonVerbatimToObjectiveC(x) else {
_preconditionFailure(
"Dictionary key failed to bridge from Swift type to a Objective-C type")
}
_autorelease(bridged)
return bridged
}
@warn_unused_result
@_silgen_name("swift_bridgeNonVerbatimToObjectiveC")
func _bridgeNonVerbatimToObjectiveC<T>(x: T) -> AnyObject?
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + if the dynamic type of `x` is not `T._getObjectiveCType()`
/// or a subclass of it, trap;
/// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`;
/// - otherwise, trap.
@warn_unused_result
public func _forceBridgeFromObjectiveC<T>(x: AnyObject, _: T.Type) -> T {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as! T
}
var result: T?
_bridgeNonVerbatimFromObjectiveC(x, T.self, &result)
return result!
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
@warn_unused_result
@_silgen_name("_forceBridgeFromObjectiveC_bridgeable")
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(x: T._ObjectiveCType, _: T.Type) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + if `T._isBridgedToObjectiveC()` returns `false`, then the result is
/// empty;
/// + otherwise, if the dynamic type of `x` is not `T._getObjectiveCType()`
/// or a subclass of it, the result is empty;
/// + otherwise, returns the result of
/// `T._conditionallyBridgeFromObjectiveC(x)`;
/// - otherwise, the result is empty.
@warn_unused_result
public func _conditionallyBridgeFromObjectiveC<T>(
x: AnyObject,
_: T.Type
) -> T? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as? T
}
var result: T?
_bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result)
return result
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
@warn_unused_result
@_silgen_name("_conditionallyBridgeFromObjectiveC_bridgeable")
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
@_silgen_name("swift_bridgeNonVerbatimFromObjectiveC")
func _bridgeNonVerbatimFromObjectiveC<T>(
x: AnyObject,
_ nativeType: T.Type,
inout _ result: T?
)
/// Runtime optional to conditionall perform a bridge from an object to a value
/// type.
///
/// - parameter result: Will be set to the resulting value if bridging succeeds, and
/// unchanged otherwise.
///
/// - Returns: `true` to indicate success, `false` to indicate failure.
@_silgen_name("swift_bridgeNonVerbatimFromObjectiveCConditional")
func _bridgeNonVerbatimFromObjectiveCConditional<T>(
x: AnyObject,
_ nativeType: T.Type,
inout _ result: T?
) -> Bool
/// Determines if values of a given type can be converted to an Objective-C
/// representation.
///
/// - If `T` is a class type, returns `true`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, returns
/// `T._isBridgedToObjectiveC()`.
@warn_unused_result
public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return true
}
return _isBridgedNonVerbatimToObjectiveC(T.self)
}
@warn_unused_result
@_silgen_name("swift_isBridgedNonVerbatimToObjectiveC")
func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool
/// A type that's bridged "verbatim" does not conform to
/// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an
/// `AnyObject`. When this function returns true, the storage of an
/// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`.
@warn_unused_result
public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool {
return _isClassOrObjCExistential(T.self)
}
/// Retrieve the Objective-C type to which the given type is bridged.
@warn_unused_result
public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return T.self
}
return _getBridgedNonVerbatimObjectiveCType(T.self)
}
@warn_unused_result
@_silgen_name("swift_getBridgedNonVerbatimObjectiveCType")
func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?
// -- Pointer argument bridging
@_transparent
internal var _nilNativeObject: AnyObject? {
return nil
}
/// A mutable pointer-to-ObjC-pointer argument.
///
/// This type has implicit conversions to allow passing any of the following
/// to a C or ObjC API:
///
/// - `nil`, which gets passed as a null pointer,
/// - an inout argument of the referenced type, which gets passed as a pointer
/// to a writeback temporary with autoreleasing ownership semantics,
/// - an `UnsafeMutablePointer<Memory>`, which is passed as-is.
///
/// Passing pointers to mutable arrays of ObjC class pointers is not
/// directly supported. Unlike `UnsafeMutablePointer<Memory>`,
/// `AutoreleasingUnsafeMutablePointer<Memory>` must reference storage that
/// does not own a reference count to the referenced
/// value. UnsafeMutablePointer's operations, by contrast, assume that
/// the referenced storage owns values loaded from or stored to it.
///
/// This type does not carry an owner pointer unlike the other C*Pointer types
/// because it only needs to reference the results of inout conversions, which
/// already have writeback-scoped lifetime.
public struct AutoreleasingUnsafeMutablePointer<Memory /* TODO : class */>
: Equatable, NilLiteralConvertible, _PointerType {
@available(*, unavailable, renamed="Memory")
public typealias T = Memory
public let _rawValue: Builtin.RawPointer
@_transparent
public // COMPILER_INTRINSIC
init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
@_transparent
var _isNull : Bool {
return UnsafeMutablePointer<Memory>(self)._isNull
}
/// Access the underlying raw memory, getting and
/// setting values.
public var memory: Memory {
/// Retrieve the value the pointer points to.
@_transparent get {
_debugPrecondition(!_isNull)
// We can do a strong load normally.
return UnsafeMutablePointer<Memory>(self).memory
}
/// Set the value the pointer points to, copying over the previous value.
///
/// AutoreleasingUnsafeMutablePointers are assumed to reference a
/// value with __autoreleasing ownership semantics, like 'NSFoo**'
/// in ARC. This autoreleases the argument before trivially
/// storing it to the referenced memory.
@_transparent nonmutating set {
_debugPrecondition(!_isNull)
// Autorelease the object reference.
typealias OptionalAnyObject = AnyObject?
Builtin.retain(unsafeBitCast(newValue, OptionalAnyObject.self))
Builtin.autorelease(unsafeBitCast(newValue, OptionalAnyObject.self))
// Trivially assign it as a COpaquePointer; the pointer references an
// autoreleasing slot, so retains/releases of the original value are
// unneeded.
let p = UnsafeMutablePointer<COpaquePointer>(
UnsafeMutablePointer<Memory>(self))
p.memory = unsafeBitCast(newValue, COpaquePointer.self)
}
}
/// Access the `i`th element of the raw array pointed to by
/// `self`.
///
/// - Requires: `self != nil`.
public subscript(i: Int) -> Memory {
@_transparent
get {
_debugPrecondition(!_isNull)
// We can do a strong load normally.
return (UnsafePointer<Memory>(self) + i).memory
}
}
/// Create an instance initialized with `nil`.
@_transparent public
init(nilLiteral: ()) {
_rawValue = _nilRawPointer
}
/// Initialize to a null pointer.
@_transparent public
init() {
self._rawValue = _nilRawPointer
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
@_transparent public
init<U>(_ ptr: UnsafeMutablePointer<U>) {
self._rawValue = ptr._rawValue
}
/// Explicit construction from a UnsafePointer.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
@_transparent
init<U>(_ ptr: UnsafePointer<U>) {
self._rawValue = ptr._rawValue
}
}
extension AutoreleasingUnsafeMutablePointer : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
@_transparent
@warn_unused_result
public func == <Memory> (
lhs: AutoreleasingUnsafeMutablePointer<Memory>,
rhs: AutoreleasingUnsafeMutablePointer<Memory>
) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
internal struct _CocoaFastEnumerationStackBuf {
// Clang uses 16 pointers. So do we.
var item0: Builtin.RawPointer
var item1: Builtin.RawPointer
var item2: Builtin.RawPointer
var item3: Builtin.RawPointer
var item4: Builtin.RawPointer
var item5: Builtin.RawPointer
var item6: Builtin.RawPointer
var item7: Builtin.RawPointer
var item8: Builtin.RawPointer
var item9: Builtin.RawPointer
var item10: Builtin.RawPointer
var item11: Builtin.RawPointer
var item12: Builtin.RawPointer
var item13: Builtin.RawPointer
var item14: Builtin.RawPointer
var item15: Builtin.RawPointer
@_transparent
var length: Int {
return 16
}
init() {
item0 = _nilRawPointer
item1 = item0
item2 = item0
item3 = item0
item4 = item0
item5 = item0
item6 = item0
item7 = item0
item8 = item0
item9 = item0
item10 = item0
item11 = item0
item12 = item0
item13 = item0
item14 = item0
item15 = item0
_sanityCheck(sizeofValue(self) >= sizeof(Builtin.RawPointer.self) * length)
}
}
#endif
|
apache-2.0
|
a010c7fb69c4eeda269f48b7fb43a7f6
| 32.311871 | 114 | 0.696424 | 4.321587 | false | false | false | false |
lorentey/swift
|
test/Sema/option-set-empty.swift
|
12
|
1236
|
// RUN: %target-typecheck-verify-swift
struct SomeOptions: OptionSet {
var rawValue: Int
static let some = MyOptions(rawValue: 4)
static let empty = SomeOptions(rawValue: 0) // expected-warning {{static property 'empty' produces an empty option set}} expected-note {{use [] to silence this warning}}{{35-48=([])}}
static var otherVal = SomeOptions(rawValue: 0)
let someVal = MyOptions(rawValue: 6)
let option = MyOptions(float: Float.infinity)
let none = SomeOptions(rawValue: 0) // expected-error {{value type 'SomeOptions' cannot have a stored property that recursively contains it}}
}
struct MyOptions: OptionSet {
let rawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
}
init(float: Float) {
self.rawValue = float.exponent
}
static let none = MyOptions(rawValue: 0) // expected-warning {{static property 'none' produces an empty option set}} expected-note {{use [] to silence this warning}}{{32-45=([])}}
static var nothing = MyOptions(rawValue: 0)
static let nope = MyOptions()
static let other = SomeOptions(rawValue: 8)
static let piVal = MyOptions(float: Float.pi)
static let zero = MyOptions(float: 0.0)
}
|
apache-2.0
|
19ce7c540e6abf7672d522b1ad02d5d7
| 37.625 | 187 | 0.675566 | 4.079208 | false | false | false | false |
colbylwilliams/bugtrap
|
iOS/Code/Swift/bugTrap/bugTrapKit/Services/RestProxy.swift
|
1
|
9671
|
//
// RestProxy.swift
// bugTrap
//
// Created by Colby L Williams on 11/14/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
class RestProxy : NSObject {
//var data: NSMutableData = NSMutableData()
var authHeader: String?
let sessionConfig: NSURLSessionConfiguration
override init() {
self.sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
super.init()
}
func setAuthentication(authenticationType: AuthenticationType, username: String = "", password: String = "", token: String = "") {
switch (authenticationType) {
case .Basic: // DoneDone
if !username.isEmpty && !password.isEmpty {
let credentials = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions([])
authHeader = "Basic \(credentials)"
} else {
Log.error("RestProxy setAuthentication", "Attempt to set Basic Authentication Failed. No Username or Passowrd")
}
case .Token: // Pivotal
if !token.isEmpty {
authHeader = token
} else {
Log.error("RestProxy setAuthentication", "Attempt to set Token Authentication Failed. No Token")
}
}
}
func getAuthenticatedRequest(url: NSURL, authenticationType: AuthenticationType, method: HttpMethod = HttpMethod.Get, contentType: String = ContentType.Json.rawValue) -> NSMutableURLRequest {
let request = getRequest(url, method: method)
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
if let header = authHeader {
switch (authenticationType) {
case .Basic: // DoneDone
request.addValue(header, forHTTPHeaderField: "Authorization")
request.addValue("nocheck", forHTTPHeaderField: "X-Atlassian-Token")
case .Token: // Pivotal
request.addValue(header, forHTTPHeaderField: "X-TrackerToken")
}
} else {
Log.error ("RestProxy authHeader has no value")
}
Log.info("RestProxy getAuthenticatedRequest", authHeader)
return request
}
func getRequest(url: NSURL, method: HttpMethod = HttpMethod.Get) -> NSMutableURLRequest {
let request = NSMutableURLRequest()
request.URL = url
request.HTTPMethod = method.string
return request
}
func get(url: NSURL, authenticationType: AuthenticationType, callback: (Result<JSON>) -> ()) {
let session = NSURLSession(configuration: sessionConfig)
let task = session.dataTaskWithRequest(getAuthenticatedRequest(url, authenticationType: authenticationType)){ (data, response, error) in
self.processJSONResponse(data, response: response, error: error, callback: callback)
}
task.resume()
}
func getData(url: NSURL, callback : (Result<NSData>) -> ()) {
let session = NSURLSession(configuration: sessionConfig)
let task = session.dataTaskWithRequest(getRequest(url)) { (data, response, error) in
if error == nil {
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == HttpStatus.Ok.rawValue {
dispatch_async(dispatch_get_main_queue()) {
callback(.Value(Wrapped(data)))
}
} else {
let err = NSError(domain: HttpStatus.type, code: httpResponse.statusCode, userInfo: nil)
dispatch_async(dispatch_get_main_queue()) {
callback(.Error(err))
}
}
}
} else {
Log.error("RestProxy processJSONResponse", error)
dispatch_async(dispatch_get_main_queue()) {
callback(.Error(error!))
}
}
}
task.resume()
}
func processJSONResponse(data: NSData!, response: NSURLResponse!, error: NSError!, callback: (Result<JSON>) -> ()) {
if error == nil {
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == HttpStatus.Ok.rawValue || httpResponse.statusCode == HttpStatus.Created.rawValue {
let json = JSON(data: data)
if let jsonError = json.error {
Log.info("RestProxy processJSONResponse", json)
dispatch_async(dispatch_get_main_queue()) {
callback(.Error(jsonError))
}
} else {
Log.info("RestProxy processJSONResponse", json)
dispatch_async(dispatch_get_main_queue()) {
callback(.Value(Wrapped(json)))
}
}
} else {
let err = NSError(domain: HttpStatus.type, code: httpResponse.statusCode, userInfo: nil)
Log.error("RestProxy processJSONResponse", error)
dispatch_async(dispatch_get_main_queue()) {
callback(.Error(err))
}
}
}
} else {
Log.error("RestProxy processJSONResponse", error)
dispatch_async(dispatch_get_main_queue()) {
callback(.Error(error))
}
}
}
func post<T : JsonSerializable>(url: NSURL, authenticationType: AuthenticationType, object: T, callback: (Result<JSON>) -> ()) {
Log.info("RestProxy post")
let session = NSURLSession(configuration: sessionConfig)
var err : NSError?
// serialize the data
let dict = object.serialize()
Log.info("RestProxy post", dict)
let data: NSData?
do {
data = try NSJSONSerialization.dataWithJSONObject(dict, options: [])
} catch let error as NSError {
err = error
data = nil
}
if err != nil {
dispatch_async(dispatch_get_main_queue()) {
callback(.Error(err!))
}
}
// create a POST request and attach the data
let request = getAuthenticatedRequest(url, authenticationType: authenticationType, method: .Post)
request.HTTPBody = data
// make the service call
let task = session.dataTaskWithRequest(request) { (data, response, error) in
self.processJSONResponse(data, response: response, error: error, callback: callback)
}
task.resume()
}
// Pivotal Tracker
func postAttachment(url: NSURL, authenticationType: AuthenticationType, attachment: NSData? = nil, callback: (Result<JSON>) -> ()) {
let body: NSMutableData = NSMutableData()
let session = NSURLSession(configuration: sessionConfig)
let boundary = "Boundary-\(NSUUID().UUIDString)"
let name = "file", filename = "bugTrap screen capture.jpeg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(ContentType.ImageJpeg.rawValue)\r\n\r\n")
body.appendData(attachment!)
body.appendString("\r\n--\(boundary)--\r\n")
let contentType = "\(ContentType.MultiPartForm.rawValue); boundary=\(boundary)"
// create a POST request and attach the data
let request = getAuthenticatedRequest(url, authenticationType: authenticationType, method: .Post, contentType: contentType)
request.HTTPBody = body
// make the service call
let task = session.dataTaskWithRequest(request) { (data, response, error) in
self.processJSONResponse(data, response: response, error: error, callback: callback)
}
task.resume()
}
// DoneDone
func postWithAttachments<T : JsonSerializable>(url: NSURL, authenticationType: AuthenticationType, object: T, attachments: [NSData]? = nil, callback: (Result<JSON>) -> ()) {
if attachments == nil {
self.post(url, authenticationType: authenticationType, object: object, callback: callback)
return
}
var count = 0;
var fieldData = ""
let data: NSMutableData = NSMutableData()
let session = NSURLSession(configuration: sessionConfig)
let boundary = "------------------------\(NSDate().timeIntervalSince1970 * 1000)"
// get the dictionary of fields for this object and add the data as form-data parts
let fieldDict = object.serialize()
for keyValue in fieldDict {
fieldData += "\n--\(boundary)\nContent-Type: \(ContentType.TextPlain.rawValue)\nContent-Disposition: form-data;name=\"\(keyValue.key)\"\n\n\(keyValue.value)"
}
data.appendData(fieldData.dataUsingEncoding(NSUTF8StringEncoding)!)
for attachment in attachments! {
let name = count == 0 ? "bugTrap screen capture.jpg" : "bugTrap screen capture \(count).jpg"
count++
let fileInfo = "\n--\(boundary)\nContent-Disposition: filename=\"\(name)\"\nContent-Type: \(ContentType.ImageJpeg.rawValue)\n\n".dataUsingEncoding(NSUTF8StringEncoding)!
data.appendData(fileInfo)
data.appendData(attachment)
}
// trailing boundary
let trailer = "\n--\(boundary)--\n".dataUsingEncoding(NSASCIIStringEncoding)!
data.appendData(trailer)
let contentType = "\(ContentType.MultiPartForm.rawValue); boundary=\(boundary)"
// create a POST request and attach the data
let request = getAuthenticatedRequest(url, authenticationType: authenticationType, method: .Post, contentType: contentType)
request.HTTPBody = data
// make the service call
let task = session.dataTaskWithRequest(request) { (data, response, error) in
self.processJSONResponse(data, response: response, error: error, callback: callback)
}
task.resume()
}
}
|
mit
|
a95ae8f687669e4cf07d881d6c53a77c
| 29.511041 | 192 | 0.629821 | 4.57474 | false | false | false | false |
urbanthings/urbanthings-sdk-apple
|
UrbanThingsAPI/Internal/Response/UTLocation.swift
|
1
|
2259
|
//
// Location.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 26/04/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
import CoreLocation
extension CLLocationCoordinate2D : Location {}
public typealias UTLocation = CLLocationCoordinate2D
extension CLLocationCoordinate2D: JSONInitialization {
public init?(latitude: Double?, longitude: Double?) {
guard let latitude = latitude, let longitude = longitude else {
return nil
}
self.latitude = latitude
self.longitude = longitude
}
public init(required: Any?, latitude: JSONKey, longitude: JSONKey) throws {
guard let json = required as? [String:AnyObject] else {
throw UTAPIError(expected: [String:AnyObject].self, not: required, file:#file, function:#function, line:#line)
}
guard let lat = json[latitude] as? Double, let lng = json[longitude] as? Double else {
throw UTAPIError(jsonParseError:"Missing coordinate \(latitude) and/or \(longitude) in \(json)", file:#file, function:#function, line:#line)
}
self.latitude = lat
self.longitude = lng
}
public init?(optional: Any?, latitude: JSONKey, longitude: JSONKey) throws {
guard let json = optional as? [String:AnyObject] else {
return nil
}
let lat = json[JSONKey.Latitude] as? Double
let lng = json[JSONKey.Longitude] as? Double
guard lat != nil && lng != nil else {
if lat != nil || lng != nil {
throw UTAPIError(jsonParseError:"Missing coordinate \(latitude) and/or \(longitude) in \(json)", file:#file, function:#function, line:#line)
}
return nil
}
self.latitude = lat!
self.longitude = lng!
}
public init(required: Any?) throws {
try self.init(required: required, latitude: .Latitude, longitude: .Longitude)
}
public init?(optional: Any?) throws {
guard let json = optional as? [String:Any] else {
return nil
}
try self.init(required: json)
}
public init(required: [String: Any], key: JSONKey) throws {
try self.init(required: required[key])
}
}
|
apache-2.0
|
e710080e8f0cc487a92ab664a44e8443
| 30.361111 | 156 | 0.620461 | 4.392996 | false | false | false | false |
KinveyApps/IOS-Starter
|
Bookshelf/DetailViewController.swift
|
1
|
4023
|
//
// DetailViewController.swift
// Bookshelf
//
// Created by Victor Barros on 2016-02-08.
// Copyright © 2016 Kinvey. All rights reserved.
//
import UIKit
import Kinvey
import SVProgressHUD
import MobileCoreServices
import AssetsLibrary
import Photos
class DetailViewController: UIViewController {
@IBOutlet weak var pictureImageView: UIImageView!
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var takeChoosePictureButton: UIButton!
var authorsTVC: AuthorsTableViewController!
var store: DataStore<Book>!
var book: Book! {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let book = book, let titleTextField = titleTextField {
titleTextField.text = book.title
}
}
override func viewDidAppear(_ animated: Bool) {
self.titleTextField.becomeFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
@IBAction func addAuthor(_ sender: Any) {
authorsTVC.tableView.beginUpdates()
authorsTVC.authors.append(Author())
let indexPath = IndexPath(row: authorsTVC.authors.count - 1, section: 0)
authorsTVC.tableView.insertRows(at: [indexPath], with: .automatic)
authorsTVC.tableView.endUpdates()
let cell = authorsTVC.tableView.cellForRow(at: indexPath) as? AuthorTableViewCell
if let cell = cell {
cell.textField.becomeFirstResponder()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
case "authors":
authorsTVC = segue.destination as? AuthorsTableViewController
authorsTVC.authors = book.authors.map { $0 }
default:
break
}
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
switch identifier {
case "save":
if book == nil {
book = Book()
}
book.title = titleTextField.text
book.authors.removeAll()
book.authors.append(objectsIn: authorsTVC.authors)
SVProgressHUD.show()
store.save(book, options: nil) {
SVProgressHUD.dismiss()
switch $0 {
case .success:
self.performSegue(withIdentifier: identifier, sender: sender)
case .failure:
let alert = UIAlertController(title: "Error", message: "Operation not completed", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
return false
case "cancel":
if book == nil {
book = Book()
}
SVProgressHUD.show()
if let bookId = book.entityId {
SVProgressHUD.dismiss()
//user cancelled, reload book from the cache to disacard any local changes
store.find(bookId, options: nil) {
switch $0 {
case .success(let cachedBook):
self.book = cachedBook
case .failure:
break
}
}
}
return false
default:
return true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
a50e711db7c5f1d403f7f5e461d753a4
| 29.938462 | 125 | 0.55644 | 5.4278 | false | false | false | false |
skyfe79/SwiftImageProcessing
|
02_PixelOperation.playground/Contents.swift
|
1
|
980
|
//: Playground - noun: a place where people can play
import UIKit
let rgba = RGBAImage(image: UIImage(named: "monet")!)!
var totalR = 0
var totalG = 0
var totalB = 0
rgba.process { (pixel) -> Pixel in
totalR += Int(pixel.R)
totalG += Int(pixel.G)
totalB += Int(pixel.B)
return pixel
}
let pixelCount = rgba.width * rgba.height
let avgR = totalR / pixelCount
let avgG = totalG / pixelCount
let avgB = totalB / pixelCount
func contrast(_ image: RGBAImage) -> RGBAImage {
image.process { (pixel) -> Pixel in
var pixel = pixel
let deltaR = Int(pixel.R) - avgR
let deltaG = Int(pixel.G) - avgG
let deltaB = Int(pixel.B) - avgB
pixel.R = UInt8(max(min(255, avgR + 3 * deltaR), 0)) //clamp
pixel.G = UInt8(max(min(255, avgG + 3 * deltaG), 0))
pixel.B = UInt8(max(min(255, avgB + 3 * deltaB), 0))
return pixel
}
return image
}
let newImage = contrast(rgba).toUIImage()
|
mit
|
184d386b46d84201d5dc380b3938d69a
| 20.777778 | 68 | 0.602041 | 3.192182 | false | false | false | false |
Shannon-Yang/SYNetworking
|
SYNetworkingTests/SYNetworkingTestCase.swift
|
1
|
16161
|
//
// SYNetworkingTestCase.swift
// SYNetworking
//
// Created by Shannon Yang on 2017/1/20.
// Copyright © 2017年 Hangzhou Yunti Technology Co. Ltd. All rights reserved.
//
import UIKit
import XCTest
import Alamofire
@testable import SYNetworking
enum JSONTestType {
case get
case post
}
enum ObjectMapperType {
case `default`
case object
case objectKeyPath
case objectNestedKeyPath
case array
case arrayKeyPath
case arrayNestedKeyPath
}
enum ResponseType {
case `default`
case data
case string
case json(JSONTestType)
case propertyList
case swiftyJSON
case objectMapper(ObjectMapperType)
}
class SYNetworkTestCase: XCTestCase {
func expectSuccess(with type: ResponseType, request: SYBasicDataRequest, assertion: (() -> Void)? = nil) {
let exp = self.expectation(description: "Request should succeed")
switch type {
case .default:
request.response({ defalutDataResponse in
XCTAssertNotNil(request)
XCTAssertNotNil(defalutDataResponse)
XCTAssertNotNil(defalutDataResponse.data)
if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
XCTAssertNotNil(defalutDataResponse.metrics)
}
exp.fulfill()
})
case .data:
request.responseData({ (isDataFromCache, dataResponse) in
XCTAssertEqual(dataResponse.result.isSuccess, true)
XCTAssertNotNil(request)
XCTAssertNotNil(dataResponse)
XCTAssertNotNil(dataResponse.data)
if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
XCTAssertNotNil(dataResponse.metrics)
}
exp.fulfill()
})
case .string:
request.responseString({ (isDataFromCache, dataResponse) in
XCTAssertNotNil(dataResponse.request)
XCTAssertNotNil(dataResponse.response)
XCTAssertNotNil(dataResponse.data)
XCTAssertEqual(dataResponse.result.isSuccess, true)
if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
XCTAssertNotNil(dataResponse.metrics)
}
exp.fulfill()
})
case .json(let type):
switch type {
case .get:
request.responseJSON({ (isDataFromCache, dataResponse) in
XCTAssertNotNil(dataResponse.request)
XCTAssertNotNil(dataResponse.response)
XCTAssertNotNil(dataResponse.data)
XCTAssertEqual(dataResponse.result.isSuccess, true)
if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
XCTAssertNotNil(dataResponse.metrics)
}
// The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info.
// - https://openradar.appspot.com/radar?id=5517037090635776
if let args = (dataResponse.result.value as AnyObject?)?["args" as NSString] as? [String: String] {
XCTAssertEqual(args, ["foo": "bar"], "args should match parameters")
} else {
XCTFail("args should not be nil")
}
exp.fulfill()
})
case .post:
request.responseJSON({ (isDataFromCache, dataResponse) in
// Then
XCTAssertNotNil(dataResponse.request)
XCTAssertNotNil(dataResponse.response)
XCTAssertNotNil(dataResponse.data)
XCTAssertNotNil(dataResponse.data)
XCTAssertEqual(dataResponse.result.isSuccess, true)
if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) {
XCTAssertNotNil(dataResponse.metrics)
}
// The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info.
// - https://openradar.appspot.com/radar?id=5517037090635776
if let form = (dataResponse.result.value as AnyObject?)?["form" as NSString] as? [String: String] {
XCTAssertEqual(form, ["foo": "bar"], "form should match parameters")
} else {
XCTFail("form should not be nil")
}
})
}
case .swiftyJSON:
request.responseSwiftyJSON({ (isDataFromCache, dataResponse) in
XCTAssertNotNil(dataResponse.request)
XCTAssertNotNil(dataResponse.response)
XCTAssertNotNil(dataResponse.data)
XCTAssertNotNil(dataResponse.data)
XCTAssertEqual(dataResponse.result.isSuccess, true)
XCTAssertNotNil(dataResponse.value)
exp.fulfill()
})
case .objectMapper(let value):
switch value {
case .default:
request.responseObject(completionHandler: { (isDataFromCache, dataResponse: DataResponse<WeatherResponse>) in
exp.fulfill()
let mappedObject = dataResponse.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
})
case .object:
let weatherResponse = WeatherResponse()
weatherResponse.date = Date()
request.responseObject(mapToObject: weatherResponse, completionHandler: { (isDataFromCache, dataResponse: DataResponse<WeatherResponse>) in
exp.fulfill()
let mappedObject = dataResponse.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.date, "Date should not be nil") // Date is not in JSON but should not be nil because we mapped onto an existing object with a date set
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
})
case .objectKeyPath:
request.responseObject(completionHandler: { (isDataFromCache, dataResponse: DataResponse<WeatherResponse>) in
exp.fulfill()
let mappedObject = dataResponse.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
})
case .objectNestedKeyPath:
request.responseObject(completionHandler: { (isDataFromCache, dataResponse: DataResponse<WeatherResponse>) in
exp.fulfill()
let mappedObject = dataResponse.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
})
case .array:
request.responseObjectArray(completionHandler: { (isDataFromCache, dataResponse: DataResponse<[Forecast]>) in
exp.fulfill()
let mappedArray = dataResponse.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
})
case .arrayKeyPath:
request.responseObjectArray(completionHandler: { (isDataFromCache, dataResponse: DataResponse<[Forecast]>) in
exp.fulfill()
let mappedArray = dataResponse.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
})
case .arrayNestedKeyPath:
request.responseObjectArray(completionHandler: { (isDataFromCache, dataResponse: DataResponse<[Forecast]>) in
exp.fulfill()
let mappedArray = dataResponse.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
})
}
default:
break
}
self.waitForExpectationsWithCommonTimeout()
}
func expectFailure(with type: ResponseType, request: SYBasicDataRequest, assertion: (() -> Void)? = nil) {
let exp = self.expectation(description: "Request should fail")
switch type {
case .default:
request.response({ (defalutDataResponse) in
XCTAssertNotNil(defalutDataResponse.request)
XCTAssertNil(defalutDataResponse.response)
XCTAssertNotNil(defalutDataResponse.data)
XCTAssertNotNil(defalutDataResponse.error)
})
case .data:
request.responseData { (isDataFromCache, dataResponse) in
switch dataResponse.result {
case .success( _):
XCTFail("Request should fail, but succeeded")
exp.fulfill()
case .failure(let error):
XCTAssertNotNil(error)
XCTAssertNotNil(request)
exp.fulfill()
}
}
default:
break
}
self.waitForExpectationsWithCommonTimeout()
}
func expectSuccess(_ responseDataSource: ResponseDataSource, request: SYBasicDataRequest?) {
guard let request = request else {
return
}
let exp = self.expectation(description: "Request should succeed")
switch responseDataSource {
case .server:
request.responseJSON(responseDataSource: responseDataSource) { (isDataFromCache, dataResponse) in
// Data should not be from cache.
XCTAssertFalse(isDataFromCache)
XCTAssertNotNil(dataResponse)
XCTAssertNotNil(dataResponse.result)
XCTAssertNotNil(dataResponse.data)
exp.fulfill()
}
case .cacheIfPossible:
request.responseJSON(responseDataSource: responseDataSource) { (isDataFromCache, dataResponse) in
// First time. Data should not be from cache. should from server
XCTAssertFalse(isDataFromCache)
XCTAssertNotNil(dataResponse)
XCTAssertNotNil(dataResponse.result)
XCTAssertNotNil(dataResponse.data)
exp.fulfill()
}
self.waitForExpectationsWithCommonTimeout()
sleep(5)
// Request again.
let exp = self.expectation(description: "Request should succeed")
request.responseJSON(responseDataSource: responseDataSource) { (isDataFromCache, dataResponse) in
// This time data should be from cache.
XCTAssertTrue(isDataFromCache)
XCTAssertNotNil(dataResponse)
XCTAssertNotNil(dataResponse.result)
XCTAssertNotNil(dataResponse.data)
exp.fulfill()
}
case .cacheAndServer:
request.responseJSON(responseDataSource: responseDataSource) { (isDataFromCache, dataResponse) in
// First time. Data should not be from cache. should from server
XCTAssertFalse(isDataFromCache)
XCTAssertNotNil(dataResponse)
XCTAssertNotNil(dataResponse.result)
XCTAssertNotNil(dataResponse.data)
exp.fulfill()
}
self.waitForExpectationsWithCommonTimeout()
let exp = self.expectation(description: "Request should succeed")
request.responseJSON(responseDataSource: responseDataSource) { (isDataFromCache, dataResponse) in
// This time data should be from cache.
XCTAssertTrue(isDataFromCache)
XCTAssertNotNil(dataResponse)
XCTAssertNotNil(dataResponse.result)
XCTAssertNotNil(dataResponse.data)
exp.fulfill()
}
default:
break
}
self.waitForExpectationsWithCommonTimeout()
}
func waitForExpectationsWithCommonTimeout() {
self.waitForExpectationsWithCommonTimeoutUsingHandler { error in
print("Error: \(error?.localizedDescription)")
}
}
func waitForExpectationsWithCommonTimeoutUsingHandler(with handler: @escaping XCWaitCompletionHandler) {
self.waitForExpectations(timeout: 30, handler: handler)
}
}
|
mit
|
29fd89997dbadd8d77871ba01de650fe
| 45.297994 | 184 | 0.560094 | 6.101964 | false | false | false | false |
asurinsaka/swift_examples_2.1
|
NSTimer/NSTimer/ViewController.swift
|
1
|
948
|
//
// ViewController.swift
// NSTimer
//
// Created by larryhou on 4/1/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController
{
private var startstamp:NSTimeInterval = 0
private var laststamp:NSTimeInterval = 0
override func viewDidLoad()
{
super.viewDidLoad()
scheduleNewTimer()
}
func scheduleNewTimer()
{
startstamp = NSDate.timeIntervalSinceReferenceDate()
laststamp = startstamp
NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "tickUpdate:", userInfo: "data", repeats: true)
}
func tickUpdate(timer:NSTimer)
{
let now = NSDate.timeIntervalSinceReferenceDate()
print(now - laststamp)
laststamp = now
if now - startstamp >= 30.0
{
timer.invalidate()
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
82bf9833c0a26a706af7f5c7d594adf2
| 17.98 | 118 | 0.719409 | 3.732283 | false | false | false | false |
marcelmueller/MyWeight
|
MyWeight/Views/ImageTextView.swift
|
1
|
2267
|
//
// ImageTextView.swift
// MyWeight
//
// Created by Diogo on 20/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import UIKit
public protocol ImageTextViewModelProtocol {
var image: UIImage? { get }
var text: NSAttributedString? { get }
}
public class ImageTextView: UIView {
struct EmptyViewModel: ImageTextViewModelProtocol {
let image: UIImage? = nil
let text: NSAttributedString? = NSAttributedString()
}
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .center
imageView.setContentHuggingPriority(UILayoutPriorityRequired,
for: .horizontal)
return imageView
}()
let textLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
return label
}()
public var viewModel: ImageTextViewModelProtocol {
didSet {
update()
}
}
override public init(frame: CGRect)
{
viewModel = EmptyViewModel()
super.init(frame: frame)
setUp()
update()
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUp()
{
let contentView = self
let stackView = UIStackView()
stackView.spacing = Style().grid * 2
stackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
}
func update()
{
let image = viewModel.image
imageView.image = image
imageView.isHidden = image == nil
let text = viewModel.text
textLabel.attributedText = text
textLabel.isHidden = text == nil
}
}
|
mit
|
ad835b20df69b4419a57f52b2731f814
| 25.045977 | 92 | 0.637688 | 5.209195 | false | false | false | false |
Archerlly/ACRouter
|
Example/ACRouter/ProfileViewController.swift
|
1
|
1807
|
//
// ProfileViewController.swift
// ACRouter
//
// Created by SnowCheng on 13/03/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import ACRouter
class ProfileViewController: UIViewController, ACRouterable {
static func registerAction(info: [String : AnyObject]) -> AnyObject {
let newInstance = self.init()
if let image = info["avatar"] as? UIImage {
newInstance.avatarView.image = image
newInstance.avatarView.sizeToFit()
newInstance.avatarView.center = newInstance.view.center
}
if let content = info["content"] as? String {
newInstance.infoLabel.text = content
newInstance.infoLabel.sizeToFit()
newInstance.infoLabel.center = newInstance.view.center
}
return newInstance
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let back = UIButton()
back.setTitle("back", for: .normal)
back.setTitleColor(UIColor.black, for: .normal)
back.addTarget(self, action: #selector(ProfileViewController.backAction), for: .touchUpInside)
back.frame = CGRect.init(x: 20, y: 20, width: 50, height: 50)
view.addSubview(back)
}
@objc private func backAction() {
dismiss(animated: true, completion: nil)
}
lazy var avatarView: UIImageView = {
let avatarView = UIImageView()
self.view.addSubview(avatarView)
self.view.sendSubview(toBack: avatarView)
return avatarView
}()
lazy var infoLabel: UILabel = {
let infoLabel = UILabel()
self.view.addSubview(infoLabel)
return infoLabel
}()
}
|
mit
|
9ad7440f9bb4452b4855321ef17c6c8b
| 27.666667 | 102 | 0.610742 | 4.841823 | false | false | false | false |
zhanggaoqiang/SwiftLearn
|
Swift语法/Swift自动引用计数/Swift自动引用计数/main.swift
|
1
|
7203
|
//
// main.swift
// Swift自动引用计数
//
// Created by zgq on 16/4/23.
// Copyright © 2016年 zgq. All rights reserved.
//
import Foundation
//Swift使用自动引用计数(ARC)这一机制来跟踪和管理应用程序的内存
//通常情况下我们不需要去手动释放内存,因为ARC会在类的实例不再被使用时,自动释放其占用的内存
//但有些时候我们还是需要在代码中实现内存管理
//ARC功能如下:
/*
1.当每次使用init()方法创建一个类的新的实例的时候,ARC会分配一大块内存用来储存实例的信息
2.内存中会包含实例的类型信息,以及这个实例所有相关属性的值
3.当类实例不再被使用时,ARC释放实例所占用的内存,并让释放的内存挪作他用
4.为了确保使用中的实例不会被销毁,ARC会跟踪和计算每一个实例正在被多少属性,常量和变量所引用
5.实例赋值给属性,常量或变量,它们都会创建此实例的强引用,只要强引用还在,实例是不允许被销毁的
*/
class Person {
var name:String = ""
init(name:String){
self.name = name
print("\(name) 开始初始化")
}
deinit{
print("\(name)被析构")
}
}
//值会被自动初始化为nil,目前还不会引用到Person类的实例
var reference1:Person?
var reference2 :Person?
var reference3:Person?
//创建Person类的实例
reference1 = Person(name:"Runoob")
//赋值给其它两个变量,该实例又会多出两个强引用
reference2=reference1
reference3=reference1
reference1 = nil//断开第一个强引用
reference2 = nil//断开第二个强引用
reference3 = nil//断开第三个强引用,并且调用析构函数
//类实例之间的循环强引用
/*
上面的例子中ARC会跟踪你所新创建的Person实例的引用数量,并且会在Person实例不再被需要时销毁它
然而,我们可能会写出这样的代码,一个类永远不会有0个强引用,这种情况发生在两个类实例互相保持对方的强引用,并让对方不被
销毁,这就是所谓的循环强引用
*/
class People {
var name:String = ""
init(name:String){
self.name = name
}
var apartment:Apartment?
deinit {
print("\(name) 被析构")
}
}
class Apartment {
var number:Int = 0
init(number:Int)
{
self.number = number
}
var tenant :People?
deinit
{
print("Apartment\(number) 被析构")
}
}
//两个变量都被初始化为nil
var runoob :People?
var number73 :Apartment?
//赋值
runoob = People(name:"Runoob")
number73=Apartment(number:73)
//感叹号是用来展开和访问可选变量runoob和number73中的实例
//循环强引用被创建
runoob!.apartment=number73
number73!.tenant=runoob
//断开runoob和number73变量所持有的强引用时,引用计数并不会降为0,实例也不会被ARC销毁
//注意,当你把这两个变量设为nil时候,没有人任何一个析构函数被调用
//强引用循环阻止了person和Apartment类实例的销毁并且在你的应用程序中造成了内存泄露
runoob = nil
number73 = nil
//解决实例之间的循环强引用
/*
1.若引用
2.无主引用
若引用和无主引用允许循环引用中的一个实例引用另外一个实例而不保持强引用。这样实例能够互相引用不产生循环强引用。
对于声明周期中会变为nil的实例使用弱引用。相反的,对于初始化赋值后再也不会被赋值为nil的实例,使用无主引用
*/
//弱引用实例
class Module {
var name:String = ""
init(name:String){
self.name = name
}
var sub:SubModule?
deinit {
print("\(name)主模块")
}
}
class SubModule {
var number:Int = 0
init(number:Int){
self.number = number
}
weak var topic:Module?
deinit{
print("子模块topic 数为\(number)")
}
}
var toc:Module?
var list:SubModule?
toc = Module(name:"ARC")
list = SubModule(number:4)
toc!.sub = list
list!.topic = toc
toc = nil
list = nil
//无主引用实例
class Student {
var name :String = ""
var section:Marks?
init(name:String){
self.name = name
}
deinit {
print("\name")
}
}
class Marks {
var marks:Int = 0
unowned let stname:Student
init(marks:Int,stname:Student) {
self.marks = marks
self.stname = stname
}
deinit{
print("学生的分数为 \(marks)")
}
}
var module: Student?
module = Student(name: "ARC")
module!.section = Marks(marks: 98, stname: module!)
module = nil
//闭包引起的循环引用
/*
循环引用还会发生在当你将一个闭包赋值给类实例的某个属性,并且这个闭包体中又使用了实例。这个闭包中可能访问了某个属性
例如。self..someproperty,或者闭包中调用了实例的某个方法,例如self.someMethod.这两种情况都导致了闭包捕获self,
从而产生了循环强引用
*/
//实例,下面的实例展示了当一个闭包是如何产生一个循环强引用的,例子定义了一个脚HTMLlement的类,用一种简单的模型表示HTML中的
//一个单独的元素
class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
// 创建实例并打印信息
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
//弱引用和无主引用
/*
当闭包和捕获的实例总是互相引用并且总是同时销毁时,将闭包的捕获定义为无主引用
相反的,当捕获的引用有时可能会为nil时、将闭包的捕获定义为弱引用
如果捕获的引用绝对不会置为nil,应该是无主引用,而不是弱引用
*/
//实例
//前面的HTMLElement例子中,无主引用是正确的解决循环强引用的方法。这样编写HTMLElement类来避免循环强引用:
class HTMLElement1 {
let name: String
let text: String?
lazy var asHTML: () -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) 被析构")
}
}
//创建并打印HTMLElement实例
var paragraph1: HTMLElement1? = HTMLElement1(name: "p", text: "hello, world")
print(paragraph1!.asHTML())
// HTMLElement实例将会被销毁,并能看到它的析构函数打印出的消息
paragraph1 = nil
|
mit
|
52449ca6155c87e54593e56931889fa3
| 14.015291 | 77 | 0.63055 | 2.820218 | false | false | false | false |
marcw/volte-ios
|
Volte/Timeline/TimelineMessageCell.swift
|
1
|
6248
|
//
// TimelineMessageCell.swift
// Volte
//
// Created by Romain Pouclet on 2016-10-12.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import Foundation
import UIKit
import VolteCore
protocol TimelineMessageCellDelegate: class {
func didTap(url: URL)
}
class TimelineMessageCell: UITableViewCell {
fileprivate let formater: DateFormatter = {
let formater = DateFormatter()
formater.dateStyle = .short
formater.timeStyle = .none
return formater
}()
weak var delegate: TimelineMessageCellDelegate?
let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let contentLabel: UITextView = {
let label = UITextView()
label.textContainerInset = .zero
label.font = .systemFont(ofSize: 15)
label.translatesAutoresizingMaskIntoConstraints = false
label.isScrollEnabled = false
label.dataDetectorTypes = [.link]
label.isEditable = false
label.isUserInteractionEnabled = true
label.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.blue]
label.contentInset = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0)
label.textAlignment = .left
return label
}()
let avatarView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.cornerRadius = 5
imageView.clipsToBounds = true
return imageView
}()
let preview: UIImageView = {
let preview = UIImageView()
preview.translatesAutoresizingMaskIntoConstraints = false
preview.contentMode = .scaleAspectFit
return preview
}()
private var noAttachmentsConstraints: [NSLayoutConstraint] = []
private var attachmentsConstraints: [NSLayoutConstraint] = []
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(titleLabel)
contentLabel.delegate = self
contentView.addSubview(contentLabel)
contentView.addSubview(avatarView)
separatorInset = .zero
NSLayoutConstraint.activate([
avatarView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
avatarView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10),
avatarView.widthAnchor.constraint(equalToConstant: 40),
avatarView.heightAnchor.constraint(equalToConstant: 40),
titleLabel.topAnchor.constraint(equalTo: avatarView.topAnchor, constant: -5), // There is Probably something better to do with baseline
titleLabel.leftAnchor.constraint(equalTo: avatarView.rightAnchor, constant: 10),
titleLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10),
contentLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 5),
contentLabel.leftAnchor.constraint(equalTo: titleLabel.leftAnchor),
contentLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10),
contentLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 18)
])
noAttachmentsConstraints = [
contentLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10)
]
attachmentsConstraints = [
preview.topAnchor.constraint(equalTo: contentLabel.bottomAnchor, constant: 10),
preview.leftAnchor.constraint(equalTo: contentView.leftAnchor),
preview.rightAnchor.constraint(equalTo: contentView.rightAnchor),
preview.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
preview.heightAnchor.constraint(equalTo: contentView.widthAnchor)
]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(item: Message) {
if item.attachments?.count == 0 {
preview.removeFromSuperview()
NSLayoutConstraint.activate(noAttachmentsConstraints)
NSLayoutConstraint.deactivate(attachmentsConstraints)
} else {
contentView.addSubview(preview)
NSLayoutConstraint.activate(attachmentsConstraints)
NSLayoutConstraint.deactivate(noAttachmentsConstraints)
if let attachment = item.attachments?.anyObject() as? Attachment, let data = attachment.data {
preview.image = UIImage(data: data as Data)
}
}
contentLabel.text = item.content
titleLabel.attributedText = attributedString(forAuthor: item.author!, date: item.postedAt as! Date)
setNeedsUpdateConstraints()
}
fileprivate func format(date: Date) -> String {
let interval = Int(Date().timeIntervalSince(date))
if interval < 60 {
return L10n.Timeline.Date.SecondsAgo(p0: interval)
} else if interval < 3600 {
return L10n.Timeline.Date.MinutesAgo(p0: Int(interval / 60))
} else if interval < 86400 {
return L10n.Timeline.Date.HoursAgo(p0: Int(interval / 3600))
}
return formater.string(from: date)
}
func attributedString(forAuthor author: String, date: Date) -> NSAttributedString {
let string = NSMutableAttributedString(string: author, attributes: [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16),
NSForegroundColorAttributeName: UIColor.black
])
string.append(NSMutableAttributedString(string: " " + format(date: date), attributes: [
NSFontAttributeName: UIFont.systemFont(ofSize: 13),
NSForegroundColorAttributeName: UIColor.lightGray
]))
return string
}
}
extension TimelineMessageCell: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
delegate?.didTap(url: URL)
return false
}
}
|
agpl-3.0
|
0f2435010f45afa371a49b4476deaa62
| 35.532164 | 147 | 0.675684 | 5.455895 | false | false | false | false |
optimistapp/optimistapp
|
Optimist/MoodView.swift
|
1
|
3749
|
//
// MoodCollectionView.swift
// Optimist
//
// Created by Jacob Johannesen on 1/30/15.
// Copyright (c) 2015 Optimist. All rights reserved.
//
import Foundation
import UIKit
import CoreGraphics
public class MoodView: UIView
{
var texts1: [String] = ["angry"];
var texts2: [String] = ["anxious", "annoyed"];
var texts3: [String] = ["depressed", "down", "heartbroken"];
var texts4: [String] = ["hopeless", "hurting"];
var texts5: [String] = ["irritatable", "mournful", "sad"];
var texts6: [String] = ["pissed", "regretful"];
var texts7: [String] = ["resentful", "scared", "sick"];
var texts8: [String] = ["stressed", "nervous"];
var texts9: [String] = ["sulky", "worthless"];
var booleanArr: [Bool] = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]
let DEFAULT_HEIGHT: CGFloat = 36.0
let DEFAULT_WIDTH: CGFloat = 150.0
let DEFAULT_MAX_WIDTH: CGFloat = 400.0
let NUM_LINES: Int = 9;
let DEFAULT_PADDING: CGFloat = 10.0
let TEXT_SCALING_FACTOR: CGFloat = 18.0
var trackIndex: Int = 0;
public override init(frame: CGRect)
{
super.init(frame:frame)
var lines: [UIView] = [createLine(texts1), createLine(texts2), createLine(texts3), createLine(texts4), createLine(texts5), createLine(texts6), createLine(texts7), createLine(texts8), createLine(texts9)];
for var index = 0; index < NUM_LINES; index++
{
lines[index].frame = CGRect(x: (self.frame.width / 2) - (lines[index].frame.width / 2), y: 0 + (DEFAULT_HEIGHT + DEFAULT_PADDING) * CGFloat(index), width: lines[index].frame.width, height: lines[index].frame.height);
self.addSubview(lines[index])
}
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createLine(texts: [String]) -> UIView
{
let numTexts = count(texts);
var totalLengthUsed: CGFloat = 0
var endResultTotal: CGFloat = 0
for var index = 0; index < numTexts; index++
{
let dynamicButtonWidth = calculateWidth(texts[index])
endResultTotal = endResultTotal + DEFAULT_PADDING + dynamicButtonWidth;
}
var lineView = UIView(frame: CGRect(x: 0, y: 0, width: endResultTotal, height: DEFAULT_HEIGHT))
for var index = 0; index < numTexts; index++
{
let dynamicButtonWidth = calculateWidth(texts[index])
let moodButton = MoodButton(width: dynamicButtonWidth, title: texts[index], moodView: self, index: trackIndex);
moodButton.frame = CGRect(x: totalLengthUsed, y: 0, width: moodButton.frame.width, height: moodButton.frame.height);
lineView.addSubview(moodButton);
totalLengthUsed = totalLengthUsed + DEFAULT_PADDING + dynamicButtonWidth;
trackIndex++;
}
return lineView;
}
func printBooleans()
{
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(booleanArr, forKey: "theBool")
defaults.synchronize()
/*for element in booleanArr
{
println("boolean is \(element)")
}*/
}
func calculateWidth(thisText: String) -> CGFloat
{
var CalculatedWidth = CGFloat(count(thisText)) * TEXT_SCALING_FACTOR
if(CalculatedWidth > 120)
{
CalculatedWidth = 120;
}
return CalculatedWidth
}
}
|
apache-2.0
|
0f102921bf1cf337bb3c5ac8ae6d1fd1
| 32.783784 | 228 | 0.592158 | 4.026853 | false | false | false | false |
ReactiveKit/Bond
|
Sources/Bond/Data Structures/IndexPath+Bond.swift
|
1
|
2584
|
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension IndexPath {
public func isAffectedByDeletionOrInsertion(at index: IndexPath) -> Bool {
assert(index.count > 0)
assert(self.count > 0)
guard index.count <= self.count else { return false }
let testLevel = index.count - 1
if index.prefix(testLevel) == self.prefix(testLevel) {
return index[testLevel] <= self[testLevel]
} else {
return false
}
}
public func shifted(by: Int, atLevelOf other: IndexPath) -> IndexPath {
assert(self.count > 0)
assert(other.count > 0)
let level = other.count - 1
guard level < self.count else { return self }
if by == -1 {
return self.advanced(by: -1, atLevel: level)
} else if by == 1 {
return self.advanced(by: 1, atLevel: level)
} else {
fatalError()
}
}
public func advanced(by offset: Int, atLevel level: Int) -> IndexPath {
var copy = self
copy[level] += offset
return copy
}
public func isAncestor(of other: IndexPath) -> Bool {
guard self.count < other.count else { return false }
return self == other.prefix(self.count)
}
public func replacingAncestor(_ ancestor: IndexPath, with newAncestor: IndexPath) -> IndexPath {
return newAncestor + dropFirst(ancestor.count)
}
}
|
mit
|
c7259598fd05db5b1356272e23bdcf13
| 36.449275 | 100 | 0.658669 | 4.243021 | false | true | false | false |
cnoon/CollectionViewAnimations
|
Source/Sticky Headers/ViewController.swift
|
1
|
4612
|
//
// ViewController.swift
// Sticky Headers
//
// Created by Christian Noon on 10/29/15.
// Copyright © 2015 Noondev. All rights reserved.
//
import SnapKit
import UIKit
class ViewController: UIViewController {
// MARK: Properties
let colors: [[UIColor]]
var collectionView: UICollectionView!
var layout = Layout()
// MARK: Initialization
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.colors = {
var colorsBySection: [[UIColor]] = []
for _ in 0...Number.random(from: 2, to: 4) {
var colors: [UIColor] = []
for _ in 0...Number.random(from: 2, to: 10) {
colors.append(UIColor.randomColor())
}
colorsBySection.append(colors)
}
return colorsBySection
}()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
collectionView = {
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(ContentCell.self, forCellWithReuseIdentifier: ContentCell.reuseIdentifier)
collectionView.registerClass(
SectionHeaderCell.self,
forSupplementaryViewOfKind: SectionHeaderCell.kind,
withReuseIdentifier: SectionHeaderCell.reuseIdentifier
)
return collectionView
}()
view.addSubview(collectionView)
collectionView.snp_makeConstraints { make in
make.edges.equalTo(view)
}
}
// MARK: Status Bar
override func prefersStatusBarHidden() -> Bool {
return true
}
}
// MARK: - UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource {
func collectionView(
collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection section: Int)
-> CGSize
{
return CGSize(width: collectionView.bounds.width, height: 40.0)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return colors.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colors[section].count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
ContentCell.reuseIdentifier,
forIndexPath: indexPath
) as! ContentCell
UIView.performWithoutAnimation {
cell.backgroundColor = self.colors[indexPath.section][indexPath.item]
cell.label.text = "Cell (\(indexPath.section), \(indexPath.item))"
}
return cell
}
func collectionView(
collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
{
let cell = collectionView.dequeueReusableSupplementaryViewOfKind(
SectionHeaderCell.kind,
withReuseIdentifier: SectionHeaderCell.reuseIdentifier,
forIndexPath: indexPath
) as! SectionHeaderCell
cell.label.text = "Section \(indexPath.section)"
return cell
}
}
// MARK: - UICollectionViewDelegate
extension ViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
layout.selectedCellIndexPath = layout.selectedCellIndexPath == indexPath ? nil : indexPath
let bounceEnabled = false
UIView.animateWithDuration(
0.4,
delay: 0.0,
usingSpringWithDamping: bounceEnabled ? 0.5 : 1.0,
initialSpringVelocity: bounceEnabled ? 2.0 : 0.0,
options: UIViewAnimationOptions(),
animations: {
self.layout.invalidateLayout()
self.collectionView.layoutIfNeeded()
},
completion: nil
)
}
}
|
mit
|
db7db9b7e40f039ce658936a88bc92ff
| 28.748387 | 130 | 0.641293 | 5.836709 | false | false | false | false |
IsaoTakahashi/iOS-KaraokeSearch
|
KaraokeSearch/PodSongTableViewCell.swift
|
1
|
1686
|
//
// PodSongTableViewCell.swift
// KaraokeSearch
//
// Created by 高橋 勲 on 2015/05/21.
// Copyright (c) 2015年 高橋 勲. All rights reserved.
//
import UIKit
import MaterialKit
protocol PodSongTableViewCellDelegate{
func selectSong(song: PodSong)
}
class PodSongTableViewCell: MKTableViewCell {
@IBOutlet weak var artistLabel: MKLabel!
@IBOutlet weak var songLabel: MKLabel!
var song: PodSong! = nil
var delegate: PodSongTableViewCellDelegate! = nil
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// UILabelとかを追加
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configureCell(song: PodSong, atIndexPath indexPath: NSIndexPath){
self.song = song;
artistLabel.textColor = UIColor.MainDarkColor()
songLabel.textColor = UIColor.MainDarkColor()
artistLabel.text = song.artistName
songLabel.text = song.songTitle
self.rippleLocation = .TapLocation
self.rippleLayerColor = UIColor.MainLightColor()
self.selectionStyle = .None
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
//delegate.selectSong(self.song)
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
//super.touchesBegan(touches, withEvent: event)
delegate.selectSong(self.song)
super.touchesEnded(touches, withEvent: event)
}
}
|
mit
|
42b5dfaf15aac3c9fc18a215d0767e98
| 27.186441 | 82 | 0.666667 | 4.52861 | false | false | false | false |
matrix-org/matrix-ios-sdk
|
MatrixSDK/Background/Store/MXSyncResponseStoreManager.swift
|
1
|
16218
|
//
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
/// Sync response storage in a file implementation.
@objcMembers
public class MXSyncResponseStoreManager: NSObject {
/// Maximum data size for each sync response cached in MXSyncResponseStore.
/// Under this value, sync reponses are merged. This limit allows to work on several smaller sync responses to limit RAM usage.
/// Default is 512kB.
var syncResponseCacheSizeLimit: Int = 512 * 1024
/// The actual store
let syncResponseStore: MXSyncResponseStore
/// Serial queue to merge sync responses
private lazy var mergeQueue: DispatchQueue = {
return DispatchQueue(label: String(describing: self) + "-MergeQueue")
}()
public init(syncResponseStore: MXSyncResponseStore) {
self.syncResponseStore = syncResponseStore
}
/// The sync token that is the origin of the stored sync response.
/// - Returns: the original sync token.
public func syncToken() -> String? {
self.firstSyncResponse()?.syncToken
}
/// The sync token to use for the next /sync requests
/// - Returns: the next sync token
public func nextSyncToken() -> String? {
self.lastSyncResponse()?.syncResponse.nextBatch
}
public func firstSyncResponse() -> MXCachedSyncResponse? {
guard let id = syncResponseStore.syncResponseIds.first else {
return nil
}
guard let syncResponse = try? syncResponseStore.syncResponse(withId: id) else {
MXLog.debug("[MXSyncResponseStoreManager] firstSyncResponse: invalid id")
return nil
}
return syncResponse
}
public func lastSyncResponse() -> MXCachedSyncResponse? {
guard let id = syncResponseStore.syncResponseIds.last else {
return nil
}
guard let syncResponse = try? syncResponseStore.syncResponse(withId: id) else {
MXLog.debug("[MXSyncResponseStoreManager] lastSyncResponse: invalid id")
return nil
}
return syncResponse
}
public func markDataOutdated() {
let syncResponseIds = syncResponseStore.syncResponseIds
if syncResponseIds.count == 0 {
return
}
MXLog.debug("[MXSyncResponseStoreManager] markDataOutdated \(syncResponseIds.count) cached sync responses. The sync token was \(String(describing: syncToken()))")
syncResponseStore.markOutdated(syncResponseIds: syncResponseIds)
}
public func mergedSyncResponse(fromSyncResponseIds responseIds: [String],
completion: @escaping (MXCachedSyncResponse?) -> Void) {
if responseIds.isEmpty {
// empty array
DispatchQueue.main.async {
completion(nil)
}
return
}
let stopwatch = MXStopwatch()
mergeQueue.async {
var result: MXSyncResponse?
var syncToken: String?
for responseId in responseIds {
if let response = try? self.syncResponseStore.syncResponse(withId: responseId) {
if let tmpResult = result {
result = self.merged(response.syncResponse, onto: tmpResult)
} else {
result = response.syncResponse
syncToken = response.syncToken
}
}
}
MXLog.debug("[MXSyncResponseStoreManager] mergedSyncResponse: merging \(responseIds.count) sync responses lasted \(stopwatch.readable())")
if let result = result {
DispatchQueue.main.async {
completion(MXCachedSyncResponse(syncToken: syncToken,
syncResponse: result))
}
} else {
DispatchQueue.main.async {
completion(nil)
}
}
}
}
/// Cache a sync response.
/// - Parameters:
/// - newSyncResponse: the sync response to store
/// - syncToken: the sync token that generated this sync response.
public func updateStore(with newSyncResponse: MXSyncResponse, syncToken: String) {
if let id = syncResponseStore.syncResponseIds.last {
// Check if we can merge the new sync response to the last one
// Store it as a new chunk if the previous chunk is too big
let cachedSyncResponseSize = syncResponseStore.syncResponseSize(withId: id)
if cachedSyncResponseSize < syncResponseCacheSizeLimit,
let cachedSyncResponse = try? syncResponseStore.syncResponse(withId: id) {
MXLog.debug("[MXSyncResponseStoreManager] updateStore: Merge new sync response to the previous one")
let updatedSyncResponse = merged(newSyncResponse, onto: cachedSyncResponse.syncResponse)
// And update it to the store.
// Note we we care only about the cached sync token. syncToken is now useless
let updatedCachedSyncResponse = MXCachedSyncResponse(syncToken: cachedSyncResponse.syncToken,
syncResponse: updatedSyncResponse)
syncResponseStore.updateSyncResponse(withId: id, syncResponse: updatedCachedSyncResponse)
} else {
// Use a new chunk
MXLog.debug("[MXSyncResponseStoreManager] updateStore: Create a new chunk to store the new sync response. Previous chunk size: \(cachedSyncResponseSize)")
let cachedSyncResponse = MXCachedSyncResponse(syncToken: syncToken,
syncResponse: newSyncResponse)
_ = syncResponseStore.addSyncResponse(syncResponse: cachedSyncResponse)
}
} else {
// no current sync response, directly save the new one
MXLog.debug("[MXSyncResponseStoreManager] updateStore: Start storing sync response")
let cachedSyncResponse = MXCachedSyncResponse(syncToken: syncToken,
syncResponse: newSyncResponse)
_ = syncResponseStore.addSyncResponse(syncResponse: cachedSyncResponse)
}
// Manage user account data
if let newAccountData = newSyncResponse.accountData,
let newAccountDataEvents = newAccountData["events"] as? [[String: Any]], newAccountDataEvents.count > 0 {
let cachedAccountData = syncResponseStore.accountData ?? [:]
guard let accountData = MXAccountData(accountData: cachedAccountData) else {
return
}
newAccountDataEvents.forEach {
accountData.update(withEvent: $0)
}
syncResponseStore.accountData = accountData.accountData
}
}
/// Fetch event in the store
/// - Parameters:
/// - eventId: Event identifier to be fetched.
/// - roomId: Room identifier to be fetched.
public func event(withEventId eventId: String, inRoom roomId: String) -> MXEvent? {
for id in syncResponseStore.syncResponseIds.reversed() {
let event = autoreleasepool { () -> MXEvent? in
guard let response = try? syncResponseStore.syncResponse(withId: id) else {
return nil
}
return self.event(withEventId: eventId, inRoom: roomId, inSyncResponse: response)
}
if let event = event {
return event
}
}
MXLog.debug("[MXSyncResponseStoreManager] event: Not found event \(eventId) in room \(roomId)")
return nil
}
private func event(withEventId eventId: String, inRoom roomId: String, inSyncResponse response: MXCachedSyncResponse) -> MXEvent? {
var allEvents: [MXEvent] = []
if let joinedRoomSync = response.syncResponse.rooms?.join?[roomId] {
allEvents.appendIfNotNil(contentsOf: joinedRoomSync.state.events)
allEvents.appendIfNotNil(contentsOf: joinedRoomSync.timeline.events)
allEvents.appendIfNotNil(contentsOf: joinedRoomSync.accountData.events)
}
if let invitedRoomSync = response.syncResponse.rooms?.invite?[roomId] {
allEvents.appendIfNotNil(contentsOf: invitedRoomSync.inviteState.events)
}
if let leftRoomSync = response.syncResponse.rooms?.leave?[roomId] {
allEvents.appendIfNotNil(contentsOf: leftRoomSync.state.events)
allEvents.appendIfNotNil(contentsOf: leftRoomSync.timeline.events)
allEvents.appendIfNotNil(contentsOf: leftRoomSync.accountData.events)
}
let result = allEvents.first(where: { eventId == $0.eventId })
result?.roomId = roomId
MXLog.debug("[MXSyncResponseStoreManager] eventWithEventId: \(eventId) \(result == nil ? "not " : "" )found")
return result
}
/// Fetch room summary for an invited room. Just uses the data in syncResponse to guess the room display name
/// - Parameter roomId: Room identifier to be fetched
/// - Parameter model: A room summary model (if exists) which user had before a sync response
public func roomSummary(forRoomId roomId: String, using model: MXRoomSummaryProtocol?) -> MXRoomSummaryProtocol? {
let summary: MXRoomSummary?
if let model = model {
summary = MXRoomSummary(summaryModel: model)
} else {
summary = MXRoomSummary(roomId: roomId, andMatrixSession: nil)
}
guard var result = summary else {
return nil
}
// update summary with each sync response
for id in syncResponseStore.syncResponseIds.reversed() {
autoreleasepool {
if let response = try? syncResponseStore.syncResponse(withId: id) {
result = roomSummary(forRoomId: roomId, using: result, inSyncResponse: response)
}
}
}
return result
}
// MARK: - Private
private func merged(_ newSyncResponse: MXSyncResponse, onto oldSyncResponse: MXSyncResponse) -> MXSyncResponse {
let stopwatch = MXStopwatch()
// handle new limited timelines
newSyncResponse.rooms?.joinedOrLeftRoomSyncs?.filter({ $1.timeline.limited == true }).forEach { (roomId, _) in
if let joinedRoomSync = oldSyncResponse.rooms?.join?[roomId] {
// remove old events
joinedRoomSync.timeline.events = []
// mark old timeline as limited too
joinedRoomSync.timeline.limited = true
}
}
// handle old limited timelines
oldSyncResponse.rooms?.joinedOrLeftRoomSyncs?.filter({ $1.timeline.limited == true }).forEach { (roomId, _) in
if let joinedRoomSync = newSyncResponse.rooms?.join?[roomId] {
// mark new timeline as limited too, to avoid losing value of limited
joinedRoomSync.timeline.limited = true
}
}
// handle newly joined/left rooms for when invited
newSyncResponse.rooms?.joinedOrLeftRoomSyncs?.forEach { (roomId, newRoomSync) in
if let invitedRoomSync = oldSyncResponse.rooms?.invite?[roomId] {
// add inviteState events into the beginning of the state events
newRoomSync.state.events.insert(contentsOf: invitedRoomSync.inviteState.events, at: 0)
// remove invited room from old sync response
oldSyncResponse.rooms?.invite?.removeValue(forKey: roomId)
}
}
// handle newly left rooms for when joined
newSyncResponse.rooms?.leave?.forEach { (roomId, leftRoomSync) in
if let joinedRoomSync = oldSyncResponse.rooms?.join?[roomId] {
// add inviteState events into the beginning of the state events
leftRoomSync.state.events.insert(contentsOf: joinedRoomSync.state.events, at: 0)
// add joined timeline events into the beginning of the left timeline events
leftRoomSync.timeline.events.insert(contentsOf: joinedRoomSync.timeline.events, at: 0)
// remove joined room from old sync response
oldSyncResponse.rooms?.join?.removeValue(forKey: roomId)
}
}
// Merge the new sync response to the old one
var dictionary = NSDictionary(dictionary: oldSyncResponse.jsonDictionary())
dictionary = dictionary + NSDictionary(dictionary: newSyncResponse.jsonDictionary())
MXLog.debug("[MXSyncResponseStoreManager] merged: merging two sync responses lasted \(stopwatch.readable())")
return MXSyncResponse(fromJSON: dictionary as? [AnyHashable : Any])
}
private func roomSummary(forRoomId roomId: String, using summary: MXRoomSummary, inSyncResponse response: MXCachedSyncResponse) -> MXRoomSummary {
var eventsToProcess: [MXEvent] = []
if let invitedRoomSync = response.syncResponse.rooms?.invite?[roomId] {
eventsToProcess.append(contentsOf: invitedRoomSync.inviteState.events)
}
if let joinedRoomSync = response.syncResponse.rooms?.join?[roomId] {
eventsToProcess.append(contentsOf: joinedRoomSync.state.events)
eventsToProcess.append(contentsOf: joinedRoomSync.timeline.events)
}
if let leftRoomSync = response.syncResponse.rooms?.leave?[roomId] {
eventsToProcess.append(contentsOf: leftRoomSync.state.events)
eventsToProcess.append(contentsOf: leftRoomSync.timeline.events)
}
for event in eventsToProcess {
switch event.eventType {
case .roomAliases:
if summary.displayname == nil {
summary.displayname = (event.content["aliases"] as? [String])?.first
}
case .roomCanonicalAlias:
if summary.displayname == nil {
summary.displayname = event.content["alias"] as? String
if summary.displayname == nil {
summary.displayname = (event.content["alt_aliases"] as? [String])?.first
}
}
case .roomName:
summary.displayname = event.content["name"] as? String
default:
break
}
}
return summary
}
}
// MARK: - Private
private extension Array {
mutating func appendIfNotNil(contentsOf array: Array?) {
if let array = array {
append(contentsOf: array)
}
}
}
private extension MXRoomsSyncResponse {
var joinedOrLeftRoomSyncs: [String: MXRoomSync]? {
guard let joined = join else {
return leave
}
guard let left = leave else {
return joined
}
return joined.merging(left) { current, _ in
current
}
}
}
|
apache-2.0
|
9e85e820cf46aad38da0ecf4c29cb1e0
| 42.018568 | 170 | 0.60254 | 5.301733 | false | false | false | false |
zixun/CocoaChinaPlus
|
Code/CocoaChinaPlus/Application/Business/CocoaChina/BBS/Edition/CCPBBSEditionViewController.swift
|
1
|
6877
|
//
// CCPBBSEditionViewController.swift
// CocoaChinaPlus
//
// Created by zixun on 15/8/14.
// Copyright © 2015年 zixun. All rights reserved.
//
import UIKit
import Alamofire
import Neon
import Log4G
//static var pagenow = 1
// MARK: ZXBaseViewController
class CCPBBSEditionViewController: ZXBaseViewController {
//UI
lazy var tableview: UITableView = {
let newTableView = UITableView(frame: CGRect.zero, style: .plain)
newTableView.delegate = self
newTableView.dataSource = self
newTableView.backgroundColor = UIColor(hex: 0x000000, alpha: 0.8)
newTableView.separatorStyle = .none
newTableView.addInfiniteScrolling(actionHandler: { [weak self] () -> Void in
guard let sself = self else {
return
}
sself.loadNextPage();
})
newTableView.infiniteScrollingView.activityIndicatorViewStyle = .white
newTableView.register(CCPBBSEditionTableViewCell.self, forCellReuseIdentifier: "CCPBBSEditionTableViewCell")
return newTableView
}()
//数据
var dataSource = CCPBBSEditionModel()
//url
var currentLink = ""
required init(navigatorURL URL: URL?, query: Dictionary<String, String>) {
super.init(navigatorURL: URL, query: query)
//設置tableview
self.view.addSubview(self.tableview)
//設置連結
if let link = query["link"] {
self.currentLink = link
} else {
Log4G.error("連結缺失")
}
//讀取資料
CCPBBSEditionParser.parserEdition(self.currentLink) { [weak self] (model) -> Void in
guard let sself = self else {
return
}
sself.dataSource = model
sself.tableview.reloadData()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tableview.fillSuperview()
}
}
// MARK: Private Instance Method
extension CCPBBSEditionViewController {
//加載下一個分頁
fileprivate func loadNextPage() {
guard
let url = URL(string: self.currentLink),
let urlParameter = url.paramDictionary()
else {
Log4G.warning("連結缺失或參數錯誤")
return
}
//建立下一分頁連結
var newURL: URL
if let _ = urlParameter["more"] {
newURL = url.newURLByReplaceParams(params: ["page": String(self.dataSource.pagenext)])
self.currentLink = newURL.absoluteString
} else {
//之前是第一页
newURL = url.newURLByAppendingParams(params: ["more": "1", "page": String(self.dataSource.pagenext)])
self.currentLink = newURL.absoluteString
}
//加載
CCPBBSEditionParser.parserEdition(newURL.absoluteString) { [weak self] (model) -> Void in
guard let sself = self else {
return
}
sself.dataSource.append(model)
var insertIndexPaths = [IndexPath]()
for post in model.posts {
let row = sself.dataSource.posts.index(of: post)
let indexPath = IndexPath(row: row ?? 0, section: 0)
insertIndexPaths.append(indexPath)
}
sself.tableview.beginUpdates()
sself.tableview.insertRows(at: insertIndexPaths, with: .none)
sself.tableview.endUpdates()
sself.tableview.infiniteScrollingView.stopAnimating()
}
}
}
// MARK: UITableViewDataSource
extension CCPBBSEditionViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "CCPBBSEditionTableViewCell", for: indexPath) as! CCPBBSEditionTableViewCell
let post = self.dataSource.posts[indexPath.row]
cell.configure(post)
return cell
}
}
// MARK: UITableViewDelegate
extension CCPBBSEditionViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let post = self.dataSource.posts[indexPath.row]
ZXOpenURL("go/ccp/article", param: ["link": post.link])
}
}
// MARK: CCPBBSEditionTableViewCell
class CCPBBSEditionTableViewCell: CCPTableViewCell {
//UI
fileprivate lazy var titleLabel: UILabel = {
let newTitleLabel = UILabel()
newTitleLabel.textColor = UIColor.white
newTitleLabel.font = UIFont.boldSystemFont(ofSize: 14)
newTitleLabel.textAlignment = .left
newTitleLabel.numberOfLines = 2
newTitleLabel.lineBreakMode = .byTruncatingTail
return newTitleLabel
}()
fileprivate lazy var authorLabel: UILabel = {
let newAuthorLabel = UILabel()
newAuthorLabel.textColor = UIColor.gray
newAuthorLabel.font = UIFont.systemFont(ofSize: 12)
newAuthorLabel.textAlignment = .left
return newAuthorLabel
}()
fileprivate var timeLabel: UILabel = {
let newTimeLabel = UILabel()
newTimeLabel.textColor = UIColor.gray
newTimeLabel.font = UIFont.systemFont(ofSize: 12)
newTimeLabel.textAlignment = .right
return newTimeLabel
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//設置標題
self.containerView.addSubview(self.titleLabel)
//設置作者
self.containerView.addSubview(self.authorLabel)
//設置時間
self.containerView.addSubview(self.timeLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.anchorAndFillEdge(Edge.top, xPad: 4, yPad: 4, otherSize: AutoHeight)
self.authorLabel.anchorInCornerWithAutoSize(Corner.bottomLeft, xPad: 4, yPad: 0)
self.timeLabel.anchorInCornerWithAutoSize(Corner.bottomRight, xPad: 4, yPad: 0)
}
func configure(_ model: CCPBBSEditionPostModel) {
titleLabel.text = model.title
authorLabel.text = model.author
timeLabel.text = model.time
}
}
|
mit
|
63fbc98c80ce6943d62258c32df69c61
| 31.009479 | 141 | 0.628516 | 4.693537 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS
|
WordPressEditor/WordPressEditor/Classes/Plugins/WordPressPlugin/Gutenberg/GutenbergOutputHTMLTreeProcessor.swift
|
2
|
5037
|
import Aztec
import Foundation
public class GutenbergOutputHTMLTreeProcessor: HTMLTreeProcessor {
private let decoder = GutenbergAttributeDecoder()
public init() {}
public func process(_ rootNode: RootNode) {
rootNode.children = rootNode.children.flatMap({ (node) -> [Node] in
guard let element = node as? ElementNode else {
return [node]
}
if element.type == .gutenblock {
return process(gutenblock: element)
} else if element.type == .gutenpack {
return process(gutenpack: element)
} else if element.type == .p {
// Our output serializer is a bit dumb, and it wraps gutenpack elements into P tags.
// If we find any, we remove them here.
return process(paragraph: element)
} else {
return [element]
}
})
}
private func process(gutenblock: ElementNode) -> [Node] {
precondition(gutenblock.type == .gutenblock)
let openingComment = gutenbergOpener(for: gutenblock)
let containedNodes = gutenblock.children
let closingComment = gutenbergCloser(for: gutenblock)
let closingNewline = TextNode(text: "\n")
return [openingComment] + containedNodes + [closingComment, closingNewline]
}
private func process(gutenpack: ElementNode) -> [Node] {
precondition(gutenpack.type == .gutenpack)
let selfContainedBlockComment = gutenbergSelfCloser(for: gutenpack)
let closingNewline = TextNode(text: "\n")
return [selfContainedBlockComment, closingNewline]
}
private func process(paragraph: ElementNode) -> [Node] {
var children = ArraySlice<Node>(paragraph.children)
var result = [Node]()
while let (index, gutenpack) = nextGutenpack(in: children) {
let nodesBeforeGutenpack = children.prefix(index)
if nodesBeforeGutenpack.count > 0 {
let newParagraph = deepCopy(paragraph, withChildren: Array(nodesBeforeGutenpack))
result.append(newParagraph)
children = children.dropFirst(nodesBeforeGutenpack.count)
}
let replacementNodes = process(gutenpack: gutenpack)
result.append(contentsOf: replacementNodes)
children = children.dropFirst()
}
if children.count > 0 {
paragraph.children = Array(children)
result.append(paragraph)
}
return result
}
private func deepCopy(_ elementNode: ElementNode, withChildren children: [Node]) -> ElementNode {
let copiedAttributes = elementNode.attributes.map { (attribute) -> Attribute in
return Attribute(name: attribute.name, value: attribute.value)
}
return ElementNode(type: elementNode.type, attributes: copiedAttributes, children: children)
}
private func nextGutenpack(in nodes: ArraySlice<Node>) -> (index: Int, element: ElementNode)? {
for (index, node) in nodes.enumerated() {
if let element = node as? ElementNode,
element.type == .gutenpack {
return (index, element)
}
}
return nil
}
}
// MARK: - Gutenberg Tags
private extension GutenbergOutputHTMLTreeProcessor {
func gutenbergCloser(for element: ElementNode) -> CommentNode {
guard let closer = gutenblockCloserData(for: element) else {
fatalError("There's no scenario in which this information missing can make sense. Review the logic.")
}
return CommentNode(text: closer)
}
func gutenbergOpener(for element: ElementNode) -> CommentNode {
guard let opener = gutenblockOpenerData(for: element) else {
fatalError("There's no scenario in which this information missing can make sense. Review the logic.")
}
return CommentNode(text: opener)
}
func gutenbergSelfCloser(for element: ElementNode) -> CommentNode {
guard let selfCloser = gutenblockSelfCloserData(for: element) else {
fatalError("There's no scenario in which this information missing can make sense. Review the logic.")
}
return CommentNode(text: selfCloser)
}
// MARK: - Gutenberg HTML Attribute Data
private func gutenblockCloserData(for element: ElementNode) -> String? {
return decoder.attribute(.blockCloser, from: element)
}
private func gutenblockOpenerData(for element: ElementNode) -> String? {
return decoder.attribute(.blockOpener, from: element)
}
private func gutenblockSelfCloserData(for element: ElementNode) -> String? {
return decoder.attribute(.selfCloser, from: element)
}
}
|
gpl-2.0
|
ad8d5a7501ff8b1a030376c2bfd5d771
| 34.723404 | 114 | 0.6081 | 4.838617 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/Calling/CallController/CallController.swift
|
1
|
6587
|
//
// Wire
// Copyright (C) 2021 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 UIKit
import WireSyncEngine
final class CallController: NSObject {
// MARK: - Public Implentation
weak var router: ActiveCallRouterProtocol?
var callConversationProvider: CallConversationProvider?
// MARK: - Private Implentation
private var observerTokens: [Any] = []
private var minimizedCall: ZMConversation?
private var priorityCallConversation: ZMConversation? {
return callConversationProvider?.priorityCallConversation
}
private var dateOfLastErrorAlertByConversationId = [AVSIdentifier: Date]()
private var alertDebounceInterval: TimeInterval { 15 * .oneMinute }
// MARK: - Init
override init() {
super.init()
addObservers()
}
// MARK: - Public Implementation
func updateActiveCallPresentationState() {
guard let priorityCallConversation = priorityCallConversation else {
dismissCall()
return
}
showCallTopOverlay(for: priorityCallConversation)
presentOrMinimizeActiveCall(for: priorityCallConversation)
}
// MARK: - Private Implementation
private func addObservers() {
if let userSession = ZMUserSession.shared() {
observerTokens.append(WireCallCenterV3.addCallStateObserver(observer: self, userSession: userSession))
observerTokens.append(WireCallCenterV3.addCallErrorObserver(observer: self, userSession: userSession))
}
}
private func presentOrMinimizeActiveCall(for conversation: ZMConversation) {
conversation == minimizedCall
? minimizeCall()
: presentCall(in: conversation)
}
private func minimizeCall() {
router?.minimizeCall(animated: true, completion: nil)
}
private func presentCall(in conversation: ZMConversation) {
guard let voiceChannel = conversation.voiceChannel else { return }
if minimizedCall == conversation { minimizedCall = nil }
let animated = shouldAnimateTransitionForCall(in: conversation)
router?.presentActiveCall(for: voiceChannel, animated: animated)
}
private func dismissCall() {
router?.dismissActiveCall(animated: true, completion: { [weak self] in
self?.hideCallTopOverlay()
self?.minimizedCall = nil
})
}
private func showCallTopOverlay(for conversation: ZMConversation) {
router?.showCallTopOverlay(for: conversation)
}
private func hideCallTopOverlay() {
router?.hideCallTopOverlay()
}
private func shouldAnimateTransitionForCall(in conversation: ZMConversation) -> Bool {
guard SessionManager.shared?.callNotificationStyle == .callKit else {
return true
}
switch conversation.voiceChannel?.state {
case .outgoing?:
return true
default:
return false // We don't want animate when transition from CallKit screen
}
}
private func isClientOutdated(callState: CallState) -> Bool {
switch callState {
case .terminating(let reason) where reason == .outdatedClient:
return true
default:
return false
}
}
}
// MARK: - WireCallCenterCallStateObserver
extension CallController: WireCallCenterCallStateObserver {
func callCenterDidChange(callState: CallState,
conversation: ZMConversation,
caller: UserType,
timestamp: Date?,
previousCallState: CallState?) {
presentUnsupportedVersionAlertIfNecessary(callState: callState)
presentSecurityDegradedAlertIfNecessary(for: conversation.voiceChannel)
updateActiveCallPresentationState()
}
private func presentUnsupportedVersionAlertIfNecessary(callState: CallState) {
guard isClientOutdated(callState: callState) else { return }
router?.presentUnsupportedVersionAlert()
}
private func presentSecurityDegradedAlertIfNecessary(for voiceChannel: VoiceChannel?) {
guard let degradationState = voiceChannel?.degradationState else {
return
}
switch degradationState {
case .incoming(degradedUser: let user):
router?.presentSecurityDegradedAlert(degradedUser: user?.value)
default:
break
}
}
}
// MARK: - ActiveCallViewControllerDelegate
extension CallController: ActiveCallViewControllerDelegate {
func activeCallViewControllerDidDisappear(_ activeCallViewController: ActiveCallViewController,
for conversation: ZMConversation?) {
router?.dismissActiveCall(animated: true, completion: nil)
minimizedCall = conversation
}
}
// MARK: - WireCallCenterCallErrorObserver
extension CallController: WireCallCenterCallErrorObserver {
func callCenterDidReceiveCallError(_ error: CallError, conversationId: AVSIdentifier) {
guard
error == .unknownProtocol,
shouldDisplayErrorAlert(for: conversationId)
else {
return
}
dateOfLastErrorAlertByConversationId[conversationId] = Date()
router?.presentUnsupportedVersionAlert()
}
private func shouldDisplayErrorAlert(for conversation: AVSIdentifier) -> Bool {
guard let dateOfLastErrorAlert = dateOfLastErrorAlertByConversationId[conversation] else {
return true
}
let elapsedTimeIntervalSinceLastAlert = -dateOfLastErrorAlert.timeIntervalSinceNow
return elapsedTimeIntervalSinceLastAlert > alertDebounceInterval
}
}
extension CallController {
// NOTA BENE: THIS MUST BE USED JUST FOR TESTING PURPOSE
public func testHelper_setMinimizedCall(_ conversation: ZMConversation?) {
minimizedCall = conversation
}
}
|
gpl-3.0
|
4ac4b4535c944c93dcd0b88ffcb1c933
| 33.851852 | 114 | 0.682557 | 5.265388 | false | false | false | false |
jonnguy/HSTracker
|
HSTracker/Logging/Enums/Zone.swift
|
1
|
832
|
/*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 19/02/16.
*/
import Foundation
import Wrap
enum Zone: Int, WrappableEnum, CaseIterable {
case invalid = 0,
play = 1,
deck = 2,
hand = 3,
graveyard = 4,
removedfromgame = 5,
setaside = 6,
secret = 7
init?(rawString: String) {
let string = rawString.lowercased()
for _enum in Zone.allCases where "\(_enum)" == string {
self = _enum
return
}
if let value = Int(rawString), let _enum = Zone(rawValue: value) {
self = _enum
return
}
self = .invalid
}
}
|
mit
|
40051b83fcd0e9fcdaa602df2238472c
| 22.111111 | 74 | 0.580529 | 3.924528 | false | false | false | false |
dgoodine/Slogger
|
Slogger/Slogger/XCodeColorsDecorator.swift
|
1
|
1184
|
//
// XCodeColorsDecorator.swift
// Slogger
//
// Created by David Goodine on 10/24/15.
// Copyright © 2015 David Goodine. All rights reserved.
//
import Foundation
/// Decorator that uses XcodeColors format
public struct XCodeColorsDecorator: Decorator {
fileprivate let escape = "\u{001b}["
fileprivate let resetFg = "\u{001b}[fg;"
fileprivate let resetBg = "\u{001b}[bg;"
fileprivate let reset = "\u{001b}[;"
fileprivate let maxColor = 255.0
/// Protocol implementation
public func decorateString(_ string: String, spec: ColorSpec) -> String {
let fg = spec.fg
let bg = spec.bg
func prefix (_ color: Color, _ typeCode: String) -> String {
let r = Int(color.r * maxColor)
let g = Int(color.g * maxColor)
let b = Int(color.b * maxColor)
return "\(escape)\(typeCode)\(r),\(g),\(b);"
}
var fgStart = ""
let fgEnd = (fg == nil) ? "" : resetFg
if fg != nil {
fgStart = prefix(fg!, "fg")
}
var bgStart = ""
let bgEnd = (bg == nil) ? "" : resetBg
if bg != nil {
bgStart = prefix(bg!, "bg")
}
let value = "\(fgStart)\(bgStart)\(string)\(fgEnd)\(bgEnd)"
return value
}
}
|
mit
|
04640e3dd7a7441714ebdfbed1fd46eb
| 24.717391 | 75 | 0.597633 | 3.489676 | false | false | false | false |
richard92m/three.bar
|
ThreeBar/ThreeBar/SKSceneExtension.swift
|
1
|
1097
|
//
// SKSceneExtension.swift
// ThreeBar
//
// Created by Marquez, Richard A on 12/22/14.
// Copyright (c) 2014 Richard Marquez. All rights reserved.
//
import SpriteKit
extension SKScene {
func getRandomPosition(fromPoint: CGPoint = CGPoint(), minDistance: CGFloat = 0.0) -> CGPoint {
var possiblePosition: CGPoint
var possibleLength: CGFloat
var currentLength = fromPoint.length()
var distance: CGFloat = 0.0
do {
possiblePosition = CGPoint(x: CGFloat(size.width) * (CGFloat(arc4random()) / CGFloat(UInt32.max)),
y: CGFloat(size.height) * (CGFloat(arc4random()) / CGFloat(UInt32.max)))
possibleLength = possiblePosition.length()
distance = abs(currentLength - possibleLength)
} while distance < CGFloat(minDistance)
return possiblePosition
}
func getRelativeDirection(origin: CGPoint, destination: CGPoint) -> CGPoint {
let facingDirection = (destination - origin).normalized()
return facingDirection
}
}
|
gpl-3.0
|
fd4646a156668de3cd27f9a709c963c1
| 31.294118 | 110 | 0.628988 | 4.570833 | false | false | false | false |
knutnyg/ios-iou
|
iou/AddParticipantsParent.swift
|
1
|
2419
|
//
// Created by Knut Nygaard on 18/11/15.
// Copyright (c) 2015 APM solutions. All rights reserved.
//
import Foundation
import SnapKit
enum Type {
case NEW
case UPDATE
}
class AddParticipantsParent: UIViewController {
var addParticipantTableView: AddParticipantsToExpenseTableViewController!
var sendButton: UIButton!
var expense: Expense!
var delegate: GroupViewController!
var type:Type!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
addParticipantTableView = AddParticipantsToExpenseTableViewController()
addParticipantTableView.expense = expense
addParticipantTableView.group = delegate.group
sendButton = createButton("Send", font: UIFont(name: "HelveticaNeue", size: 20)!)
sendButton.addTarget(self, action: "sendButtonPressed:", forControlEvents: .TouchUpInside)
addChildViewController(addParticipantTableView)
view.addSubview(addParticipantTableView.view)
view.addSubview(sendButton)
sendButton.snp_makeConstraints {
(button) -> Void in
button.bottom.equalTo(self.view.snp_bottom).offset(-20)
button.right.equalTo(self.view.snp_right).offset(-20)
}
var tableHeight = delegate.group.members.count * 100 + 100
if tableHeight > 700 {
tableHeight = 700
}
addParticipantTableView.view.snp_makeConstraints {
(make) -> Void in
make.height.equalTo(tableHeight)
make.width.equalTo(self.view.snp_width)
}
}
func sendButtonPressed(sender: UIButton) {
expense.participants = addParticipantTableView.selectedMembers
switch type! {
case .NEW:
API.newExpense(expense)
.onSuccess {
expense in
self.navigationController?.popToViewController(self.delegate, animated: true)
}
.onFailure {
err in
print(err)
}
break
case .UPDATE:
API.putExpense(expense)
.onSuccess{ expense in
self.navigationController?.popToViewController(self.delegate, animated: true)
}
.onFailure{err in print(err)}
break
}
}
}
|
bsd-2-clause
|
150c81c02ffa5481182acd5706ba6ff2
| 29.2375 | 98 | 0.610583 | 5.146809 | false | false | false | false |
Ferrari-lee/firefox-ios
|
FxAClient/Frontend/SignIn/FxAContentViewController.swift
|
17
|
6376
|
/* 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 SnapKit
import UIKit
import WebKit
protocol FxAContentViewControllerDelegate: class {
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void
func contentViewControllerDidCancel(viewController: FxAContentViewController)
}
/**
* A controller that manages a single web view connected to the Firefox
* Accounts (Desktop) Sync postMessage interface.
*
* The postMessage interface is not really documented, but it is simple
* enough. I reverse engineered it from the Desktop Firefox code and the
* fxa-content-server git repository.
*/
class FxAContentViewController: SettingsContentViewController, WKScriptMessageHandler {
private enum RemoteCommand: String {
case CanLinkAccount = "can_link_account"
case Loaded = "loaded"
case Login = "login"
case SessionStatus = "session_status"
case SignOut = "sign_out"
}
weak var delegate: FxAContentViewControllerDelegate?
init() {
super.init(backgroundColor: UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0), title: NSAttributedString(string: "Firefox Accounts"))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func makeWebView() -> WKWebView {
// Inject our setup code after the page loads.
let source = getJS()
let userScript = WKUserScript(
source: source,
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true
)
// Handle messages from the content server (via our user script).
let contentController = WKUserContentController()
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(
self,
name: "accountsCommandHandler"
)
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(
frame: CGRect(x: 0, y: 0, width: 1, height: 1),
configuration: config
)
webView.navigationDelegate = self
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
// Don't allow overscrolling.
webView.scrollView.bounces = false
return webView
}
// Send a message to the content server.
func injectData(type: String, content: [String: AnyObject]) {
NSLog("injectData: " + type)
let data = [
"type": type,
"content": content,
]
let json = JSON(data).toString(false)
let script = "window.postMessage(\(json), '\(self.url)');"
webView.evaluateJavaScript(script, completionHandler: nil)
}
private func onCanLinkAccount(data: JSON) {
// // We need to confirm a relink - see shouldAllowRelink for more
// let ok = shouldAllowRelink(accountData.email);
let ok = true
injectData("message", content: ["status": "can_link_account", "data": ["ok": ok]]);
}
// We're not signed in to a Firefox Account at this time, which we signal by returning an error.
private func onSessionStatus(data: JSON) {
injectData("message", content: ["status": "error"])
}
// We're not signed in to a Firefox Account at this time. We should never get a sign out message!
private func onSignOut(data: JSON) {
injectData("message", content: ["status": "error"])
}
// The user has signed in to a Firefox Account. We're done!
private func onLogin(data: JSON) {
NSLog("onLogin: " + data.toString())
injectData("message", content: ["status": "login"])
self.delegate?.contentViewControllerDidSignIn(self, data: data)
}
// The content server page is ready to be shown.
private func onLoaded() {
NSLog("Handling loaded remote command.");
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
// Handle a message coming from the content server.
func handleRemoteCommand(rawValue: String, data: JSON) {
if let command = RemoteCommand(rawValue: rawValue) {
NSLog("Handling remote command '\(rawValue)' .");
if !isLoaded && command != .Loaded {
// Work around https://github.com/mozilla/fxa-content-server/issues/2137
NSLog("Synthesizing loaded remote command.")
onLoaded()
}
switch (command) {
case .Loaded:
onLoaded()
case .Login:
onLogin(data)
case .CanLinkAccount:
onCanLinkAccount(data)
case .SessionStatus:
onSessionStatus(data)
case .SignOut:
onSignOut(data)
}
} else {
NSLog("Unknown remote command '\(rawValue)'; ignoring.");
}
}
// Dispatch webkit messages originating from our child webview.
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if (message.name == "accountsCommandHandler") {
let body = JSON(message.body)
let detail = body["detail"]
handleRemoteCommand(detail["command"].asString!, data: detail["data"])
} else {
NSLog("Got unrecognized message \(message)")
}
}
private func getJS() -> String {
let fileRoot = NSBundle.mainBundle().pathForResource("FxASignIn", ofType: "js")
return (try! NSString(contentsOfFile: fileRoot!, encoding: NSUTF8StringEncoding)) as String
}
override func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
// Ignore for now.
}
override func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
// Ignore for now.
}
}
|
mpl-2.0
|
510166f4a0cd35511ceb28ccd950219b
| 35.649425 | 168 | 0.635979 | 4.91596 | false | false | false | false |
trenskow/Slaminate
|
Slaminate/PropertyInfo.swift
|
1
|
1774
|
//
// PropertyInfo.swift
// Slaminate
//
// Created by Kristian Trenskow on 08/02/16.
// Copyright © 2016 Trenskow.io. All rights reserved.
//
import Foundation
protocol PropertyInfoProtocol: Equatable, Hashable {
weak var object: NSObject? { get set }
var key: String { get set }
var fromValue: NSObject? { get set }
var toValue: NSObject? { get set }
func applyFromValue()
func applyToValue()
init(object: NSObject, key: String)
}
extension PropertyInfoProtocol {
func applyFromValue() {
object?.setValue(fromValue, forKey: key)
}
func applyToValue() {
object?.setValue(toValue, forKey: key)
}
var hashValue: Int {
return (object?.hashValue ?? 0) + key.hashValue
}
}
func ==<T: PropertyInfoProtocol>(lhs: T, rhs: T) -> Bool {
return lhs.object == rhs.object && lhs.key == rhs.key
}
func ==<T: PropertyInfoProtocol>(lhs: T, rhs: (NSObject, String)) -> Bool {
return lhs.object == rhs.0 && lhs.key == rhs.1
}
struct PropertyInfo: PropertyInfoProtocol {
weak var object: NSObject?
var key: String
var fromValue: NSObject?
var toValue: NSObject?
init(object: NSObject, key: String) {
self.object = object
self.key = key
}
}
extension Array where Element: PropertyInfoProtocol {
mutating func indexOf(_ object: NSObject, key: String) -> Index {
for index in self.indices {
if self[index] == (object, key) {
return index
}
}
append(Element(object: object, key: key))
return endIndex.advanced(by: -1)
}
func applyFromValues() {
self.forEach({ $0.applyFromValue() })
}
func applyToValues() {
self.forEach({ $0.applyToValue() })
}
}
|
mit
|
71a1b003f3f5f71f91b20d6226601a1a
| 25.073529 | 75 | 0.615341 | 3.862745 | false | false | false | false |
pkkup/Pkkup-iOS
|
Pkkup/viewControllers/CreateGameViewController.swift
|
1
|
6680
|
//
// CreateGameViewController.swift
// Pkkup
//
// Created by Deepak on 10/19/14.
// Copyright (c) 2014 Pkkup. All rights reserved.
//
import UIKit
protocol CreateGameViewControllerDelegate
{
func locationSelected(location: String, rowSelected: Int)
func sportSelected(sport: String, rowSelected: Int)
}
class CreateGameViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CreateGameViewControllerDelegate {
@IBOutlet weak var createGameButton: UIButton!
@IBOutlet var createGameTableView: UITableView!
@IBOutlet weak var gameDatePicker: UIDatePicker!
var locations: [PkkupLocation] = _LOCATIONS
var games: [PkkupGame] = _GAMES
var sports: [PkkupSport] = _SPORTS
var isPickerChanged: Bool! = false
var sectionExpanded = [0: false, 1: false]
var locationRowSelected = 0
var sportRowSelected = 0
var gameDate: String!
var delegate:CreateGameViewControllerDelegate?
var selectedLocation: String!
var selectedSport: String!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = _THEME_COLOR
createGameTableView.dataSource = self
createGameTableView.delegate = self
self.createGameTableView.reloadData()
gameDatePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headerView = UIView(frame: CGRect(x:0, y:0, width: 320, height: 30))
headerView.backgroundColor = UIColor.whiteColor()
var headerLabel = UILabel(frame: CGRect(x:0, y:0, width:320, height: 30))
if (section == 0) {
headerLabel.text = "Location"
}
if (section == 1) {
headerLabel.text = "Sport"
}
headerView.addSubview(headerLabel)
return headerView
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(section == 0) {
if (sectionExpanded[section] == true) {
return locations.count
} else {
return 1
}
}
if(section == 1) {
if (sectionExpanded[section] == true) {
return sports.count
} else {
return 1
}
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var section = indexPath.section
if(section == 0 || section == 1) {
var cell = tableView.dequeueReusableCellWithIdentifier("LocationSportCell") as LocationSportCell
cell.section = indexPath.section
if (!sectionExpanded[section]!) {
if (section == 0) {
cell.row = locationRowSelected
} else if section == 1 {
cell.row = sportRowSelected
}
} else {
cell.row = indexPath.row
}
cell.sportSelected = self.sportRowSelected
cell.locationSelected = self.locationRowSelected
cell.sectionExpanded = sectionExpanded[section]!
cell.createGameDelegate = delegate
return cell
} else {
//var cell = tableView.dequeueReusableCellWithIdentifier("CreateGameCell") as CreateGameCell
return UITableViewCell()
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
createGameTableView.deselectRowAtIndexPath(indexPath, animated: true)
var section = indexPath.section
if (section == 0 || section == 1) {
if (sectionExpanded[section] == true) {
if (section == 0) {
locationRowSelected = indexPath.row
println("locationRowSelected = \(locationRowSelected)")
self.delegate?.locationSelected(locations[indexPath.row].name!, rowSelected: indexPath.row)
} else {
sportRowSelected = indexPath.row
println("sportRowSelected = \(sportRowSelected)")
self.delegate?.sportSelected(sports[indexPath.row].name!, rowSelected: indexPath.row)
}
sectionExpanded[section] = false
} else {
sectionExpanded[section] = true
}
}
tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: UITableViewRowAnimation.Fade)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func locationSelected(location: String, rowSelected: Int) {
self.selectedLocation = location
self.locationRowSelected = rowSelected
}
func sportSelected(sport: String, rowSelected: Int) {
self.selectedSport = sport
self.sportRowSelected = rowSelected
}
@IBAction func onCreate(sender: AnyObject) {
//var sportId: Int = (PkkupSport)self.sportRowSelected
var sportName: String = PkkupSport.get(self.sportRowSelected).name!
var newGame: PkkupGame = PkkupGame()
newGame.location?.id = self.locationRowSelected
newGame.sport?.id = self.sportRowSelected
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
newGame.startTime = dateFormatter.dateFromString(self.gameDate)
}
func datePickerChanged(datePicker:UIDatePicker) {
println("Date changed ####")
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var strDate = dateFormatter.stringFromDate(datePicker.date)
self.gameDate = strDate
println("Game strDate = \(strDate)")
}
@IBAction func onViewTap(sender: UITapGestureRecognizer) {
view.endEditing(true)
}
}
|
mit
|
bcfd0a61bb74c3787b43f7804604820d
| 33.43299 | 128 | 0.616916 | 5.255704 | false | false | false | false |
suragch/MongolAppDevelopment-iOS
|
Mongol App Componants/UIMongolButton.swift
|
1
|
4550
|
// UIMongolButton
// version 1.0
import UIKit
@IBDesignable class UIMongolButton: UIControl {
// MARK:- Unique to Button
// ********* Unique to Button *********
fileprivate let view = UIButton()
fileprivate var userInteractionEnabledForSubviews = false
let mongolFontName = "ChimeeWhiteMirrored"
let defaultFontSize: CGFloat = 17
func setTitle(_ title: String, forState: UIControlState) {
self.view.setTitle(title, for: forState)
}
func setTitleColor(_ color: UIColor, forState: UIControlState) {
self.view.setTitleColor(color, for: forState)
}
@IBInspectable var title: String {
get {
return view.titleLabel?.text ?? ""
}
set {
self.setTitle(newValue, forState: UIControlState())
//view.titleLabel!.text = newValue
}
}
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.beginTracking(touch, with: event)
print("touch began")
return true // return true if needs to respond when touch is dragged
}
override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.continueTracking(touch, with: event)
let lastPoint = touch.location(in: self)
// do something with lastPoint
print("touching point: \(lastPoint)")
self.sendActions(for: UIControlEvents.valueChanged)
return true // if want to track at touch location
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
print("touch ended")
}
func setup() {
self.view.setTitleColor(UIColor.blue, for: UIControlState())
self.view.isUserInteractionEnabled = userInteractionEnabledForSubviews
// set font if user didn't specify size in IB
if self.view.titleLabel?.font.fontName != mongolFontName {
view.titleLabel!.font = UIFont(name: mongolFontName, size: defaultFontSize)
}
}
// MARK:- General code for Mongol views
// *******************************************
// ****** General code for Mongol views ******
// *******************************************
fileprivate var oldWidth: CGFloat = 0
fileprivate var oldHeight: CGFloat = 0
// This method gets called if you create the view in the Interface Builder
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method gets called if you create the view in code
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
// layoutSubviews gets called multiple times, only need it once
if self.frame.height == oldHeight && self.frame.width == oldWidth {
return
} else {
oldWidth = self.frame.width
oldHeight = self.frame.height
}
// Remove the old rotation view
if self.subviews.count > 0 {
self.subviews[0].removeFromSuperview()
}
// setup rotationView container
let rotationView = UIView()
rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
rotationView.isUserInteractionEnabled = userInteractionEnabledForSubviews
self.addSubview(rotationView)
// transform rotationView (so that it covers the same frame as self)
rotationView.transform = translateRotateFlip()
// add view
view.frame = rotationView.bounds
rotationView.addSubview(view)
}
func translateRotateFlip() -> CGAffineTransform {
var transform = CGAffineTransform.identity
// translate to new center
transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2))
// rotate counterclockwise around center
transform = transform.rotated(by: CGFloat(-M_PI_2))
// flip vertically
transform = transform.scaledBy(x: -1, y: 1)
return transform
}
}
|
mit
|
a59067fbc606c6767c92c657478f7ae5
| 30.37931 | 148 | 0.588132 | 5.13544 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/DiscoveryV1/Models/Field.swift
|
1
|
1468
|
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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
/**
Object containing field details.
*/
public struct Field: Codable, Equatable {
/**
The type of the field.
*/
public enum TypeEnum: String {
case nested = "nested"
case string = "string"
case date = "date"
case long = "long"
case integer = "integer"
case short = "short"
case byte = "byte"
case double = "double"
case float = "float"
case boolean = "boolean"
case binary = "binary"
}
/**
The name of the field.
*/
public var field: String?
/**
The type of the field.
*/
public var type: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case field = "field"
case type = "type"
}
}
|
apache-2.0
|
acef4592677ed7c72a774ef037df7f83
| 24.754386 | 82 | 0.626022 | 4.194286 | false | false | false | false |
salemoh/GoldenQuraniOS
|
GoldenQuranSwift/Pods/GRDB.swift/GRDB/QueryInterface/QueryInterfaceRequest.swift
|
1
|
15374
|
/// A QueryInterfaceRequest describes an SQL query.
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<T> : TypedRequest {
public typealias Fetched = T
let query: QueryInterfaceSelectQueryDefinition
init(query: QueryInterfaceSelectQueryDefinition) {
self.query = query
}
}
extension QueryInterfaceRequest : SQLSelectQuery {
/// This function is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// See SQLSelectQuery.selectQuerySQL(_)
public func selectQuerySQL(_ arguments: inout StatementArguments?) -> String {
return query.selectQuerySQL(&arguments)
}
}
extension QueryInterfaceRequest {
// MARK: Request Derivation
/// A new QueryInterfaceRequest with a new net of selected columns.
///
/// // SELECT id, email FROM persons
/// var request = Person.all()
/// request = request.select(Column("id"), Column("email"))
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM persons
/// request
/// .select(Column("id"))
/// .select(Column("email"))
public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<T> {
return select(selection)
}
/// A new QueryInterfaceRequest with a new net of selected columns.
///
/// // SELECT id, email FROM persons
/// var request = Person.all()
/// request = request.select([Column("id"), Column("email")])
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM persons
/// request
/// .select([Column("id")])
/// .select([Column("email")])
public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<T> {
var query = self.query
query.selection = selection
return QueryInterfaceRequest(query: query)
}
/// A new QueryInterfaceRequest with a new net of selected columns.
///
/// // SELECT id, email FROM persons
/// var request = Person.all()
/// request = request.select(sql: "id, email")
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM persons
/// request
/// .select(sql: "id")
/// .select(sql: "email")
public func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
return select(SQLExpressionLiteral(sql, arguments: arguments))
}
/// A new QueryInterfaceRequest which returns distinct rows.
///
/// // SELECT DISTINCT * FROM persons
/// var request = Person.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM persons
/// var request = Person.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest<T> {
var query = self.query
query.isDistinct = true
return QueryInterfaceRequest(query: query)
}
/// A new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
///
/// // SELECT * FROM persons WHERE email = '[email protected]'
/// var request = Person.all()
/// request = request.filter(Column("email") == "[email protected]")
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
var query = self.query
if let whereExpression = query.whereExpression {
query.whereExpression = whereExpression && predicate.sqlExpression
} else {
query.whereExpression = predicate.sqlExpression
}
return QueryInterfaceRequest(query: query)
}
/// A new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
///
/// // SELECT * FROM persons WHERE email = '[email protected]'
/// var request = Person.all()
/// request = request.filter(sql: "email = ?", arguments: ["[email protected]"])
public func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
return filter(SQLExpressionLiteral(sql, arguments: arguments))
}
/// A new QueryInterfaceRequest grouped according to *expressions*.
public func group(_ expressions: SQLExpressible...) -> QueryInterfaceRequest<T> {
return group(expressions)
}
/// A new QueryInterfaceRequest grouped according to *expressions*.
public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest<T> {
var query = self.query
query.groupByExpressions = expressions.map { $0.sqlExpression }
return QueryInterfaceRequest(query: query)
}
/// A new QueryInterfaceRequest with a new grouping.
public func group(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
return group(SQLExpressionLiteral(sql, arguments: arguments))
}
/// A new QueryInterfaceRequest with the provided *predicate* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
var query = self.query
if let havingExpression = query.havingExpression {
query.havingExpression = (havingExpression && predicate).sqlExpression
} else {
query.havingExpression = predicate.sqlExpression
}
return QueryInterfaceRequest(query: query)
}
/// A new QueryInterfaceRequest with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
return having(SQLExpressionLiteral(sql, arguments: arguments))
}
/// A new QueryInterfaceRequest with the provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.all()
/// request = request.order(Column("name"))
///
/// Any previous ordering is replaced:
///
/// // SELECT * FROM persons ORDER BY name
/// request
/// .order(Column("email"))
/// .order(Column("name"))
public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<T> {
return order(orderings)
}
/// A new QueryInterfaceRequest with the provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.all()
/// request = request.order([Column("name")])
///
/// Any previous ordering is replaced:
///
/// // SELECT * FROM persons ORDER BY name
/// request
/// .order([Column("email")])
/// .order([Column("name")])
public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<T> {
var query = self.query
query.orderings = orderings
return QueryInterfaceRequest(query: query)
}
/// A new QueryInterfaceRequest with the provided *sql* used for sorting.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.all()
/// request = request.order(sql: "name")
///
/// Any previous ordering is replaced:
///
/// // SELECT * FROM persons ORDER BY name
/// request
/// .order(sql: "email")
/// .order(sql: "name")
public func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
return order([SQLExpressionLiteral(sql, arguments: arguments)])
}
/// A new QueryInterfaceRequest sorted in reversed order.
///
/// // SELECT * FROM persons ORDER BY name DESC
/// var request = Person.all().order(Column("name"))
/// request = request.reversed()
public func reversed() -> QueryInterfaceRequest<T> {
var query = self.query
query.isReversed = !query.isReversed
return QueryInterfaceRequest(query: query)
}
/// A QueryInterfaceRequest which fetches *limit* rows, starting
/// at *offset*.
///
/// // SELECT * FROM persons LIMIT 1
/// var request = Person.all()
/// request = request.limit(1)
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T> {
var query = self.query
query.limit = SQLLimit(limit: limit, offset: offset)
return QueryInterfaceRequest(query: query)
}
}
extension QueryInterfaceRequest {
// MARK: Counting
/// The number of rows fetched by the request.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
return try query.fetchCount(db)
}
}
extension QueryInterfaceRequest {
// MARK: Deleting
/// Deletes matching rows; returns the number of deleted rows.
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try query.makeDeleteStatement(db).execute()
return db.changesCount
}
}
extension TableMapping {
// MARK: Request Derivation
/// Creates a QueryInterfaceRequest which fetches all records.
///
/// // SELECT * FROM persons
/// var request = Person.all()
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons
/// var request = Person.all()
public static func all() -> QueryInterfaceRequest<Self> {
let selection: [SQLSelectable]
if selectsRowID {
selection = [star, Column.rowID]
} else {
selection = [star]
}
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: selection, from: .table(name: databaseTableName, alias: nil)))
}
/// Creates a QueryInterfaceRequest which fetches no record.
public static func none() -> QueryInterfaceRequest<Self> {
return filter(false)
}
/// Creates a QueryInterfaceRequest which selects *selection*.
///
/// // SELECT id, email FROM persons
/// var request = Person.select(Column("id"), Column("email"))
public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<Self> {
return all().select(selection)
}
/// Creates a QueryInterfaceRequest which selects *selection*.
///
/// // SELECT id, email FROM persons
/// var request = Person.select([Column("id"), Column("email")])
public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<Self> {
return all().select(selection)
}
/// Creates a QueryInterfaceRequest which selects *sql*.
///
/// // SELECT id, email FROM persons
/// var request = Person.select(sql: "id, email")
public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().select(sql: sql, arguments: arguments)
}
/// Creates a QueryInterfaceRequest with the provided *predicate*.
///
/// // SELECT * FROM persons WHERE email = '[email protected]'
/// var request = Person.filter(Column("email") == "[email protected]")
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons WHERE email = '[email protected]'
/// var request = Person.filter(Column("email") == "[email protected]")
public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<Self> {
return all().filter(predicate)
}
/// Creates a QueryInterfaceRequest with the provided *predicate*.
///
/// // SELECT * FROM persons WHERE email = '[email protected]'
/// var request = Person.filter(sql: "email = ?", arguments: ["[email protected]"])
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons WHERE email = '[email protected]'
/// var request = Person.filter(sql: "email = ?", arguments: ["[email protected]"])
public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().filter(sql: sql, arguments: arguments)
}
/// Creates a QueryInterfaceRequest sorted according to the
/// provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.order(Column("name"))
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons ORDER BY name
/// var request = Person.order(Column("name"))
public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<Self> {
return all().order(orderings)
}
/// Creates a QueryInterfaceRequest sorted according to the
/// provided *orderings*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.order([Column("name")])
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons ORDER BY name
/// var request = Person.order([Column("name")])
public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<Self> {
return all().order(orderings)
}
/// Creates a QueryInterfaceRequest sorted according to *sql*.
///
/// // SELECT * FROM persons ORDER BY name
/// var request = Person.order(sql: "name")
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons ORDER BY name
/// var request = Person.order(sql: "name")
public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().order(sql: sql, arguments: arguments)
}
/// Creates a QueryInterfaceRequest which fetches *limit* rows, starting at
/// *offset*.
///
/// // SELECT * FROM persons LIMIT 1
/// var request = Person.limit(1)
///
/// If the `selectsRowID` type property is true, then the selection includes
/// the hidden "rowid" column:
///
/// // SELECT *, rowid FROM persons LIMIT 1
/// var request = Person.limit(1)
public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self> {
return all().limit(limit, offset: offset)
}
}
|
mit
|
fab29b3c9e3d310442bad17eaaed24b1
| 37.435 | 150 | 0.612788 | 4.714505 | false | false | false | false |
tiagomartinho/swift-corelibs-xctest
|
Tests/Functional/Asynchronous/Predicates/Expectations/main.swift
|
1
|
4368
|
// RUN: %{swiftc} %s -o %T/Asynchronous-Predicates
// RUN: %T/Asynchronous-Predicates > %t || true
// RUN: %{xctest_checker} %t %s
#if os(macOS)
import SwiftXCTest
#else
import XCTest
#endif
// CHECK: Test Suite 'All tests' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: Test Suite '.*\.xctest' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: Test Suite 'PredicateExpectationsTestCase' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
class PredicateExpectationsTestCase: XCTestCase {
// CHECK: Test Case 'PredicateExpectationsTestCase.test_immediatelyTruePredicateAndObject_passes' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: Test Case 'PredicateExpectationsTestCase.test_immediatelyTruePredicateAndObject_passes' passed \(\d+\.\d+ seconds\)
func test_immediatelyTruePredicateAndObject_passes() {
let predicate = NSPredicate(value: true)
let object = NSObject()
expectation(for: predicate, evaluatedWith: object)
waitForExpectations(timeout: 0.1)
}
// CHECK: Test Case 'PredicateExpectationsTestCase.test_immediatelyFalsePredicateAndObject_fails' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: .*/Tests/Functional/Asynchronous/Predicates/Expectations/main.swift:[[@LINE+6]]: error: PredicateExpectationsTestCase.test_immediatelyFalsePredicateAndObject_fails : Asynchronous wait failed - Exceeded timeout of 0.1 seconds, with unfulfilled expectations: Expect `<NSPredicate: 0x[0-9A-Fa-f]{1,16}>` for object <NSObject: 0x[0-9A-Fa-f]{1,16}>
// CHECK: Test Case 'PredicateExpectationsTestCase.test_immediatelyFalsePredicateAndObject_fails' failed \(\d+\.\d+ seconds\)
func test_immediatelyFalsePredicateAndObject_fails() {
let predicate = NSPredicate(value: false)
let object = NSObject()
expectation(for: predicate, evaluatedWith: object)
waitForExpectations(timeout: 0.1)
}
// CHECK: Test Case 'PredicateExpectationsTestCase.test_delayedTruePredicateAndObject_passes' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: Test Case 'PredicateExpectationsTestCase.test_delayedTruePredicateAndObject_passes' passed \(\d+\.\d+ seconds\)
func test_delayedTruePredicateAndObject_passes() {
var didEvaluate = false
let predicate = NSPredicate(block: { evaluatedObject, bindings in
defer { didEvaluate = true }
return didEvaluate
})
expectation(for: predicate, evaluatedWith: NSObject())
waitForExpectations(timeout: 0.1)
}
// CHECK: Test Case 'PredicateExpectationsTestCase.test_immediatelyTrueDelayedFalsePredicateAndObject_passes' started at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: Test Case 'PredicateExpectationsTestCase.test_immediatelyTrueDelayedFalsePredicateAndObject_passes' passed \(\d+\.\d+ seconds\)
func test_immediatelyTrueDelayedFalsePredicateAndObject_passes() {
var didEvaluate = false
let predicate = NSPredicate(block: { evaluatedObject, bindings in
defer { didEvaluate = true }
return !didEvaluate
})
expectation(for: predicate, evaluatedWith: NSObject())
XCTAssertTrue(didEvaluate)
waitForExpectations(timeout: 0.1)
}
static var allTests = {
return [
("test_immediatelyTruePredicateAndObject_passes", test_immediatelyTruePredicateAndObject_passes),
("test_immediatelyFalsePredicateAndObject_fails", test_immediatelyFalsePredicateAndObject_fails),
("test_delayedTruePredicateAndObject_passes", test_delayedTruePredicateAndObject_passes),
("test_immediatelyTrueDelayedFalsePredicateAndObject_passes", test_immediatelyTrueDelayedFalsePredicateAndObject_passes),
]
}()
}
// CHECK: Test Suite 'PredicateExpectationsTestCase' failed at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: \t Executed 4 tests, with 1 failure \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds
XCTMain([testCase(PredicateExpectationsTestCase.allTests)])
// CHECK: Test Suite '.*\.xctest' failed at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: \t Executed 4 tests, with 1 failure \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds
// CHECK: Test Suite 'All tests' failed at \d+-\d+-\d+ \d+:\d+:\d+\.\d+
// CHECK: \t Executed 4 tests, with 1 failure \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds
|
apache-2.0
|
839398574d9f5c6781b48b1402286d3a
| 55 | 357 | 0.676969 | 4.05571 | false | true | false | false |
dreamsxin/swift
|
test/Constraints/bridging.swift
|
2
|
15785
|
// RUN: %target-parse-verify-swift
// REQUIRES: objc_interop
import Foundation
public class BridgedClass : NSObject, NSCopying {
@objc(copyWithZone:)
public func copy(with zone: NSZone?) -> AnyObject {
return self
}
}
public class BridgedClassSub : BridgedClass { }
// Attempt to bridge to a non-whitelisted type from another module.
extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}}
public typealias _ObjectiveCType = BridgedClassSub
public static func _isBridgedToObjectiveC() -> Bool { return true }
public func _bridgeToObjectiveC() -> _ObjectiveCType {
return BridgedClassSub()
}
public static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterIterator?
) { }
public static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterIterator?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> LazyFilterIterator {
let result: LazyFilterIterator?
return result!
}
}
struct BridgedStruct : Hashable, _ObjectiveCBridgeable {
var hashValue: Int { return 0 }
static func _isBridgedToObjectiveC() -> Bool {
return true
}
func _bridgeToObjectiveC() -> BridgedClass {
return BridgedClass()
}
static func _forceBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?
) -> Bool {
return true
}
static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?)
-> BridgedStruct {
var result: BridgedStruct? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true }
struct NotBridgedStruct : Hashable {
var hashValue: Int { return 0 }
}
func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true }
class OtherClass : Hashable {
var hashValue: Int { return 0 }
}
func ==(x: OtherClass, y: OtherClass) -> Bool { return true }
// Basic bridging
func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass {
return s
return s as BridgedClass
}
func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject {
return s
return s as AnyObject
}
func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct {
return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return c as BridgedStruct
}
func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct {
return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return s as BridgedStruct
}
// Array -> NSArray
func arrayToNSArray() {
var nsa: NSArray
nsa = [AnyObject]()
nsa = [BridgedClass]()
nsa = [OtherClass]()
nsa = [BridgedStruct]()
nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}}
nsa = [AnyObject]() as NSArray
nsa = [BridgedClass]() as NSArray
nsa = [OtherClass]() as NSArray
nsa = [BridgedStruct]() as NSArray
nsa = [NotBridgedStruct]() as NSArray // expected-error{{cannot convert value of type '[NotBridgedStruct]' to type 'NSArray' in coercion}}
_ = nsa
}
// NSArray -> Array
func nsArrayToArray(_ nsa: NSArray) {
var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}}
var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}}
var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}}
var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}}
var _: [NotBridgedStruct] = nsa // expected-error{{cannot convert value of type 'NSArray' to specified type '[NotBridgedStruct]'}}
var _: [AnyObject] = nsa as [AnyObject]
var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}}
var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}}
var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}}
var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{cannot convert value of type 'NSArray' to type '[NotBridgedStruct]' in coercion}}
var arr6: Array = nsa as Array
arr6 = arr1
arr1 = arr6
}
func dictionaryToNSDictionary() {
// FIXME: These diagnostics are awful.
var nsd: NSDictionary
nsd = [NSObject : AnyObject]()
nsd = [NSObject : AnyObject]() as NSDictionary
nsd = [NSObject : BridgedClass]()
nsd = [NSObject : BridgedClass]() as NSDictionary
nsd = [NSObject : OtherClass]()
nsd = [NSObject : OtherClass]() as NSDictionary
nsd = [NSObject : BridgedStruct]()
nsd = [NSObject : BridgedStruct]() as NSDictionary
nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}}
nsd = [NSObject : NotBridgedStruct]() as NSDictionary // expected-error{{cannot convert value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary' in coercion}}
nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedClass?]() as NSDictionary // expected-error{{cannot convert value of type '[NSObject : BridgedClass?]' to type 'NSDictionary' in coercion}}
nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedStruct?]() as NSDictionary //expected-error{{cannot convert value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary' in coercion}}
nsd = [BridgedClass : AnyObject]()
nsd = [BridgedClass : AnyObject]() as NSDictionary
nsd = [OtherClass : AnyObject]()
nsd = [OtherClass : AnyObject]() as NSDictionary
nsd = [BridgedStruct : AnyObject]()
nsd = [BridgedStruct : AnyObject]() as NSDictionary
nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}}
nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // expected-error{{cannot convert value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary' in coercion}}
// <rdar://problem/17134986>
var bcOpt: BridgedClass?
nsd = [BridgedStruct() : bcOpt] // expected-error{{value of optional type 'BridgedClass?' not unwrapped; did you mean to use '!' or '?'?}}
bcOpt = nil
_ = nsd
}
// In this case, we should not implicitly convert Dictionary to NSDictionary.
struct NotEquatable {}
func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool {
// FIXME: Another awful diagnostic.
return d == d // expected-error{{binary operator '==' cannot be applied to two 'Dictionary<Int, NotEquatable>' operands}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }}
}
// NSString -> String
var nss1 = "Some great text" as NSString
var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString
// <rdar://problem/17943223>
var inferDouble = 1.0/10
let d: Double = 3.14159
inferDouble = d
// rdar://problem/17962491
var inferDouble2 = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: Use truncatingRemainder instead}}
let d2: Double = 3.14159
inferDouble2 = d2
// rdar://problem/18269449
var i1: Int = 1.5 * 3.5 // expected-error {{binary operator '*' cannot be applied to two 'Double' operands}} expected-note {{expected an argument list of type '(Int, Int)'}}
// rdar://problem/18330319
func rdar18330319(_ s: String, d: [String : AnyObject]) {
_ = d[s] as! String?
}
// rdar://problem/19551164
func rdar19551164a(_ s: String, _ a: [String]) {}
func rdar19551164b(_ s: NSString, _ a: NSArray) {
rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}}
// expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}}
}
// rdar://problem/19695671
func takesSet<T: Hashable>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}}
func takesDictionary<K: Hashable, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}}
func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}}
func rdar19695671() {
takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}}
takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}}
takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}}
}
// This failed at one point while fixing rdar://problem/19600325.
func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] }
func testCallback(_ f: (AnyObject) -> AnyObject?) {}
testCallback { return getArrayOfAnyObject($0) }
// <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast
func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) {
f((s1 ?? s2) as String)
}
// <rdar://problem/19770981>
func rdar19770981(_ s: String, ns: NSString) {
func f(_ s: String) {}
f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}}
f(ns as String)
// 'as' has higher precedence than '>' so no parens are necessary with the fixit:
s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}}
_ = s > ns as String
ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}}
_ = ns as String > s
// 'as' has lower precedence than '+' so add parens with the fixit:
s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}}
_ = s + (ns as String)
ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}}
_ = (ns as String) + s
}
// <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail
func rdar19831919() {
var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions
func rdar19831698() {
var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
var v71 = true + 1.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} expected-note {{expected an argument list of type '(Double, Double)'}}
var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[_]'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}}
}
// <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions
func rdar19836341(_ ns: NSString?, vns: NSString?) {
var vns = vns
let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
// FIXME: there should be a fixit appending "as String?" to the line; for now
// it's sufficient that it doesn't suggest appending "as String"
// Important part about below diagnostic is that from-type is described as
// 'NSString?' and not '@lvalue NSString?':
let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}
vns = ns
}
// <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!"
func rdar20029786(_ ns: NSString?) {
var s: String = ns ?? "str" as String as String // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}
var s2 = ns ?? "str" as String as String
let s3: NSString? = "str" as String?
var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{20-20=(}}{{31-31=) as String}}
var s5: String = (ns ?? "str") as String // fixed version
}
// <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic
func rdar19813772(_ nsma: NSMutableArray) {
var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array<_>'}}
// FIXME: The following diagnostic is misleading and should not happen: expected-warning@-1{{cast from 'NSMutableArray' to unrelated type 'Array<_>' always fails}}
var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}}
var a3 = nsma as Array<AnyObject>
}
// <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds"
func force_cast_fixit(_ a : [NSString]) -> [NSString] {
return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}}
}
// <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types
func rdar21244068(_ n: NSString!) -> String {
return n // expected-error {{'NSString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{11-11= as String}}
}
func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct {
return obj // expected-error{{'BridgedClass!' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}{{13-13= as BridgedStruct}}
}
|
apache-2.0
|
27d0a02a9e274f63d75f7a5252739cb7
| 47.272171 | 305 | 0.696801 | 4.133281 | false | false | false | false |
rails365/elected
|
elected-ios/elected-ios/CitiesTableViewController.swift
|
1
|
3316
|
//
// CitiesTableViewController.swift
// elected-ios
//
// Created by Peter Hitchcock on 3/24/16.
// Copyright © 2016 Peter Hitchcock. All rights reserved.
//
import UIKit
import Alamofire
import Haneke
class CitiesTableViewController: UITableViewController {
var cities = [City]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.tableFooterView = UIView()
getLocations()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CityTableViewCell
cell.nameLabel.text = cities[indexPath.row].name
if cities[indexPath.row].image.isEmpty {
cell.cellImageView.image = UIImage(named: "logo")
} else {
let URLString = cities[indexPath.row].image
let URL = NSURL(string:URLString)!
cell.cellImageView.hnk_setImageFromURL(URL)
}
return cell
}
func getLocations() {
Alamofire.request(.GET, "https://sac-elected.herokuapp.com/api/v1/cities")
.responseJSON { response in
if let JSON = response.result.value {
self.cities.removeAll()
let dict = JSON
let ar = dict["cities"] as! [AnyObject]
for a in ar {
// TODO: Potential crash if streetnumber != a numerical string need to check
var name: String
var id: Int
var image: String
if let nameJson = a["name"] {
name = nameJson as! String
} else {
name = "ERROR"
}
if let idJson = a["id"] {
id = idJson as! Int
} else {
id = 0
}
if let imageJson = a["image"] {
image = imageJson as! String
} else {
image = "ERROR"
}
let city = City(name: name, id: id, image: image)
self.cities.append(city)
}
self.tableView.reloadData()
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "officialsSegue" {
let dvc = segue.destinationViewController as! MembersTableViewController
if let row = tableView.indexPathForSelectedRow?.row {
let city = cities[row]
dvc.city = city
}
}
}
}
|
mit
|
08d51466a1f68a6bc0713aa1aa15fd42
| 28.336283 | 118 | 0.506486 | 5.525 | false | false | false | false |
otanistudio/RealmTwitterExample
|
RealmTwitterExample/AuthViewController.swift
|
1
|
3771
|
//
// AuthViewController.swift
// RealmTwitterExample
//
// Created by Robert Otani on 5/4/16.
// Copyright © 2016 otanistudio.com. All rights reserved.
//
import Accounts
import RealmSwift
import Social
import UIKit
class AuthViewController: UIViewController {
@IBOutlet weak var authButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var accountStore: ACAccountStore!
var twAccountType: ACAccountType!
var account: ACAccount?
override func viewDidLoad() {
super.viewDidLoad()
accountStore = ACAccountStore()
twAccountType = self.accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
}
@IBAction func didTapChooseTwitter() {
accountStore.requestAccessToAccounts(with: self.twAccountType, options: nil) { isGranted, error in
guard isGranted else {
DispatchQueue.main.async {
self.displayAlertWithMessage("Access to Twitter account denied. Check iOS Settings.")
}
return
}
let twAccounts = self.accountStore.accounts(with: self.twAccountType) as? [ACAccount]
if twAccounts?.count > 0 {
DispatchQueue.main.async {
self.chooseAccount(twAccounts!)
}
} else {
DispatchQueue.main.async {
self.displayAlertWithMessage("Sorry… couldn’t find Twitter accounts in iOS Settings")
}
}
}
}
func chooseAccount(_ accounts: [ACAccount]) {
if accounts.count == 1 {
self.performReverseAuth(accounts.first!)
return
}
let chooser = UIAlertController(title: "Twitter", message: "Choose Username", preferredStyle: UIAlertControllerStyle.actionSheet)
for account in accounts {
let choice = UIAlertAction(title: account.username, style: UIAlertActionStyle.default, handler: { (actionChoice) -> Void in
self.performReverseAuth(account)
})
chooser.addAction(choice)
}
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
chooser.addAction(cancel)
self.present(chooser, animated: true, completion: nil)
}
func performReverseAuth(_ twAccount: ACAccount) {
debugPrint("using twitter username:", twAccount.username)
activityIndicator.startAnimating()
if let account = self.account where account.username == twAccount.username {
debugPrint("same account")
} else {
let realm = try! Realm()
try! realm.write {
realm.deleteAllObjects()
}
}
self.account = twAccount
guard let storyboard = self.navigationController?.storyboard else {
return
}
let tweetVC = storyboard.instantiateViewController(withIdentifier: String(TweetViewController)) as! TweetViewController
tweetVC.account = twAccount
self.activityIndicator.stopAnimating()
self.navigationController?.show(tweetVC, sender: self)
}
func displayAlertWithMessage(_ message: String) {
let alert = UIAlertController(title: "Hey", message: message, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (alertAction) -> Void in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
|
mit
|
be3cadf69db097bfb6ce8e554909adc2
| 35.211538 | 137 | 0.621083 | 5.311707 | false | false | false | false |
leacode/LCYCoreDataHelper
|
LCYCoreDataHelper/LCYCoreDataHelper/NSFetchRequestExtension.swift
|
1
|
1558
|
//
// NSFetchRequesExtension.swift
// LCYCoreDataHelper
//
// Created by LiChunyu on 16/1/25.
// Copyright © 2016年 leacode. All rights reserved.
//
import UIKit
import CoreData
extension NSFetchRequest {
// public class func fetchRequestInContext(_ entityName: String, context: NSManagedObjectContext) -> NSFetchRequest {
// let request = NSFetchRequest()
// request.entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
// return request
// }
@objc
public func sort(_ key: String, ascending: Bool) {
let sortDescriptor = NSSortDescriptor(key: key, ascending: ascending)
guard let _ = self.sortDescriptors else {
self.sortDescriptors = [sortDescriptor]
return
}
self.sortDescriptors?.append(sortDescriptor)
}
@objc
public func sortByAttributes(_ attributes: [String], ascending: Bool) {
var sortDescriptors: [NSSortDescriptor] = []
for attributeName in attributes {
let sortDescriptor = NSSortDescriptor(key: attributeName, ascending: ascending)
sortDescriptors.append(sortDescriptor)
}
self.sortDescriptors = sortDescriptors
}
// public func fetchFirstObject(_ context: NSManagedObjectContext) -> AnyObject? {
// self.fetchLimit = 1
// do {
// let fetchedObject: AnyObject? = try context.fetch(self).first
// return fetchedObject
// } catch {
// return nil
// }
// }
}
|
mit
|
c0c71dd048fa53e785153a91398f4688
| 29.490196 | 120 | 0.631511 | 4.799383 | false | false | false | false |
AloneMonkey/RxSwiftStudy
|
RxSwiftTwoWayBinding/RxSwiftTwoWayBinding/ViewController.swift
|
1
|
1699
|
//
// ViewController.swift
// RxSwiftTwoWayBinding
//
// Created by monkey on 2017/3/30.
// Copyright © 2017年 Coder. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
extension UILabel {
public var rx_text: ControlProperty<String> {
// 观察text
let source: Observable<String> = self.rx.observe(String.self, "text").map { $0 ?? "" }
let setter: (UILabel, String) -> Void = { $0.text = $1 }
let bindingObserver = UIBindingObserver(UIElement: self, binding: setter)
return ControlProperty<String>(values: source, valueSink: bindingObserver)
}
}
class ViewController: UIViewController {
@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textview: UITextView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let text = Variable("双向绑定")
_ = textfield.rx.textInput <-> text
textfield.rx.text
.asObservable()
.subscribe{
print("textfield: \($0)")
}
.disposed(by: disposeBag)
textfield.text = "这是我修改的值"
label.rx_text
.asObservable()
.subscribe{
print("label:\($0)")
}
.disposed(by: disposeBag)
label.text = "修改label"
textview.rx.text
.asObservable()
.subscribe{
print("textview: \($0)")
}
.disposed(by: disposeBag)
textview.text = "这是我修改的值"
}
}
|
mit
|
f76fe3818eb3bcfda7ebfcfdcec182dc
| 24.8125 | 94 | 0.544189 | 4.550964 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.