repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
tanhuiya/ThPullRefresh | ThPullRefreshDemo/ExampleTableView.swift | 1 | 2816 | //
// ExampleTableView.swift
// PullRefresh
//
// Created by tanhui on 15/12/28.
// Copyright © 2015年 tanhui. All rights reserved.
//
import Foundation
import UIKit
class ExampleTableView: UITableViewController {
lazy var dataArr : NSMutableArray = {
return NSMutableArray()
}()
var index = 0
//MARK:Methods
func beginRefresh(){
self.tableView.headBeginRefresh()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "tableViewCell")
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44
self.tableView.tableFooterView = UIView()
self.tableView.addHeadRefresh(self) { () -> () in
self.loadNewData()
}
self.tableView.addHeadRefresh(self, action: "loadNewData")
self.tableView.head?.hideTimeLabel=true
// self.tableView.addFootRefresh(self, action: "loadMoreData")
self.tableView.addFootRefresh(self) { () -> () in
self.loadMoreData()
}
}
func loadNewData(){
//延时模拟刷新
self.index = 0
DeLayTime(2.0, closure: { () -> () in
self.dataArr.removeAllObjects()
for (var i = 0 ;i<5;i++){
let str = "最新5个cell,第\(self.index++)个"
self.dataArr.addObject(str)
}
self.tableView.reloadData()
self.tableView .tableHeadStopRefreshing()
})
}
func loadMoreData(){
//延时模拟刷新
DeLayTime(2.0, closure: { () -> () in
for (var i = 0 ;i<10;i++){
let str = "上拉刷新10个cell,第\(self.index++)个"
self.dataArr.addObject(str)
}
self.tableView.reloadData()
self.tableView .tableFootStopRefreshing()
})
}
}
extension ExampleTableView{
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row%2 == 0{
self.performSegueWithIdentifier("segue1", sender: nil)
}else{
self.navigationController?.pushViewController(ExampleController_two(), animated: true)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView .dequeueReusableCellWithIdentifier("tableViewCell", forIndexPath: indexPath)
cell.textLabel?.text=self.dataArr[indexPath.row] as? String
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArr.count
}
} | mit |
SwiftGen/SwiftGen | Sources/SwiftGenKit/Parsers/CoreData/Relationship.swift | 1 | 2982 | //
// SwiftGenKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
import Kanna
extension CoreData {
public struct Relationship {
public typealias InverseRelationship = (name: String, entityName: String)
public let name: String
public let isIndexed: Bool
public let isOptional: Bool
public var isTransient: Bool
public let isToMany: Bool
public let isOrdered: Bool
public let userInfo: [String: Any]
public let destinationEntity: String
public let inverseRelationship: InverseRelationship?
}
}
private enum XML {
fileprivate enum Attributes {
static let name = "name"
static let isIndexed = "indexed"
static let isOptional = "optional"
static let isTransient = "transient"
static let isToMany = "toMany"
static let isOrdered = "ordered"
static let destinationEntity = "destinationEntity"
static let inverseRelationshipName = "inverseName"
static let inverseRelationshipEntityName = "inverseEntity"
}
static let userInfoPath = "userInfo"
}
extension CoreData.Relationship {
init(with object: Kanna.XMLElement) throws {
guard let name = object[XML.Attributes.name] else {
throw CoreData.ParserError.invalidFormat(reason: "Missing required relationship name.")
}
guard let destinationEntity = object[XML.Attributes.destinationEntity] else {
throw CoreData.ParserError.invalidFormat(reason: "Missing required destination entity name")
}
let isIndexed = object[XML.Attributes.isIndexed].flatMap(Bool.init(from:)) ?? false
let isOptional = object[XML.Attributes.isOptional].flatMap(Bool.init(from:)) ?? false
let isTransient = object[XML.Attributes.isTransient].flatMap(Bool.init(from:)) ?? false
let isToMany = object[XML.Attributes.isToMany].flatMap(Bool.init(from:)) ?? false
let isOrdered = object[XML.Attributes.isOrdered].flatMap(Bool.init(from:)) ?? false
let inverseRelationshipName = object[XML.Attributes.inverseRelationshipName]
let inverseRelationshipEntityName = object[XML.Attributes.inverseRelationshipEntityName]
let inverseRelationship: InverseRelationship?
switch (inverseRelationshipName, inverseRelationshipEntityName) {
case (.none, .none):
inverseRelationship = nil
case (.none, _), (_, .none):
throw CoreData.ParserError.invalidFormat(
reason: "Both the name and entity name are required for inverse relationships"
)
case let (.some(name), .some(entityName)):
inverseRelationship = (name: name, entityName: entityName)
}
let userInfo = try object.at_xpath(XML.userInfoPath).map { try CoreData.UserInfo.parse(from: $0) } ?? [:]
self.init(
name: name,
isIndexed: isIndexed,
isOptional: isOptional,
isTransient: isTransient,
isToMany: isToMany,
isOrdered: isOrdered,
userInfo: userInfo,
destinationEntity: destinationEntity,
inverseRelationship: inverseRelationship
)
}
}
| mit |
shahmishal/swift | stdlib/public/core/ManagedBuffer.swift | 1 | 22112 | //===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
@usableFromInline
internal typealias _HeapObject = SwiftShims.HeapObject
@usableFromInline
@_silgen_name("swift_bufferAllocate")
internal func _swift_bufferAllocate(
bufferType type: AnyClass,
size: Int,
alignmentMask: Int
) -> AnyObject
/// A class whose instances contain a property of type `Header` and raw
/// storage for an array of `Element`, whose size is determined at
/// instance creation.
///
/// Note that the `Element` array is suitably-aligned **raw memory**.
/// You are expected to construct and---if necessary---destroy objects
/// there yourself, using the APIs on `UnsafeMutablePointer<Element>`.
/// Typical usage stores a count and capacity in `Header` and destroys
/// any live elements in the `deinit` of a subclass.
/// - Note: Subclasses must not have any stored properties; any storage
/// needed should be included in `Header`.
@_fixed_layout
open class ManagedBuffer<Header, Element> {
/// The stored `Header` instance.
///
/// During instance creation, in particular during
/// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s
/// `header` property is as-yet uninitialized, and therefore
/// reading the `header` property during `ManagedBuffer.create` is undefined.
public final var header: Header
// This is really unfortunate. In Swift 5.0, the method descriptor for this
// initializer was public and subclasses would "inherit" it, referencing its
// method descriptor from their class override table.
@usableFromInline
internal init(_doNotCallMe: ()) {
_internalInvariantFailure("Only initialize these by calling create")
}
}
extension ManagedBuffer {
/// Create a new instance of the most-derived class, calling
/// `factory` on the partially-constructed object to generate
/// an initial `Header`.
@inlinable
public final class func create(
minimumCapacity: Int,
makingHeaderWith factory: (
ManagedBuffer<Header, Element>) throws -> Header
) rethrows -> ManagedBuffer<Header, Element> {
let p = Builtin.allocWithTailElems_1(
self,
minimumCapacity._builtinWordValue, Element.self)
let initHeaderVal = try factory(p)
p.headerAddress.initialize(to: initHeaderVal)
// The _fixLifetime is not really needed, because p is used afterwards.
// But let's be conservative and fix the lifetime after we use the
// headerAddress.
_fixLifetime(p)
return p
}
/// The actual number of elements that can be stored in this object.
///
/// This header may be nontrivial to compute; it is usually a good
/// idea to store this information in the "header" area when
/// an instance is created.
@inlinable
public final var capacity: Int {
let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self))
let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr)
let realCapacity = endAddr.assumingMemoryBound(to: Element.self) -
firstElementAddress
return realCapacity
}
@inlinable
internal final var firstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(
Builtin.projectTailElems(self, Element.self))
}
@inlinable
internal final var headerAddress: UnsafeMutablePointer<Header> {
return UnsafeMutablePointer<Header>(Builtin.addressof(&header))
}
/// Call `body` with an `UnsafeMutablePointer` to the stored
/// `Header`.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@inlinable
public final func withUnsafeMutablePointerToHeader<R>(
_ body: (UnsafeMutablePointer<Header>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { (v, _) in return try body(v) }
}
/// Call `body` with an `UnsafeMutablePointer` to the `Element`
/// storage.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@inlinable
public final func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { return try body($1) }
}
/// Call `body` with `UnsafeMutablePointer`s to the stored `Header`
/// and raw `Element` storage.
///
/// - Note: These pointers are valid only for the duration of the
/// call to `body`.
@inlinable
public final func withUnsafeMutablePointers<R>(
_ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(headerAddress, firstElementAddress)
}
}
/// Contains a buffer object, and provides access to an instance of
/// `Header` and contiguous storage for an arbitrary number of
/// `Element` instances stored in that buffer.
///
/// For most purposes, the `ManagedBuffer` class works fine for this
/// purpose, and can simply be used on its own. However, in cases
/// where objects of various different classes must serve as storage,
/// `ManagedBufferPointer` is needed.
///
/// A valid buffer class is non-`@objc`, with no declared stored
/// properties. Its `deinit` must destroy its
/// stored `Header` and any constructed `Element`s.
///
/// Example Buffer Class
/// --------------------
///
/// class MyBuffer<Element> { // non-@objc
/// typealias Manager = ManagedBufferPointer<(Int, String), Element>
/// deinit {
/// Manager(unsafeBufferObject: self).withUnsafeMutablePointers {
/// (pointerToHeader, pointerToElements) -> Void in
/// pointerToElements.deinitialize(count: self.count)
/// pointerToHeader.deinitialize(count: 1)
/// }
/// }
///
/// // All properties are *computed* based on members of the Header
/// var count: Int {
/// return Manager(unsafeBufferObject: self).header.0
/// }
/// var name: String {
/// return Manager(unsafeBufferObject: self).header.1
/// }
/// }
///
@frozen
public struct ManagedBufferPointer<Header, Element> {
@usableFromInline
internal var _nativeBuffer: Builtin.NativeObject
/// Create with new storage containing an initial `Header` and space
/// for at least `minimumCapacity` `element`s.
///
/// - parameter bufferClass: The class of the object used for storage.
/// - parameter minimumCapacity: The minimum number of `Element`s that
/// must be able to be stored in the new buffer.
/// - parameter factory: A function that produces the initial
/// `Header` instance stored in the buffer, given the `buffer`
/// object and a function that can be called on it to get the actual
/// number of allocated elements.
///
/// - Precondition: `minimumCapacity >= 0`, and the type indicated by
/// `bufferClass` is a non-`@objc` class with no declared stored
/// properties. The `deinit` of `bufferClass` must destroy its
/// stored `Header` and any constructed `Element`s.
@inlinable
public init(
bufferClass: AnyClass,
minimumCapacity: Int,
makingHeaderWith factory:
(_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header
) rethrows {
self = ManagedBufferPointer(
bufferClass: bufferClass, minimumCapacity: minimumCapacity)
// initialize the header field
try withUnsafeMutablePointerToHeader {
$0.initialize(to:
try factory(
self.buffer,
{
ManagedBufferPointer(unsafeBufferObject: $0).capacity
}))
}
// FIXME: workaround for <rdar://problem/18619176>. If we don't
// access header somewhere, its addressor gets linked away
_ = header
}
/// Manage the given `buffer`.
///
/// - Precondition: `buffer` is an instance of a non-`@objc` class whose
/// `deinit` destroys its stored `Header` and any constructed `Element`s.
@inlinable
public init(unsafeBufferObject buffer: AnyObject) {
ManagedBufferPointer._checkValidBufferClass(type(of: buffer))
self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
//===--- internal/private API -------------------------------------------===//
/// Internal version for use by _ContiguousArrayBuffer where we know that we
/// have a valid buffer class.
/// This version of the init function gets called from
/// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get
/// specialized with current versions of the compiler, we can't get rid of the
/// _debugPreconditions in _checkValidBufferClass for any array. Since we know
/// for the _ContiguousArrayBuffer that this check must always succeed we omit
/// it in this specialized constructor.
@inlinable
internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) {
ManagedBufferPointer._internalInvariantValidBufferClass(type(of: buffer))
self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
/// Create with new storage containing space for an initial `Header`
/// and at least `minimumCapacity` `element`s.
///
/// - parameter bufferClass: The class of the object used for storage.
/// - parameter minimumCapacity: The minimum number of `Element`s that
/// must be able to be stored in the new buffer.
///
/// - Precondition: `minimumCapacity >= 0`, and the type indicated by
/// `bufferClass` is a non-`@objc` class with no declared stored
/// properties. The `deinit` of `bufferClass` must destroy its
/// stored `Header` and any constructed `Element`s.
@inlinable
internal init(
bufferClass: AnyClass,
minimumCapacity: Int
) {
ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true)
_precondition(
minimumCapacity >= 0,
"ManagedBufferPointer must have non-negative capacity")
self.init(
_uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity)
}
/// Internal version for use by _ContiguousArrayBuffer.init where we know that
/// we have a valid buffer class and that the capacity is >= 0.
@inlinable
internal init(
_uncheckedBufferClass: AnyClass,
minimumCapacity: Int
) {
ManagedBufferPointer._internalInvariantValidBufferClass(_uncheckedBufferClass, creating: true)
_internalInvariant(
minimumCapacity >= 0,
"ManagedBufferPointer must have non-negative capacity")
let totalSize = ManagedBufferPointer._elementOffset
+ minimumCapacity * MemoryLayout<Element>.stride
let newBuffer: AnyObject = _swift_bufferAllocate(
bufferType: _uncheckedBufferClass,
size: totalSize,
alignmentMask: ManagedBufferPointer._alignmentMask)
self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer)
}
/// Manage the given `buffer`.
///
/// - Note: It is an error to use the `header` property of the resulting
/// instance unless it has been initialized.
@inlinable
internal init(_ buffer: ManagedBuffer<Header, Element>) {
_nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)
}
}
extension ManagedBufferPointer {
/// The stored `Header` instance.
@inlinable
public var header: Header {
_read {
yield _headerPointer.pointee
}
_modify {
yield &_headerPointer.pointee
}
}
/// Returns the object instance being used for storage.
@inlinable
public var buffer: AnyObject {
return Builtin.castFromNativeObject(_nativeBuffer)
}
/// The actual number of elements that can be stored in this object.
///
/// This value may be nontrivial to compute; it is usually a good
/// idea to store this information in the "header" area when
/// an instance is created.
@inlinable
public var capacity: Int {
return (
_capacityInBytes &- ManagedBufferPointer._elementOffset
) / MemoryLayout<Element>.stride
}
/// Call `body` with an `UnsafeMutablePointer` to the stored
/// `Header`.
///
/// - Note: This pointer is valid only
/// for the duration of the call to `body`.
@inlinable
public func withUnsafeMutablePointerToHeader<R>(
_ body: (UnsafeMutablePointer<Header>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { (v, _) in return try body(v) }
}
/// Call `body` with an `UnsafeMutablePointer` to the `Element`
/// storage.
///
/// - Note: This pointer is valid only for the duration of the
/// call to `body`.
@inlinable
public func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
return try withUnsafeMutablePointers { return try body($1) }
}
/// Call `body` with `UnsafeMutablePointer`s to the stored `Header`
/// and raw `Element` storage.
///
/// - Note: These pointers are valid only for the duration of the
/// call to `body`.
@inlinable
public func withUnsafeMutablePointers<R>(
_ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(_nativeBuffer) }
return try body(_headerPointer, _elementPointer)
}
/// Returns `true` iff `self` holds the only strong reference to its buffer.
///
/// See `isUniquelyReferenced` for details.
@inlinable
public mutating func isUniqueReference() -> Bool {
return _isUnique(&_nativeBuffer)
}
}
extension ManagedBufferPointer {
@inlinable
internal static func _checkValidBufferClass(
_ bufferClass: AnyClass, creating: Bool = false
) {
_debugPrecondition(
_class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size
|| (
(!creating || bufferClass is ManagedBuffer<Header, Element>.Type)
&& _class_getInstancePositiveExtentSize(bufferClass)
== _headerOffset + MemoryLayout<Header>.size),
"ManagedBufferPointer buffer class has illegal stored properties"
)
_debugPrecondition(
_usesNativeSwiftReferenceCounting(bufferClass),
"ManagedBufferPointer buffer class must be non-@objc"
)
}
@inlinable
internal static func _internalInvariantValidBufferClass(
_ bufferClass: AnyClass, creating: Bool = false
) {
_internalInvariant(
_class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size
|| (
(!creating || bufferClass is ManagedBuffer<Header, Element>.Type)
&& _class_getInstancePositiveExtentSize(bufferClass)
== _headerOffset + MemoryLayout<Header>.size),
"ManagedBufferPointer buffer class has illegal stored properties"
)
_internalInvariant(
_usesNativeSwiftReferenceCounting(bufferClass),
"ManagedBufferPointer buffer class must be non-@objc"
)
}
}
extension ManagedBufferPointer {
/// The required alignment for allocations of this type, minus 1
@inlinable
internal static var _alignmentMask: Int {
return max(
MemoryLayout<_HeapObject>.alignment,
max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1
}
/// The actual number of bytes allocated for this object.
@inlinable
internal var _capacityInBytes: Int {
return _swift_stdlib_malloc_size(_address)
}
/// The address of this instance in a convenient pointer-to-bytes form
@inlinable
internal var _address: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer))
}
/// Offset from the allocated storage for `self` to the stored `Header`
@inlinable
internal static var _headerOffset: Int {
_onFastPath()
return _roundUp(
MemoryLayout<_HeapObject>.size,
toAlignment: MemoryLayout<Header>.alignment)
}
/// An **unmanaged** pointer to the storage for the `Header`
/// instance. Not safe to use without _fixLifetime calls to
/// guarantee it doesn't dangle
@inlinable
internal var _headerPointer: UnsafeMutablePointer<Header> {
_onFastPath()
return (_address + ManagedBufferPointer._headerOffset).assumingMemoryBound(
to: Header.self)
}
/// An **unmanaged** pointer to the storage for `Element`s. Not
/// safe to use without _fixLifetime calls to guarantee it doesn't
/// dangle.
@inlinable
internal var _elementPointer: UnsafeMutablePointer<Element> {
_onFastPath()
return (_address + ManagedBufferPointer._elementOffset).assumingMemoryBound(
to: Element.self)
}
/// Offset from the allocated storage for `self` to the `Element` storage
@inlinable
internal static var _elementOffset: Int {
_onFastPath()
return _roundUp(
_headerOffset + MemoryLayout<Header>.size,
toAlignment: MemoryLayout<Element>.alignment)
}
}
extension ManagedBufferPointer: Equatable {
@inlinable
public static func == (
lhs: ManagedBufferPointer,
rhs: ManagedBufferPointer
) -> Bool {
return lhs._address == rhs._address
}
}
// FIXME: when our calling convention changes to pass self at +0,
// inout should be dropped from the arguments to these functions.
// FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too,
// but currently does not. rdar://problem/29341361
/// Returns a Boolean value indicating whether the given object is known to
/// have a single strong reference.
///
/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the
/// copy-on-write optimization for the deep storage of value types:
///
/// mutating func update(withValue value: T) {
/// if !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// Use care when calling `isKnownUniquelyReferenced(_:)` from within a Boolean
/// expression. In debug builds, an instance in the left-hand side of a `&&`
/// or `||` expression may still be referenced when evaluating the right-hand
/// side, inflating the instance's reference count. For example, this version
/// of the `update(withValue)` method will re-copy `myStorage` on every call:
///
/// // Copies too frequently:
/// mutating func badUpdate(withValue value: T) {
/// if myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// To avoid this behavior, swap the call `isKnownUniquelyReferenced(_:)` to
/// the left-hand side or store the result of the first expression in a local
/// constant:
///
/// mutating func goodUpdate(withValue value: T) {
/// let shouldCopy = myStorage.shouldCopy
/// if shouldCopy || !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the
/// given object---if `object` has additional weak or unowned references, the
/// result may still be `true`. Because weak and unowned references cannot be
/// the only reference to an object, passing a weak or unowned reference as
/// `object` always results in `false`.
///
/// If the instance passed as `object` is being accessed by multiple threads
/// simultaneously, this function may still return `true`. Therefore, you must
/// only call this function from mutating methods with appropriate thread
/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`
/// only returns `true` when there is really one accessor, or when there is a
/// race condition, which is already undefined behavior.
///
/// - Parameter object: An instance of a class. This function does *not* modify
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`.
@inlinable
public func isKnownUniquelyReferenced<T: AnyObject>(_ object: inout T) -> Bool
{
return _isUnique(&object)
}
/// Returns a Boolean value indicating whether the given object is known to
/// have a single strong reference.
///
/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the
/// copy-on-write optimization for the deep storage of value types:
///
/// mutating func update(withValue value: T) {
/// if !isKnownUniquelyReferenced(&myStorage) {
/// myStorage = self.copiedStorage()
/// }
/// myStorage.update(withValue: value)
/// }
///
/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the
/// given object---if `object` has additional weak or unowned references, the
/// result may still be `true`. Because weak and unowned references cannot be
/// the only reference to an object, passing a weak or unowned reference as
/// `object` always results in `false`.
///
/// If the instance passed as `object` is being accessed by multiple threads
/// simultaneously, this function may still return `true`. Therefore, you must
/// only call this function from mutating methods with appropriate thread
/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`
/// only returns `true` when there is really one accessor, or when there is a
/// race condition, which is already undefined behavior.
///
/// - Parameter object: An instance of a class. This function does *not* modify
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`. If `object` is `nil`, the return value is `false`.
@inlinable
public func isKnownUniquelyReferenced<T: AnyObject>(
_ object: inout T?
) -> Bool {
return _isUnique(&object)
}
| apache-2.0 |
roambotics/swift | stdlib/public/core/LifetimeManager.swift | 4 | 9710 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended. If `body` has a return value, that value is also used as the
/// return value for the `withExtendedLifetime(_:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended. If `body` has a return value, that value is also used as the
/// return value for the `withExtendedLifetime(_:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Calls the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafeMutablePointer(to:_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameters:
/// - value: An instance to temporarily use via pointer. Note that the `inout`
/// exclusivity rules mean that, like any other `inout` argument, `value`
/// cannot be directly accessed by other code for the duration of `body`.
/// Access must only occur through the pointer argument to `body` until
/// `body` returns.
/// - body: A closure that takes a mutable pointer to `value` as its sole
/// argument. If the closure has a return value, that value is also used
/// as the return value of the `withUnsafeMutablePointer(to:_:)` function.
/// The pointer argument is valid only for the duration of the function's
/// execution.
/// - Returns: The return value, if any, of the `body` closure.
@inlinable
public func withUnsafeMutablePointer<T, Result>(
to value: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&value)))
}
/// Calls the given closure with a mutable pointer to the given argument.
///
/// This function is similar to `withUnsafeMutablePointer`, except that it
/// doesn't trigger stack protection for the pointer.
@_alwaysEmitIntoClient
public func _withUnprotectedUnsafeMutablePointer<T, Result>(
to value: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
#if $BuiltinUnprotectedAddressOf
return try body(UnsafeMutablePointer<T>(Builtin.unprotectedAddressOf(&value)))
#else
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&value)))
#endif
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in parameters by const pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later
/// use.
///
/// - Parameters:
/// - value: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `value` as its sole argument. If
/// the closure has a return value, that value is also used as the return
/// value of the `withUnsafePointer(to:_:)` function. The pointer argument
/// is valid only for the duration of the function's execution.
/// It is undefined behavior to try to mutate through the pointer argument
/// by converting it to `UnsafeMutablePointer` or any other mutable pointer
/// type. If you need to mutate the argument through the pointer, use
/// `withUnsafeMutablePointer(to:_:)` instead.
/// - Returns: The return value, if any, of the `body` closure.
@inlinable
public func withUnsafePointer<T, Result>(
to value: T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressOfBorrow(value)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in parameters by const pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later
/// use.
///
/// - Parameters:
/// - value: An instance to temporarily use via pointer. Note that the `inout`
/// exclusivity rules mean that, like any other `inout` argument, `value`
/// cannot be directly accessed by other code for the duration of `body`.
/// Access must only occur through the pointer argument to `body` until
/// `body` returns.
/// - body: A closure that takes a pointer to `value` as its sole argument. If
/// the closure has a return value, that value is also used as the return
/// value of the `withUnsafePointer(to:_:)` function. The pointer argument
/// is valid only for the duration of the function's execution.
/// It is undefined behavior to try to mutate through the pointer argument
/// by converting it to `UnsafeMutablePointer` or any other mutable pointer
/// type. If you need to mutate the argument through the pointer, use
/// `withUnsafeMutablePointer(to:_:)` instead.
/// - Returns: The return value, if any, of the `body` closure.
@inlinable
public func withUnsafePointer<T, Result>(
to value: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&value)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// This function is similar to `withUnsafePointer`, except that it
/// doesn't trigger stack protection for the pointer.
@_alwaysEmitIntoClient
public func _withUnprotectedUnsafePointer<T, Result>(
to value: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
#if $BuiltinUnprotectedAddressOf
return try body(UnsafePointer<T>(Builtin.unprotectedAddressOf(&value)))
#else
return try body(UnsafePointer<T>(Builtin.addressof(&value)))
#endif
}
extension String {
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of UTF-8 code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameter body: A closure with a pointer parameter that points to a
/// null-terminated sequence of UTF-8 code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(_:)` method. The pointer argument is valid only for the
/// duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // fast-path: already C-string compatible
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try _guts.withCString(body)
}
}
/// Takes in a value at +0 and performs a Builtin.copy upon it.
///
/// IMPLEMENTATION NOTES: During transparent inlining, Builtin.copy becomes the
/// explicit_copy_value instruction if we are inlining into a context where the
/// specialized type is loadable. If the transparent function is called in a
/// context where the inlined function specializes such that the specialized
/// type is still not loadable, the compiler aborts (a). Once we have opaque
/// values, this restriction will be lifted since after that address only types
/// at SILGen time will be loadable objects.
///
/// (a). This is implemented by requiring that Builtin.copy only be called
/// within a function marked with the semantic tag "lifetimemanagement.copy"
/// which conveniently is only the function we are defining here: _copy.
///
/// NOTE: We mark this _alwaysEmitIntoClient to ensure that we are not creating
/// new ABI that the stdlib must maintain if a user calls this ignoring the '_'
/// implying it is stdlib SPI.
@_alwaysEmitIntoClient
@inlinable
@_transparent
@_semantics("lifetimemanagement.copy")
public func _copy<T>(_ value: T) -> T {
#if $BuiltinCopy
Builtin.copy(value)
#else
value
#endif
}
| apache-2.0 |
bkmunar/firefox-ios | Client/Frontend/Reader/ReaderModeHandlers.swift | 1 | 4120 | /* 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
struct ReaderModeHandlers {
static func register(webServer: WebServer, profile: Profile) {
// Register our fonts, which we want to expose to web content that we present in the WebView
webServer.registerMainBundleResourcesOfType("ttf", module: "reader-mode/fonts")
// Register a handler that simply lets us know if a document is in the cache or not. This is called from the
// reader view interstitial page to find out when it can stop showing the 'Loading...' page and instead load
// the readerized content.
webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page-exists") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in
if let url = request.query["url"] as? String {
if let url = NSURL(string: url) {
if ReaderModeCache.sharedInstance.contains(url, error: nil) {
return GCDWebServerResponse(statusCode: 200)
} else {
return GCDWebServerResponse(statusCode: 404)
}
}
}
return GCDWebServerResponse(statusCode: 500)
}
// Register the handler that accepts /reader-mode/page?url=http://www.example.com requests.
webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in
if let url = request.query["url"] as? String {
if let url = NSURL(string: url) {
if let readabilityResult = ReaderModeCache.sharedInstance.get(url, error: nil) {
// We have this page in our cache, so we can display it. Just grab the correct style from the
// profile and then generate HTML from the Readability results.
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict) {
readerModeStyle = style
}
}
if let html = ReaderModeUtils.generateReaderContent(readabilityResult, initialStyle: readerModeStyle) {
return GCDWebServerDataResponse(HTML: html)
}
} else {
// This page has not been converted to reader mode yet. This happens when you for example add an
// item via the app extension and the application has not yet had a change to readerize that
// page in the background.
//
// What we do is simply queue the page in the ReadabilityService and then show our loading
// screen, which will periodically call page-exists to see if the readerized content has
// become available.
ReadabilityService.sharedInstance.process(url)
if let readerViewLoadingPath = NSBundle.mainBundle().pathForResource("ReaderViewLoading", ofType: "html") {
if let readerViewLoading = NSMutableString(contentsOfFile: readerViewLoadingPath, encoding: NSUTF8StringEncoding, error: nil) {
return GCDWebServerDataResponse(HTML: readerViewLoading as String)
}
}
}
}
}
let errorString = NSLocalizedString("There was an error converting the page", comment: "Error displayed when reader mode cannot be enabled")
return GCDWebServerDataResponse(HTML: errorString) // TODO Needs a proper error page
}
}
} | mpl-2.0 |
practicalswift/swift | validation-test/compiler_crashers_2_fixed/0172-rdar-44235762.swift | 36 | 360 | // RUN: not %target-swift-frontend -typecheck %s
// Was crashing in associated type inference.
protocol P {
associatedtype Assoc
subscript(i: Int) -> Assoc { get }
func f() -> Assoc
}
struct X<T, U> { }
extension P {
subscript<T>(i: T) -> X<T, Self> { return X<T, Self>() }
func f<T>() -> X<T, Self> { return X<T, Self> }
}
struct Y<T>: P { }
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/EthereumKitMock/EthereumKeyPairDeriverMock.swift | 1 | 509 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import EthereumKit
import PlatformKit
import RxSwift
class EthereumKeyPairDeriverMock: KeyPairDeriverAPI {
var deriveResult: Result<EthereumKeyPair, HDWalletError> = .success(
MockEthereumWalletTestData.keyPair
)
var lastMnemonic: String?
func derive(input: EthereumKeyDerivationInput) -> Result<EthereumKeyPair, HDWalletError> {
lastMnemonic = input.mnemonic
return deriveResult
}
}
| lgpl-3.0 |
wess/overlook | Sources/json/json.swift | 1 | 3532 | //
// JSON.swift
// JSON
//
// Created by Sam Soffes on 9/22/16.
// Copyright © 2016 Sam Soffes. All rights reserved.
//
import Foundation
/// JSON dictionary type alias.
///
/// Strings must be keys.
public typealias JSONDictionary = [String: Any]
/// Protocol for things that can be deserialized with JSON.
public protocol JSONDeserializable {
/// Initialize with a JSON representation
///
/// - parameter jsonRepresentation: JSON representation
/// - throws: JSONError
init(jsonRepresentation: JSONDictionary) throws
}
public protocol JSONSerializable {
/// JSON representation
var jsonRepresentation: JSONDictionary { get }
}
/// Errors for deserializing JSON representations
public enum JSONDeserializationError: Error {
/// A required attribute was missing
case missingAttribute(key: String)
/// An invalid type for an attribute was found
case invalidAttributeType(key: String, expectedType: Any.Type, receivedValue: Any)
/// An attribute was invalid
case invalidAttribute(key: String)
}
/// Generically decode an value from a given JSON dictionary.
///
/// - parameter dictionary: a JSON dictionary
/// - parameter key: key in the dictionary
/// - returns: The expected value
/// - throws: JSONDeserializationError
public func decode<T>(_ dictionary: JSONDictionary, key: String) throws -> T {
guard let value = dictionary[key] else {
throw JSONDeserializationError.missingAttribute(key: key)
}
guard let attribute = value as? T else {
throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: T.self, receivedValue: value)
}
return attribute
}
/// Decode a date value from a given JSON dictionary. ISO8601 or Unix timestamps are supported.
///
/// - parameter dictionary: a JSON dictionary
/// - parameter key: key in the dictionary
/// - returns: The expected value
/// - throws: JSONDeserializationError
public func decode(_ dictionary: JSONDictionary, key: String) throws -> Date {
guard let value = dictionary[key] else {
throw JSONDeserializationError.missingAttribute(key: key)
}
if let string = value as? String {
guard let date = ISO8601DateFormatter().date(from: string) else {
throw JSONDeserializationError.invalidAttribute(key: key)
}
return date
}
if let timeInterval = value as? TimeInterval {
return Date(timeIntervalSince1970: timeInterval)
}
if let timeInterval = value as? Int {
return Date(timeIntervalSince1970: TimeInterval(timeInterval))
}
throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: String.self, receivedValue: value)
}
/// Decode a JSONDeserializable type from a given JSON dictionary.
///
/// - parameter dictionary: a JSON dictionary
/// - parameter key: key in the dictionary
/// - returns: The expected JSONDeserializable value
/// - throws: JSONDeserializationError
public func decode<T: JSONDeserializable>(_ dictionary: JSONDictionary, key: String) throws -> T {
let value: JSONDictionary = try decode(dictionary, key: key)
return try decode(value)
}
/// Decode a JSONDeserializable type
///
/// - parameter dictionary: a JSON dictionary
/// - returns: the decoded type
/// - throws: JSONDeserializationError
public func decode<T: JSONDeserializable>(_ dictionary: JSONDictionary) throws -> T {
return try T.init(jsonRepresentation: dictionary)
}
func ISO8601DateFormatter() -> DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}
| mit |
zhangxigithub/GIF | GIF/AppDelegate.swift | 1 | 1869 | //
// AppDelegate.swift
// GIF
//
// Created by zhangxi on 7/1/16.
// Copyright © 2016 zhangxi.me. All rights reserved.
//
import Cocoa
let thumbPath = NSHomeDirectory().stringByAppendingString("/Documents/thumb")
let folderPath = NSHomeDirectory().stringByAppendingString("/Documents/gif")
//let palettePath = NSHomeDirectory().stringByAppendingString("/Documents/palette.png")
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
let fm = NSFileManager.defaultManager()
do{
try fm.createDirectoryAtPath(folderPath, withIntermediateDirectories: true, attributes: nil)
try fm.createDirectoryAtPath(thumbPath, withIntermediateDirectories: true, attributes: nil)
}catch
{
}
/*
NSFileManager *fm = [NSFileManager defaultManager];
NSString *appGroupName = @"Z123456789.com.example.app-group"; /* For example */
NSURL *groupContainerURL = [fm containerURLForSecurityApplicationGroupIdentifier:appGroupName];
NSError* theError = nil;
if (![fm createDirectoryAtURL: groupContainerURL withIntermediateDirectories:YES attributes:nil error:&theError]) {
// Handle the error.
}
*/
}
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if flag == false{
for window in sender.windows{
window.makeKeyAndOrderFront(self)
}
}
return true
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| apache-2.0 |
huonw/swift | validation-test/compiler_crashers_fixed/00402-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 65 | 454 | // 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
// RUN: not %target-swift-frontend %s -typecheck
class d<T, f: d where T: P {
let t: NSObject {
var e: T
| apache-2.0 |
alex-d-fox/iDoubtIt | iDoubtIt/Code/Card.swift | 1 | 4837 | //
// Card.swift
// iDoubtIt
//
// Created by Alexander Fox on 8/30/16.
// Copyright © 2016
//
import Foundation
import SpriteKit
enum Suit :String {
case Hearts,
Spades,
Clubs,
Diamonds,
NoSuit
static let allValues = [ Hearts,
Spades,
Clubs,
Diamonds,
NoSuit ]
}
enum Value :Int {
case Ace,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Joker
static let allValues = [ Ace,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Joker ]
}
enum cardBack :String {
case cardBack_blue1,
cardBack_blue2,
cardBack_blue3,
cardBack_blue4,
cardBack_blue5,
cardBack_green1,
cardBack_green2,
cardBack_green3,
cardBack_green4,
cardBack_green5,
cardBack_red1,
cardBack_red2,
cardBack_red3,
cardBack_red4,
cardBack_red5
static let allValues = [cardBack_blue1,
cardBack_blue2,
cardBack_blue3,
cardBack_blue4,
cardBack_blue5,
cardBack_green1,
cardBack_green2,
cardBack_green3,
cardBack_green4,
cardBack_green5,
cardBack_red1,
cardBack_red2,
cardBack_red3,
cardBack_red4,
cardBack_red5]
}
class Card : SKSpriteNode {
let suit :Suit
let frontTexture :SKTexture
let backTexture :SKTexture
let value :Value
var cardName :String
var facedUp :Bool
var curTexture :SKTexture
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
init(suit: Suit, value: Value, faceUp: Bool) {
self.suit = suit
self.value = value
if (value != .Joker || suit != .NoSuit) {
cardName = "\(value)of\(suit)"
}
else {
cardName = String(format: "Joker")
}
backTexture = SKTexture(imageNamed: cardCover)
frontTexture = SKTexture(imageNamed: cardName)
facedUp = faceUp
if facedUp {
curTexture = frontTexture
} else {
curTexture = backTexture
}
super.init(texture: curTexture, color: .clear, size: curTexture.size())
name = cardName
}
func flipOver() {
if facedUp {
texture = frontTexture
} else {
texture = backTexture
}
facedUp = !facedUp
}
func getIcon() -> String {
let Cards = ["Ace": ["Hearts": "🂱", "Spades": "🂡", "Clubs": "🃑", "Diamonds": "🃁", "NoSuit": "❗️"],
"Two": ["Hearts": "🂲", "Spades": "🂢", "Clubs": "🃒", "Diamonds": "🃂", "NoSuit": "❗️"],
"Three": ["Hearts": "🂳", "Spades": "🂣", "Clubs": "🃓", "Diamonds": "🃃", "NoSuit": "❗️"],
"Four": ["Hearts": "🂴", "Spades": "🂤", "Clubs": "🃔", "Diamonds": "🃄", "NoSuit": "❗️"],
"Five": ["Hearts": "🂵", "Spades": "🂥", "Clubs": "🃕", "Diamonds": "🃅", "NoSuit": "❗️"],
"Six": ["Hearts": "🂶", "Spades": "🂦", "Clubs": "🃖", "Diamonds": "🃆", "NoSuit": "❗️"],
"Seven": ["Hearts": "🂷", "Spades": "🂧", "Clubs": "🃗", "Diamonds": "🃇", "NoSuit": "❗️"],
"Eight": ["Hearts": "🂸", "Spades": "🂨", "Clubs": "🃘", "Diamonds": "🃈", "NoSuit": "❗️"],
"Nine": ["Hearts": "🂹", "Spades": "🂩", "Clubs": "🃙", "Diamonds": "🃉", "NoSuit": "❗️"],
"Ten": ["Hearts": "🂺", "Spades": "🂪", "Clubs": "🃚", "Diamonds": "🃊", "NoSuit": "❗️"],
"Jack": ["Hearts": "🂻", "Spades": "🂫", "Clubs": "🃛", "Diamonds": "🃋", "NoSuit": "❗️"],
"Queen": ["Hearts": "🂽", "Spades": "🂭", "Clubs": "🃝", "Diamonds": "🃍", "NoSuit": "❗️"],
"King": ["Hearts": "🂾", "Spades": "🂮", "Clubs": "🃞", "Diamonds": "🃎", "NoSuit": "❗️"],
"Joker": ["Hearts": "🃟", "Spades": "🃟", "Clubs": "🃟", "Diamonds": "🃟", "NoSuit": "❗️"]]
let icon = Cards["\(value)"]?["\(suit)"]
return icon!
}
}
| gpl-3.0 |
KaneCheshire/ShowTime | Example/Pods/PixelTest/PixelTest/Protocols/LayoutCoordinatorType.swift | 1 | 227 | //
// LayoutCoordinatorType.swift
// PixelTest
//
// Created by Kane Cheshire on 25/04/2018.
//
import Foundation
protocol LayoutCoordinatorType {
func layOut(_ view: UIView, with layoutStyle: LayoutStyle)
}
| mit |
adamcin/SwiftCJ | SwiftCJ/CJDataElem.swift | 1 | 1224 | import Foundation
public struct CJDataElem {
public let name: String
public let prompt: String?
public let value: AnyObject?
func copyAndSet(value: AnyObject?) -> CJDataElem {
if value == nil {
return CJDataElem(name: name, prompt: prompt, value: nil)
} else if NSJSONSerialization.isValidJSONObject(value!) {
return CJDataElem(name: name, prompt: prompt, value: value!)
} else {
return CJDataElem(name: name, prompt: prompt, value: "\(value!)")
}
}
func toSeri() -> [String: AnyObject] {
var seri = [String: AnyObject]()
seri["name"] = self.name
if let prompt = self.prompt {
seri["prompt"] = self.prompt
}
if let value: AnyObject = self.value {
seri["value"] = self.value
}
return seri
}
static func elementFromDictionary(dict: [NSObject: AnyObject]) -> CJDataElem? {
if let name = dict["name"] as? String {
let prompt = dict["prompt"] as? String
let value: AnyObject? = dict["value"]
return CJDataElem(name: name, prompt: prompt, value: value)
}
return nil
}
}
| mit |
googlearchive/science-journal-ios | ScienceJournal/UI/AppFlowViewController.swift | 1 | 23261 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs
/// The primary view controller for Science Journal which owns the navigation controller and manages
/// all other flows and view controllers.
class AppFlowViewController: UIViewController {
/// The account user manager for the current account. Exposed for testing. If the current
/// account's ID matches the existing accountUserManager account ID, this returns the existing
/// manager. If not, a new manager is created for the current account and returned.
var currentAccountUserManager: AccountUserManager? {
guard let account = accountsManager.currentAccount else { return nil }
if _currentAccountUserManager == nil || _currentAccountUserManager!.account.ID != account.ID {
_currentAccountUserManager = AccountUserManager(fileSystemLayout: fileSystemLayout,
account: account,
driveConstructor: driveConstructor,
networkAvailability: networkAvailability,
sensorController: sensorController,
analyticsReporter: analyticsReporter)
}
return _currentAccountUserManager
}
private var _currentAccountUserManager: AccountUserManager?
/// The device preference manager. Exposed for testing.
let devicePreferenceManager = DevicePreferenceManager()
/// The root user manager. Exposed for testing.
let rootUserManager: RootUserManager
/// The accounts manager. Exposed so the AppDelegate can ask for reauthentication and related
/// tasks, as well as testing.
let accountsManager: AccountsManager
private let analyticsReporter: AnalyticsReporter
private let commonUIComponents: CommonUIComponents
private let drawerConfig: DrawerConfig
private let driveConstructor: DriveConstructor
private var existingDataMigrationManager: ExistingDataMigrationManager?
private var existingDataOptionsVC: ExistingDataOptionsViewController?
private let feedbackReporter: FeedbackReporter
private let fileSystemLayout: FileSystemLayout
private let networkAvailability: NetworkAvailability
private let queue = GSJOperationQueue()
private let sensorController: SensorController
private var shouldShowPreferenceMigrationMessage = false
/// The current user flow view controller, if it exists.
private weak var userFlowViewController: UserFlowViewController?
#if FEATURE_FIREBASE_RC
private var remoteConfigManager: RemoteConfigManager?
/// Convenience initializer.
///
/// - Parameters:
/// - fileSystemLayout: The file system layout.
/// - accountsManager: The accounts manager.
/// - analyticsReporter: The analytics reporter.
/// - commonUIComponents: Common UI components.
/// - drawerConfig: The drawer config.
/// - driveConstructor: The drive constructor.
/// - feedbackReporter: The feedback reporter.
/// - networkAvailability: Network availability.
/// - remoteConfigManager: The remote config manager.
/// - sensorController: The sensor controller.
convenience init(fileSystemLayout: FileSystemLayout,
accountsManager: AccountsManager,
analyticsReporter: AnalyticsReporter,
commonUIComponents: CommonUIComponents,
drawerConfig: DrawerConfig,
driveConstructor: DriveConstructor,
feedbackReporter: FeedbackReporter,
networkAvailability: NetworkAvailability,
remoteConfigManager: RemoteConfigManager,
sensorController: SensorController) {
self.init(fileSystemLayout: fileSystemLayout,
accountsManager: accountsManager,
analyticsReporter: analyticsReporter,
commonUIComponents: commonUIComponents,
drawerConfig: drawerConfig,
driveConstructor: driveConstructor,
feedbackReporter: feedbackReporter,
networkAvailability: networkAvailability,
sensorController: sensorController)
self.remoteConfigManager = remoteConfigManager
}
#endif
/// Designated initializer.
///
/// - Parameters:
/// - fileSystemLayout: The file system layout.
/// - accountsManager: The accounts manager.
/// - analyticsReporter: The analytics reporter.
/// - commonUIComponents: Common UI components.
/// - drawerConfig: The drawer config.
/// - driveConstructor: The drive constructor.
/// - feedbackReporter: The feedback reporter.
/// - networkAvailability: Network availability.
/// - sensorController: The sensor controller.
init(fileSystemLayout: FileSystemLayout,
accountsManager: AccountsManager,
analyticsReporter: AnalyticsReporter,
commonUIComponents: CommonUIComponents,
drawerConfig: DrawerConfig,
driveConstructor: DriveConstructor,
feedbackReporter: FeedbackReporter,
networkAvailability: NetworkAvailability,
sensorController: SensorController) {
self.fileSystemLayout = fileSystemLayout
self.accountsManager = accountsManager
self.analyticsReporter = analyticsReporter
self.commonUIComponents = commonUIComponents
self.drawerConfig = drawerConfig
self.driveConstructor = driveConstructor
self.feedbackReporter = feedbackReporter
self.networkAvailability = networkAvailability
self.sensorController = sensorController
rootUserManager = RootUserManager(
fileSystemLayout: fileSystemLayout,
sensorController: sensorController
)
super.init(nibName: nil, bundle: nil)
// Register as the delegate for AccountsManager.
self.accountsManager.delegate = self
// If a user should be forced to sign in from outside the sign in flow (e.g. their account was
// invalid on foreground or they deleted an account), this notification will be fired.
NotificationCenter.default.addObserver(self,
selector: #selector(forceSignInViaNotification),
name: .userWillBeSignedOut,
object: nil)
#if SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD
// If we should create root user data to test the claim flow, this notification will be fired.
NotificationCenter.default.addObserver(self,
selector: #selector(debug_createRootUserData),
name: .DEBUG_createRootUserData,
object: nil)
// If we should create root user data and force auth to test the migration flow, this
// notification will be fired.
NotificationCenter.default.addObserver(self,
selector: #selector(debug_forceAuth),
name: .DEBUG_forceAuth,
object: nil)
#endif // SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
func accountsSupported() {
accountsManager.signInAsCurrentAccount()
}
func accountsNotSupported() {
showNonAccountUser(animated: false)
}
if accountsManager.supportsAccounts {
accountsSupported()
} else {
accountsNotSupported()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return children.last?.preferredStatusBarStyle ?? .lightContent
}
private func showCurrentUserOrSignIn() {
guard let accountUserManager = currentAccountUserManager else {
print("[AppFlowViewController] No current account user manager, must sign in.")
showSignIn()
return
}
let existingDataMigrationManager =
ExistingDataMigrationManager(accountUserManager: accountUserManager,
rootUserManager: rootUserManager)
let accountUserFlow = UserFlowViewController(
accountsManager: accountsManager,
analyticsReporter: analyticsReporter,
commonUIComponents: commonUIComponents,
devicePreferenceManager: devicePreferenceManager,
drawerConfig: drawerConfig,
existingDataMigrationManager: existingDataMigrationManager,
feedbackReporter: feedbackReporter,
networkAvailability: networkAvailability,
sensorController: sensorController,
shouldShowPreferenceMigrationMessage: shouldShowPreferenceMigrationMessage,
userManager: accountUserManager)
accountUserFlow.delegate = self
userFlowViewController = accountUserFlow
transitionToViewControllerModally(accountUserFlow)
// Set to false now so we don't accidently cache true and show it again when we don't want to.
shouldShowPreferenceMigrationMessage = false
}
private func showNonAccountUser(animated: Bool) {
let userFlow = UserFlowViewController(accountsManager: accountsManager,
analyticsReporter: analyticsReporter,
commonUIComponents: commonUIComponents,
devicePreferenceManager: devicePreferenceManager,
drawerConfig: drawerConfig,
existingDataMigrationManager: nil,
feedbackReporter: feedbackReporter,
networkAvailability: networkAvailability,
sensorController: sensorController,
shouldShowPreferenceMigrationMessage: false,
userManager: rootUserManager)
userFlow.delegate = self
userFlowViewController = userFlow
transitionToViewControllerModally(userFlow, animated: animated)
}
// Transitions to the sign in flow with an optional completion block to fire when the flow
// has been shown.
private func showSignIn(completion: (() -> Void)? = nil) {
let signInFlow = SignInFlowViewController(accountsManager: accountsManager,
analyticsReporter: analyticsReporter,
rootUserManager: rootUserManager,
sensorController: sensorController)
signInFlow.delegate = self
transitionToViewControllerModally(signInFlow, completion: completion)
}
/// Handles a file import URL if possible.
///
/// - Parameter url: A file URL.
/// - Returns: True if the URL can be handled, otherwise false.
func handleImportURL(_ url: URL) -> Bool {
guard let userFlowViewController = userFlowViewController else {
showSnackbar(withMessage: String.importSignInError)
return false
}
return userFlowViewController.handleImportURL(url)
}
// MARK: - Private
// Wrapper method for use with notifications, where notifications would attempt to push their
// notification object into the completion argument of `forceUserSignIn` incorrectly.
@objc func forceSignInViaNotification() {
tearDownCurrentUser()
showSignIn()
}
private func handlePermissionDenial() {
// Remove the current account and force the user to sign in.
accountsManager.signOutCurrentAccount()
showSignIn {
// Show an alert messaging that permission was denied if we can grab the top view controller.
// The top view controller is required to present an alert. It should be the sign in flow view
// controller.
guard let topVC = self.children.last else { return }
let alertController = MDCAlertController(title: String.serverPermissionDeniedTitle,
message: String.serverPermissionDeniedMessage)
alertController.addAction(MDCAlertAction(title: String.serverSwitchAccountsTitle,
handler: { (_) in self.presentAccountSelector() }))
alertController.addAction(MDCAlertAction(title: String.actionOk))
alertController.accessibilityViewIsModal = true
topVC.present(alertController, animated: true)
}
analyticsReporter.track(.signInPermissionDenied)
}
/// Migrates preferences and removes bluetooth devices if this account is signing in for the first
/// time.
///
/// - Parameter accountID: The account ID.
/// - Returns: Whether the user should be messaged saying that preferences were migrated.
private func migratePreferencesAndRemoveBluetoothDevicesIfNeeded(forAccountID accountID: String)
-> Bool {
// If an account does not yet have a directory, this is its first time signing in. Each new
// account should have preferences migrated from the root user.
let shouldMigratePrefs = !fileSystemLayout.hasAccountDirectory(for: accountID)
if shouldMigratePrefs, let accountUserManager = currentAccountUserManager {
let existingDataMigrationManager =
ExistingDataMigrationManager(accountUserManager: accountUserManager,
rootUserManager: rootUserManager)
existingDataMigrationManager.migratePreferences()
existingDataMigrationManager.removeAllBluetoothDevices()
}
let wasAppUsedByRootUser = rootUserManager.hasExperimentsDirectory
return wasAppUsedByRootUser && shouldMigratePrefs
}
private func performMigrationIfNeededAndContinueSignIn() {
guard let accountID = accountsManager.currentAccount?.ID else {
sjlog_error("Accounts manager does not have a current account after sign in flow completion.",
category: .general)
// This method should never be called if the current user doesn't exist but in case of error,
// show sign in again.
showSignIn()
return
}
// Unwrapping `currentAccountUserManager` would initialize a new instance of the account manager
// if a current account exists. This creates the account's directory. However, the migration
// method checks to see if this directory exists or not, so we must not call it until after
// migration.
shouldShowPreferenceMigrationMessage =
migratePreferencesAndRemoveBluetoothDevicesIfNeeded(forAccountID: accountID)
// Show the migration options if a choice has never been selected.
guard !devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption else {
showCurrentUserOrSignIn()
return
}
guard let accountUserManager = currentAccountUserManager else {
// This delegate method should never be called if the current user doesn't exist but in case
// of error, show sign in again.
showSignIn()
return
}
let existingDataMigrationManager =
ExistingDataMigrationManager(accountUserManager: accountUserManager,
rootUserManager: rootUserManager)
if existingDataMigrationManager.hasExistingExperiments {
self.existingDataMigrationManager = existingDataMigrationManager
let existingDataOptionsVC = ExistingDataOptionsViewController(
analyticsReporter: analyticsReporter,
numberOfExistingExperiments: existingDataMigrationManager.numberOfExistingExperiments)
self.existingDataOptionsVC = existingDataOptionsVC
existingDataOptionsVC.delegate = self
transitionToViewControllerModally(existingDataOptionsVC)
} else {
showCurrentUserOrSignIn()
}
}
/// Prepares an existing user to be removed from memory. This is non-descrtuctive in terms of
/// the user's local data. It should be called when a user is logging out, being removed, or
/// changing to a new user.
private func tearDownCurrentUser() {
_currentAccountUserManager?.tearDown()
_currentAccountUserManager = nil
userFlowViewController = nil
}
// swiftlint:disable vertical_parameter_alignment
/// Uses a modal UI operation to transition to a view controller.
///
/// - Parameters:
/// - viewController: The view controller.
/// - animated: Whether to animate.
/// - minimumDisplaySeconds: The minimum number of seconds to display the view controller for.
/// - completion: Called when finished transitioning to the view controller.
private func transitionToViewControllerModally(_
viewController: UIViewController,
animated: Bool = true,
withMinimumDisplaySeconds minimumDisplaySeconds: Double? = nil,
completion: (() -> Void)? = nil) {
let showViewControllerOp = GSJBlockOperation(mainQueueBlock: { [unowned self] finish in
self.transitionToViewController(viewController, animated: animated) {
completion?()
if let minimumDisplaySeconds = minimumDisplaySeconds {
DispatchQueue.main.asyncAfter(deadline: .now() + minimumDisplaySeconds) { finish() }
} else {
finish()
}
}
})
showViewControllerOp.addCondition(MutuallyExclusive.modalUI)
queue.addOperation(showViewControllerOp)
}
// swiftlint:enable vertical_parameter_alignment
}
// MARK: - AccountsManagerDelegate
extension AppFlowViewController: AccountsManagerDelegate {
func deleteAllUserDataForIdentity(withID identityID: String) {
// Remove the persistent store before deleting the DB files to avoid a log error. Use
// `_currentAccountUserManager`, because `currentAccountUserManager` will return nil because
// `accountsManager.currentAccount` is now nil. Also, remove the current account user manager so
// the sensor data manager is recreated if this same user logs back in immediately.
_currentAccountUserManager?.sensorDataManager.removeStore()
tearDownCurrentUser()
do {
try AccountDeleter(fileSystemLayout: fileSystemLayout, accountID: identityID).deleteData()
} catch {
print("Failed to delete user data: \(error.localizedDescription)")
}
}
func accountsManagerWillBeginSignIn(signInType: SignInType) {
switch signInType {
case .newSignIn:
transitionToViewControllerModally(LoadingViewController(), withMinimumDisplaySeconds: 0.5)
case .restoreCachedAccount:
break
}
}
func accountsManagerSignInComplete(signInResult: SignInResult, signInType: SignInType) {
switch signInResult {
case .accountChanged:
switch signInType {
case .newSignIn:
// Wait for the permissions check to finish before showing UI.
break
case .restoreCachedAccount:
showCurrentUserOrSignIn()
}
case .forceSignIn:
tearDownCurrentUser()
showCurrentUserOrSignIn()
case .noAccountChange:
break
}
}
func accountsManagerPermissionCheckComplete(permissionState: PermissionState,
signInType: SignInType) {
switch signInType {
case .newSignIn:
switch permissionState {
case .granted:
tearDownCurrentUser()
performMigrationIfNeededAndContinueSignIn()
case .denied:
handlePermissionDenial()
}
case .restoreCachedAccount:
switch permissionState {
case .granted:
// UI was shown when sign in completed.
break
case .denied:
handlePermissionDenial()
}
}
}
}
// MARK: - ExistingDataOptionsDelegate
extension AppFlowViewController: ExistingDataOptionsDelegate {
func existingDataOptionsViewControllerDidSelectSaveAllExperiments() {
guard let existingDataOptionsVC = existingDataOptionsVC else { return }
devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = true
let spinnerViewController = SpinnerViewController()
spinnerViewController.present(fromViewController: existingDataOptionsVC) {
self.existingDataMigrationManager?.migrateAllExperiments(completion: { (errors) in
spinnerViewController.dismissSpinner {
self.showCurrentUserOrSignIn()
if errors.containsDiskSpaceError {
showSnackbar(withMessage: String.claimExperimentsDiskSpaceErrorMessage)
} else if !errors.isEmpty {
showSnackbar(withMessage: String.claimExperimentsErrorMessage)
}
}
})
}
}
func existingDataOptionsViewControllerDidSelectDeleteAllExperiments() {
devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = true
existingDataMigrationManager?.removeAllExperimentsFromRootUser()
showCurrentUserOrSignIn()
}
func existingDataOptionsViewControllerDidSelectSelectExperimentsToSave() {
devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = true
// If the user wants to manually select experiments to claim, nothing needs to be done now. They
// will see the option to claim experiments in the experiments list.
showCurrentUserOrSignIn()
}
}
// MARK: - SignInFlowViewControllerDelegate
extension AppFlowViewController: SignInFlowViewControllerDelegate {
func signInFlowDidCompleteWithoutAccount() {
showNonAccountUser(animated: true)
}
}
// MARK: - UserFlowViewControllerDelegate
extension AppFlowViewController: UserFlowViewControllerDelegate {
func presentAccountSelector() {
accountsManager.presentSignIn(fromViewController: self)
}
}
#if SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD
// MARK: - Debug additions for creating data and testing claim and migration flows in-app.
extension AppFlowViewController {
@objc private func debug_createRootUserData() {
guard let settingsVC = userFlowViewController?.settingsVC else { return }
let spinnerVC = SpinnerViewController()
spinnerVC.present(fromViewController: settingsVC) {
self.rootUserManager.documentManager.debug_createRootUserData {
DispatchQueue.main.async {
self.userFlowViewController?.experimentsListVC?.refreshUnclaimedExperiments()
spinnerVC.dismissSpinner()
}
}
}
}
@objc private func debug_forceAuth() {
devicePreferenceManager.hasAUserChosenAnExistingDataMigrationOption = false
devicePreferenceManager.hasAUserCompletedPermissionsGuide = false
NotificationCenter.default.post(name: .DEBUG_destroyCurrentUser, object: nil, userInfo: nil)
showSignIn()
}
}
#endif // SCIENCEJOURNAL_DEV_BUILD || SCIENCEJOURNAL_DOGFOOD_BUILD
| apache-2.0 |
benbahrenburg/BucketList | Example/BucketList/AppDelegate.swift | 1 | 2212 | //
// AppDelegate.swift
// BucketList
//
// Created by ben.bahrenburg@gmail.com on 03/04/2017.
// Copyright (c) 2017 ben.bahrenburg@gmail.com. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
jovito-royeca/Decktracker | ios/Decktracker/CollectionsViewController.swift | 1 | 360 | //
// CollectionsViewController.swift
// Decktracker
//
// Created by Jovit Royeca on 11/07/2016.
// Copyright © 2016 Jovit Royeca. All rights reserved.
//
import UIKit
class CollectionsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| apache-2.0 |
mendesbarreto/IOS | CSBilling/CSBilling/User.swift | 1 | 162 | //
// User.swift
// CSBilling
//
// Created by Douglas Barreto on 2/2/16.
// Copyright © 2016 Concrete Solutions. All rights reserved.
//
import Foundation
| mit |
rcasanovan/Social-Feed | Social Feed/Pods/HanekeSwift/Haneke/Fetch.swift | 16 | 2172 | //
// Fetch.swift
// Haneke
//
// Created by Hermes Pique on 9/28/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import Foundation
enum FetchState<T> {
case pending
// Using Wrapper as a workaround for error 'unimplemented IR generation feature non-fixed multi-payload enum layout'
// See: http://swiftradar.tumblr.com/post/88314603360/swift-fails-to-compile-enum-with-two-data-cases
// See: http://owensd.io/2014/08/06/fixed-enum-layout.html
case success(Wrapper<T>)
case failure(Error?)
}
open class Fetch<T> {
public typealias Succeeder = (T) -> ()
public typealias Failer = (Error?) -> ()
fileprivate var onSuccess : Succeeder?
fileprivate var onFailure : Failer?
fileprivate var state : FetchState<T> = FetchState.pending
public init() {}
@discardableResult open func onSuccess(_ onSuccess: @escaping Succeeder) -> Self {
self.onSuccess = onSuccess
switch self.state {
case FetchState.success(let wrapper):
onSuccess(wrapper.value)
default:
break
}
return self
}
@discardableResult open func onFailure(_ onFailure: @escaping Failer) -> Self {
self.onFailure = onFailure
switch self.state {
case FetchState.failure(let error):
onFailure(error)
default:
break
}
return self
}
func succeed(_ value: T) {
self.state = FetchState.success(Wrapper(value))
self.onSuccess?(value)
}
func fail(_ error: Error? = nil) {
self.state = FetchState.failure(error)
self.onFailure?(error)
}
var hasFailed : Bool {
switch self.state {
case FetchState.failure(_):
return true
default:
return false
}
}
var hasSucceeded : Bool {
switch self.state {
case FetchState.success(_):
return true
default:
return false
}
}
}
open class Wrapper<T> {
open let value: T
public init(_ value: T) { self.value = value }
}
| apache-2.0 |
mathiasquintero/Sweeft | Sources/Sweeft/Promises/Subclasses/BulkPromise.swift | 1 | 1796 | //
// BulkPromise.swift
// Pods
//
// Created by Mathias Quintero on 12/29/16.
//
//
import Foundation
/// A promise that represent a collection of other promises and waits for them all to be finished
public final class BulkPromise<T, O: Error>: SelfSettingPromise<[T], O> {
private let queue = DispatchQueue(label: "io.quintero.Sweeft.BulkPromise")
private var cancellers: [Promise<T, O>.Canceller]
private var results: [Int : T] = .empty {
didSet {
if results.count == count {
let sorted = results.sorted(ascending: firstArgument) => lastArgument
setter?.success(with: sorted)
}
}
}
private var count: Int {
return cancellers.count
}
public init(promises: [Promise<T,O>], completionQueue: DispatchQueue = .global()) {
let cancellers = promises => { $0.canceller }
self.cancellers = cancellers
super.init(completionQueue: completionQueue)
promises.withIndex => { promise, index in
promise.onError(in: queue, call: self.setter.error)
promise.onSuccess(in: queue) { result in
self.results[index] = result
}
}
setter.onCancel {
cancellers => { $0.cancel() }
}
if promises.isEmpty {
setter.success(with: [])
}
}
}
extension BulkPromise where T: Collection {
public var flattened: Promise<[T.Element], O> {
return map { result in
return result.flatMap(id)
}
}
}
extension BulkPromise: ExpressibleByArrayLiteral {
public convenience init(arrayLiteral elements: Promise<T, O>...) {
self.init(promises: elements)
}
}
| mit |
mitchtreece/Bulletin | Example/Pods/Espresso/Espresso/Classes/Core/Protocols/Convertibles/BoolConvertible.swift | 1 | 2105 | //
// BoolConvertible.swift
// Espresso
//
// Created by Mitch Treece on 12/15/17.
//
import Foundation
/**
Protocol describing the conversion to various `Bool` representations.
*/
public protocol BoolConvertible {
/**
A boolean representation.
*/
var bool: Bool? { get }
/**
A boolean integer representation; _0 or 1_.
*/
var boolInt: Int? { get }
/**
A boolean string representation _"true" or "false"_.
*/
var boolString: String? { get }
}
extension Bool: BoolConvertible {
public static let trueString = "true"
public static let falseString = "false"
public var bool: Bool? {
return self
}
public var boolInt: Int? {
return self ? 1 : 0
}
public var boolString: String? {
return self ? Bool.trueString : Bool.falseString
}
}
extension Int: BoolConvertible {
public var bool: Bool? {
return (self <= 0) ? false : true
}
public var boolInt: Int? {
return (self <= 0) ? 0 : 1
}
public var boolString: String? {
return (self <= 0) ? Bool.falseString : Bool.trueString
}
}
extension String: BoolConvertible {
public var bool: Bool? {
guard let value = self.boolInt else { return nil }
switch value {
case 0: return false
case 1: return true
default: return nil
}
}
public var boolInt: Int? {
guard let value = self.boolString else { return nil }
switch value {
case Bool.trueString: return 1
case Bool.falseString: return 0
default: return nil
}
}
public var boolString: String? {
let value = self.lowercased()
if value == Bool.trueString || value == "1" {
return Bool.trueString
}
else if value == Bool.falseString || value == "0" {
return Bool.falseString
}
return nil
}
}
| mit |
64characters/Telephone | Telephone/SettingsAccounts.swift | 1 | 1128 | //
// SettingsAccounts.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone 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.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UseCases
final class SettingsAccounts {
private let settings: KeyValueSettings
init(settings: KeyValueSettings) {
self.settings = settings
}
}
extension SettingsAccounts: Accounts {
var haveEnabled: Bool {
return accounts().map({ SettingsAccount(dict: $0) }).filter(\.isEnabled).count > 0
}
private func accounts() -> [[String: Any]] {
return settings.array(forKey: UserDefaultsKeys.accounts) as? [[String: Any]] ?? []
}
}
| gpl-3.0 |
anatoliyv/navigato | Navigato/Classes/SourceApps/NavigatoWaze.swift | 1 | 758 | //
// NavigatoWaze.swift
// Navigato
//
// Created by Anatoliy Voropay on 10/31/17.
//
import Foundation
/// Waze maps source type for `Navigato`
public class NavigatoWaze: NavigatoSourceApp {
public override var name: String {
return "Waze"
}
override public var isAvailable: Bool {
guard let url = URL(string: "waze://") else { return false }
return UIApplication.shared.canOpenURL(url)
}
public override func path(forRequest request: Navigato.RequestType) -> String {
switch request {
case .address:
return "https://waze.com/ul?q="
case .location:
return "waze://?ll="
case .search:
return "https://waze.com/ul?q="
}
}
}
| mit |
leios/algorithm-archive | contents/verlet_integration/code/swift/verlet.swift | 1 | 1714 | func verlet(pos: Double, acc: Double, dt: Double) -> Double {
var pos = pos
var temp_pos, time: Double
var prev_pos = pos
time = 0.0
while (pos > 0) {
time += dt
temp_pos = pos
pos = pos*2 - prev_pos + acc * dt * dt
prev_pos = temp_pos
}
return time
}
func stormerVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: Double) {
var pos = pos
var temp_pos, time, vel: Double
var prev_pos = pos
vel = 0
time = 0
while (pos > 0) {
time += dt
temp_pos = pos
pos = pos*2 - prev_pos + acc * dt * dt
prev_pos = temp_pos
vel += acc*dt
}
return (time:time, vel:vel)
}
func velocityVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: Double) {
var pos = pos
var time, vel : Double
vel = 0
time = 0
while (pos > 0) {
time += dt
pos += vel*dt + 0.5*acc * dt * dt
vel += acc*dt
}
return (time:time, vel:vel)
}
func main() {
let verletTime = verlet(pos: 5.0, acc: -10.0, dt: 0.01)
print("[#]\nTime for Verlet integration is:")
print("\(verletTime)")
let stormer = stormerVerlet(pos: 5.0, acc: -10.0, dt: 0.01);
print("[#]\nTime for Stormer Verlet integration is:")
print("\(stormer.time)")
print("[#]\nVelocity for Stormer Verlet integration is:")
print("\(stormer.vel)")
let velVerlet = velocityVerlet(pos: 5.0, acc: -10, dt: 0.01)
print("[#]\nTime for velocity Verlet integration is:")
print("\(velVerlet.time)")
print("[#]\nVelocity for velocity Verlet integration is:")
print("\(velVerlet.vel)")
}
main()
| mit |
NocturneZX/TTT-Pre-Internship-Exercises | Swift/fromSam/week_02/class4/Week2-Class4-3-StdLibrary-iTunesSearchSample/SwiftSortExample/SwiftSortExample/AppDelegate.swift | 4 | 2177 | //
// AppDelegate.swift
// SwiftSortExample
//
// Created by Aditya Narayan on 6/10/14.
// Copyright (c) 2014 Aditya Narayan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-2.0 |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab5MyPage/SLV_921_AlarmListController.swift | 1 | 473 | //
// SLV_921_AlarmListController.swift
// selluv-ios
//
// Created by 조백근 on 2016. 11. 8..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
/*
알림목록 컨트롤러
*/
import Foundation
import UIKit
class SLV_921_AlarmListController: SLVBaseStatusShowController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
rentpath/RPValidationKit | RPValidationKit/RPValidationKit/Validators/RPFloatValidator.swift | 1 | 1676 | /*
* Copyright (c) 2016 RentPath, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
open class RPFloatValidator: RPValidator {
open override func getType() -> String {
return "float"
}
open override func validate(_ value: String) -> Bool {
if let _ = Float(value) {
return true
}
return false
}
open override func validateField(_ fieldName: String, value: String) -> RPValidation {
if validate(value) {
return RPValidation.valid
} else {
return RPValidation.error(message: "\(fieldName) is not a float")
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/08731-swift-sourcemanager-getmessage.swift | 11 | 211 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let g {
func i{
switch x = {
class
case ,
| mit |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Views/RightTableViewCell.swift | 1 | 835 | //
// RightTableViewCell.swift
// zhuishushenqi
//
// Created by Nory Cao on 16/9/18.
// Copyright © 2016年 QS. All rights reserved.
//
import UIKit
class RightTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
imageView?.frame = CGRect(x: 10, y: 15, width: 30, height: 30)
textLabel?.frame = CGRect(x: imageView!.frame.maxX + 15, y: 0, width: 150, height: 60)
textLabel?.textColor = UIColor.white
textLabel?.font = UIFont.systemFont(ofSize: 14)
}
}
| mit |
BBRick/wp | wp/Scenes/Home/SideVC.swift | 1 | 2295 | //
// SideVC.swift
// wp
//
// Created by 木柳 on 2016/12/22.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
import SideMenuController
class SideVC: SideMenuController, SideMenuControllerDelegate {
required init?(coder aDecoder: NSCoder) {
SideMenuController.preferences.drawing.menuButtonImage = UIImage.init(named:"1")
SideMenuController.preferences.drawing.sidePanelPosition = .overCenterPanelLeft
SideMenuController.preferences.drawing.sidePanelWidth = UIScreen.main.bounds.size.width * 0.80
SideMenuController.preferences.drawing.centerPanelShadow = true
SideMenuController.preferences.animating.statusBarBehaviour = .slideAnimation
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
performSegue(withIdentifier: "centerSegue", sender: nil)
performSegue(withIdentifier: "sideSegue", sender: nil)
delegate = self
}
func sideMenuControllerDidHide(_ sideMenuController: SideMenuController) {
tabBarController?.tabBar.isHidden = false
}
func sideMenuControllerDidReveal(_ sideMenuController: SideMenuController) {
tabBarController?.tabBar.isHidden = true
}
}
extension SideVC{
public override static func initialize() {
//tabbar的隐藏
let originalSelector = #selector(SideMenuController.toggle)
let swizzledSelector = #selector(SideVC.wpToggle)
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didsMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didsMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
func wpToggle() {
// if checkLogin() {
self.wpToggle()
super.toggle()
tabBarController?.tabBar.isHidden = true
// }
}
}
| apache-2.0 |
mkrisztian95/iOS | Tardis/APPConfig.swift | 1 | 911 | //
// APPConfig.swift
// Tardis
//
// Created by Molnar Kristian on 7/25/16.
// Copyright © 2016 Molnar Kristian. All rights reserved.
//
import UIKit
class APPConfig: NSObject {
let dataBaseRoot = "dev"
func setUpCellForUsage(cell:UITableViewCell) {
cell.accessoryType = .None
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.backgroundColor = UIColor.clearColor()
}
let blueColor:UIColor! = UIColor(red: 66/255.0, green: 133/255.0, blue: 244/255.0, alpha: 1.0)
let redColor:UIColor! = UIColor(red: 219/255.0, green: 68/255.0, blue: 55/255.0, alpha: 1.0)
let yellowColor:UIColor! = UIColor(red: 244/255.0, green: 180/255.0, blue: 0/255.0, alpha: 1.0)
let greenColor:UIColor! = UIColor(red: 15/255.0, green: 157/255.0, blue: 88/255.0, alpha: 1.0)
let appColor:UIColor! = UIColor(red: 66/255.0, green: 133/255.0, blue: 244/255.0, alpha: 1.0)
}
| apache-2.0 |
crazypoo/Tuan | Tuan/Deal/HMDealsViewController.swift | 8 | 19312 | //
// HMDealsViewController.swift
// Tuan
//
// Created by nero on 15/5/13.
// Copyright (c) 2015年 nero. All rights reserved.
//
import UIKit
class HMDealsViewController: HMDealListViewController {
//MARK: - 顶部菜单
/** 分类菜单 */
var categoryMenu:HMDealsTopMenu!
/** 区域菜单 */
var regionMenu:HMDealsTopMenu!
/** 排序菜单 */
var sortMenu:HMDealsTopMenu!
/** 选中的状态 */
var selectedCity:HMCity!
/** 当前选中的区域 */
var selectedRegion:HMRegion!
/** 当前选中的排序 */
var selectedSort:HMSort!
/** 当前选中的分类 */
var selectedCategory:HMCategory!
/** 当前选中的子分类名称 */
var selectedSubCategoryName:String!
/** 当前选中的子区域名称 */
var selectedSubRegionName:String!
//MARK: - 点击顶部菜单后弹出的Popover
/** 分类Popover */
lazy var categoryPopover:UIPopoverController = {
let cv = HMCategoriesViewController()
return UIPopoverController(contentViewController: cv)
}()
/** 区域Popover */
lazy var regionPopover:UIPopoverController = {
let rv = HMRegionsViewController()
rv.view = NSBundle.mainBundle().loadNibNamed("HMRegionsViewController", owner: rv, options: nil).last as! UIView
var region = UIPopoverController(contentViewController: rv)
rv.changeCityClosuer = {
region.dismissPopoverAnimated(false)
}
return region
}()
/** 排序Popover */
lazy var sortPopover:UIPopoverController = {
let sv = HMSortsViewController()
return UIPopoverController(contentViewController: HMSortsViewController(nibName: "HMSortsViewController", bundle: NSBundle.mainBundle()))
}()
/** 请求参数 */
var lastParam:HMFindDealsParam?
var header:MJRefreshHeaderView!
var footer:MJRefreshFooterView!
/// 团购数据
/** 存储请求结果的总数*/
var totalNumber:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
selectedSort = HMMetaDataTool.sharedMetaDataTool().selectedSort()
selectedCity = HMMetaDataTool.sharedMetaDataTool().selectedCity()
var rs = regionPopover.contentViewController as! HMRegionsViewController
if selectedCity != nil {
rs.regions = (selectedCity.regions as? [HMRegion] ) ?? nil ;
}
setupMenu()
setupNavLeft()
setupNavRight()
setupRefresh()
// 监听通知
HMNotificationCenter.addObserver(self, selector: Selector("citySelecte:"), name: HMCityNotification.HMCityDidSelectNotification, object: nil)
HMNotificationCenter.addObserver(self, selector: Selector("sortSelect:"), name: HMSortNotification.HMSortDidSelectNotification, object: nil)
HMNotificationCenter.addObserver(self, selector: Selector("categoryDidSelect:"), name: HMCategoryNotification.HMCategoryDidSelectNotification, object: nil)
HMNotificationCenter.addObserver(self, selector: Selector("regionDidSelect:"), name: HMRegionNotification.HMRegionDidSelectNotification, object: nil)
}
func setupRefresh(){
// MJRefreshHeaderView *header = [MJRefreshHeaderView header];
self.header = MJRefreshHeaderView.header()
self.footer = MJRefreshFooterView.footer()
self.header.scrollView = self.collectionView
self.footer.scrollView = self.collectionView
self.header.delegate = self
self.footer.delegate = self
header.beginRefreshing()
}
func citySelecte(noti:NSNotification){
var dict = noti.userInfo as! [String:HMCity]
selectedCity = dict[HMCityNotification.HMSelectedCity]
selectedRegion = selectedCity.regions.first as! HMRegion
regionMenu.titleLabel.text = selectedCity?.name.stringByAppendingString(" - 全部")
regionMenu.subtitleLabel.text = ""
//
var regionVc = regionPopover.contentViewController as! HMRegionsViewController
regionVc.regions = selectedCity?.regions as! [HMRegion]
header.beginRefreshing()
// 存储用户的选择到沙盒
HMMetaDataTool.sharedMetaDataTool().saveSelectedCityName(selectedCity.name)
}
func sortSelect(noti:NSNotification){
var dict = noti.userInfo as! [String:HMSort]
selectedSort = dict[HMSortNotification.HMSelectedSort]
sortMenu.subtitleLabel.text = selectedSort?.label
sortPopover.dismissPopoverAnimated(true)
header.beginRefreshing()
// 存储用户的选择到沙盒
HMMetaDataTool.sharedMetaDataTool().saveSelectedSort(selectedSort)
}
func regionDidSelect(noti:NSNotification) {
// 取出通知中的数据
selectedRegion = noti.userInfo?[HMRegionNotification.HMSelectedRegion] as? HMRegion
selectedSubRegionName = noti.userInfo?[HMRegionNotification.HMSelectedSubRegionName] as? String
regionMenu.titleLabel.text = "\(selectedCity.name) - \(selectedRegion.name)"
regionMenu.subtitleLabel.text = selectedSubRegionName
// 设置菜单数据
// 关闭popover
regionPopover.dismissPopoverAnimated(true)
header.beginRefreshing()
}
func categoryDidSelect(noti:NSNotification){
// 取出通知中的数据
selectedCategory = noti.userInfo?[HMCategoryNotification.HMSelectedCategory] as? HMCategory
selectedSubCategoryName = noti.userInfo?[HMCategoryNotification.HMSelectedSubCategoryName] as? String
// 设置菜单数据
categoryMenu.imageButton.image = selectedCategory.icon
categoryMenu.imageButton.highlightedImage = selectedCategory.highlighted_icon
categoryMenu.titleLabel.text = selectedCategory.name
categoryMenu.subtitleLabel.text = selectedSubCategoryName
// 关闭popover
categoryPopover.dismissPopoverAnimated(true)
header.beginRefreshing()
}
deinit{
HMNotificationCenter.removeObserver(self)
self.footer = nil
self.header = nil
}
/**
* 设置导航栏左边的内容
*/
private func setupNavLeft() {
// 1.LOGO
var logoItem = UIBarButtonItem(imageName: "icon_meituan_logo", highImageName: "icon_meituan_logo", target: nil, action: nil)
logoItem.customView?.userInteractionEnabled = false
// 2.分类
categoryMenu = HMDealsTopMenu()
var categoryItem = UIBarButtonItem(customView: categoryMenu)
categoryMenu.addTarget(self, action: Selector("categoryMenuClick"))
// 3.区域
regionMenu = HMDealsTopMenu()
regionMenu.imageButton.image = "icon_district";
regionMenu.imageButton.highlightedImage = "icon_district_highlighted";
var selectName = selectedCity?.name ?? " "
regionMenu.titleLabel.text = "\(selectName) - 全部"
var regionItem = UIBarButtonItem(customView: regionMenu)
regionMenu.addTarget(self, action: Selector("regionMenuClick"))
// 4.排序
sortMenu = HMDealsTopMenu()
var sortItem = UIBarButtonItem(customView: sortMenu)
sortMenu.addTarget(self, action: Selector("sortMenuClick"))
sortMenu.imageButton.image = "icon_sort";
sortMenu.imageButton.highlightedImage = "icon_sort_highlighted"
sortMenu.titleLabel.text = "排序"
sortMenu.subtitleLabel.text = self.selectedSort?.label;
self.navigationItem.leftBarButtonItems = [logoItem, categoryItem, regionItem, sortItem];
}
// MARK: -leftItem Event
/** 分类菜单 */
func categoryMenuClick(){
var cs = categoryPopover.contentViewController as! HMCategoriesViewController
cs.selectedCategory = selectedCategory
cs.selectedSubCategoryName = selectedSubCategoryName;
categoryPopover.presentPopoverFromRect(categoryMenu.bounds, inView: categoryMenu, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
/** 区域菜单 */
func regionMenuClick(){
var rs = regionPopover.contentViewController as! HMRegionsViewController
rs.selectedRegion = selectedRegion;
rs.selectedSubRegionName = selectedSubRegionName;
regionPopover.presentPopoverFromRect(regionMenu.bounds, inView: regionMenu, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
/** 排序菜单 */
func sortMenuClick(){
var os = sortPopover.contentViewController as! HMSortsViewController
os.selectedSort = self.selectedSort;
sortPopover.presentPopoverFromRect(sortMenu.bounds, inView: sortMenu, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
/**
*MARK:- 设置导航栏右边的内容
*/
private func setupNavRight() {
// // 1.地图
var mapItem = UIBarButtonItem(imageName: "icon_map", highImageName: "icon_map_highlighted", target: self , action: Selector("mapClick"))
mapItem.customView?.width = 50
mapItem.customView?.height = 27
// // 2.搜索
var searchItem = UIBarButtonItem(imageName: "icon_search", highImageName: "icon_search_highlighted", target: self, action: Selector("searchClick"))
searchItem.customView?.width = mapItem.customView!.width
searchItem.customView?.width = mapItem.customView!.height
self.navigationItem.rightBarButtonItems = [mapItem,searchItem]
}
/**
* 搜索
*/
func searchClick() {
var searchVc = HMSearchViewController(collectionViewLayout: UICollectionViewLayout())
searchVc.selectedCity = self.selectedCity;
var nav = HMNavigationController(rootViewController: searchVc)
presentViewController(nav, animated: true, completion: nil)
}
/**
* 地图
*/
func mapClick(){
var nav = HMNavigationController(rootViewController: HMMapViewController())
presentViewController(nav , animated: true, completion: nil)
}
/**
封装请求参数
:returns: param
*/
func buildParam() -> HMFindDealsParam {
var param = HMFindDealsParam()
// 城市名称
param.city = selectedCity?.name
if selectedSort != nil {
param.sort = NSNumber(int: selectedSort.value)
}
// 除开“全部分类”和“全部”以外的所有词语都可以发
if selectedCategory != nil && !(selectedCategory?.name == "全部分类") {
if selectedSubCategoryName != nil && !(self.selectedSubCategoryName == "全部"){
param.category = selectedSubCategoryName
}else{
param.category = selectedCategory?.name
}
}
if selectedRegion != nil && !(selectedRegion?.name == "全部" ){
if selectedSubRegionName != nil && !(selectedSubRegionName == "全部"){
param.region = selectedSubRegionName
}else{
param.region = selectedRegion?.name
}
}
param.page = NSNumber(int: 1)
return param
}
func loadNewDeals(){
// // 1.创建请求参数
var param = buildParam()
// // 2.加载数据
HMDealTool.findDeals(param, success: { (result) -> Void in
if param != self.lastParam {return }
// 记录总数
self.totalNumber = Int(result.total_count)
// // 清空之前的所有数据
self.deals.removeAll(keepCapacity: false)
for deal in result.deals {
self.deals.append(deal as! HMDeal)
}
self.collectionView?.reloadData()
self.header.endRefreshing()
}) { (error) -> Void in
if param != self.lastParam {return }
MBProgressHUD.showError("加载团购失败,请稍后再试")
self.header.endRefreshing()
}
// // 3.保存请求参数
self.lastParam = param;
}
/**
加载新数据
*/
#if false
func loadXXXNewDeals(){
HMDealTool.loadNewDeals(selectedCity, selectSort: selectedSort, selectedCategory: selectedCategory, selectedRegion: selectedRegion, selectedSubCategoryName: selectedSubCategoryName, selectedSubRegionName: selectedSubRegionName) { (result) -> Void in
// 清空之前的所有数据
self.deals = [HMDeal]()
// 添加新的数据
for deal in result {
self.deals.append(deal as! HMDeal)
}
// 刷新表格
self.collectionView?.reloadData()
}
}
#endif
/**
加载更多
*/
func loadMoreDeals(){
// // 1.创建请求参数
var param = buildParam()
// // 页码
if let lastParam = self.lastParam {
var currentPage = lastParam.page.intValue + 1
param.page = NSNumber(int: currentPage)
}
HMDealTool.findDeals(param, success: { (result) -> Void in
if param != self.lastParam {return }
for deal in result.deals {
self.deals.append(deal as! HMDeal)
}
self.collectionView?.reloadData()
self.footer.endRefreshing()
}) { (error) -> Void in
if param != self.lastParam {return }
MBProgressHUD.showError("加载团购失败,请稍后再试")
// // 结束刷新
self.footer.endRefreshing()
// // 回滚页码
if let lastParam = self.lastParam {
var currentPage = lastParam.page.intValue - 1
param.page = NSNumber(int: currentPage)
}
}
self.lastParam = param
}
// MARK: - 初始化菜单
private func setupMenu(){
// // 1.周边的item
var mineItem = itemWithContent("icon_pathMenu_mine_normal", highlightedContent: "icon_pathMenu_mine_highlighted")
var collectItem = itemWithContent("icon_pathMenu_collect_normal" , highlightedContent: "icon_pathMenu_collect_highlighted")
var scanItem = itemWithContent("icon_pathMenu_scan_normal", highlightedContent: "icon_pathMenu_more_normal")
var moreItem = itemWithContent("icon_pathMenu_more_normal", highlightedContent: "icon_pathMenu_more_highlighted")
var items = [mineItem,collectItem,scanItem,moreItem]
// // 2.中间的开始tiem
var startItem = AwesomeMenuItem(image: UIImage(named: "icon_pathMenu_background_normal"), highlightedImage: UIImage(named:"icon_pathMenu_background_highlighted"), contentImage: UIImage(named:"icon_pathMenu_mainMine_normal"), highlightedContentImage: UIImage(named:"icon_pathMenu_mainMine_highlighted"))
var menu = AwesomeMenu(frame: CGRectZero, startItem: startItem, optionMenus: items)
view.addSubview(menu)
// // 真个菜单的活动范围
menu.menuWholeAngle = CGFloat( M_PI_2);
// // 约束
var menuH:CGFloat = 200
menu.autoSetDimensionsToSize(CGSize(width: 200, height: menuH))
menu.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 0)
menu.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: 0)
// // 3.添加一个背景
let menubg = UIImageView()
menubg.image = UIImage(named: "icon_pathMenu_background")
menu.insertSubview(menubg, atIndex: 0)
// 约束
menubg.autoSetDimensionsToSize(menubg.image!.size)
menubg.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 0)
menubg.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: 0)
// // 起点
menu.startPoint = CGPoint(x: menubg.image!.size.width * 0.5, y: menuH - menubg.image!.size.height * 0.5)
// // 禁止中间按钮旋转
menu.rotateAddButton = false
//
// // 设置代理
menu.delegate = self;
//
menu.alpha = CGFloat(0.2)
}
private func itemWithContent(content:String , highlightedContent:String) ->AwesomeMenuItem {
let bg = UIImage(named: "bg_pathMenu_black_normal");
return AwesomeMenuItem(image: bg, highlightedImage: nil, contentImage: UIImage(named: content), highlightedContentImage: UIImage(named: highlightedContent))
}
}
extension HMDealsViewController:AwesomeMenuDelegate {
func awesomeMenuWillAnimateClose(menu: AwesomeMenu!) {
// 恢复图片
menu.contentImage = UIImage(named: "icon_pathMenu_mainMine_normal")
menu.highlightedContentImage = UIImage(named: "icon_pathMenu_mainMine_highlighted")
UIView.animateWithDuration(0.25, animations: { () -> Void in
menu.alpha = CGFloat(0.2)
})
}
func awesomeMenuWillAnimateOpen(menu: AwesomeMenu!) {
// 显示xx图片
menu.contentImage = UIImage(named: "icon_pathMenu_cross_normal");
menu.highlightedContentImage = UIImage(named: "icon_pathMenu_cross_highlighted")
UIView.animateWithDuration(0.25, animations: { () -> Void in
menu.alpha = CGFloat(1)
})
}
func awesomeMenu(menu: AwesomeMenu!, didSelectIndex idx: Int) {
awesomeMenuWillAnimateClose(menu)
if (idx == 1) { // 收藏
let collec = HMCollectViewController(collectionViewLayout: UICollectionViewFlowLayout())
var nav = HMNavigationController(rootViewController: collec)
presentViewController(nav, animated: true, completion: nil)
} else if (idx == 2) { // 浏览记录
let history = HMHistoryViewController(collectionViewLayout: UICollectionViewFlowLayout())
var nav = HMNavigationController(rootViewController: history)
presentViewController(nav, animated: true, completion: nil)
}
}
}
// MARK: - cell And Layout
extension HMDealsViewController {
// #warning 如果要在数据个数发生的改变时做出响应,那么响应操作可以考虑在数据源方法中实现
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// 尾部控件的可见性
self.footer.hidden = (self.deals.count == self.totalNumber);
return super.collectionView(collectionView, numberOfItemsInSection: section)
}
}
extension HMDealsViewController: MJRefreshBaseViewDelegate {
func refreshViewBeginRefreshing(refreshView: MJRefreshBaseView!) {
if refreshView === self.header {
self.loadNewDeals()
}else if refreshView === self.footer {
self.loadMoreDeals()
}
}
}
//MARK: - emptyView ICON
extension HMDealsViewController {
override func emptyIcon() -> String {
return "icon_deals_empty"
}
}
| mit |
emrecaliskan/ECDropDownList | ECDropDownList/ECListItemView.swift | 1 | 2655 | //
// ECListItemView.swift
// ECDropDownList
//
// Created by Emre Caliskan on 2015-03-23.
// Copyright (c) 2015 pictago. All rights reserved.
//
import UIKit
func ==(lhs: ECListItemView, rhs: ECListItemView) -> Bool {
return lhs.listItem == rhs.listItem
}
protocol ECListItemDelegate {
func didTapItem(listItemView:ECListItemView)
}
class ECListItemView: UIView {
var listItem:ECListItem
var titleLabel:UILabel = UILabel()
var listItemFrameHeight = CGFloat(40.0)
var listItemTextAlignment = NSTextAlignment.Center
var overlayButton = UIButton()
var delegate:ECListItemDelegate?
override init(frame: CGRect) {
self.listItem = ECListItem()
super.init(frame: frame)
}
init(listItem:ECListItem) {
self.listItem = listItem
super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, listItemFrameHeight))
self.backgroundColor = UIColor.lightGrayColor()
//Add titleLabel for Item
titleLabel.frame = self.frame
titleLabel.text = self.listItem.text
titleLabel.textColor = UIColor.blackColor()
titleLabel.textAlignment = listItemTextAlignment
self.addSubview(titleLabel)
//Configure Overlay Button that handles tap actions
overlayButton.frame = self.frame
overlayButton.backgroundColor = UIColor.clearColor()
overlayButton.addTarget(self, action: "didPressButton", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(overlayButton)
}
required init(coder aDecoder: NSCoder) {
self.listItem = ECListItem()
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
/// Executes listItem action, if the listItemView is not the topView in the menu.THEN, executes delegate didTap delegate. Order is important.
func didPressButton(){
if !listItem.isSelected{
listItem.action?()
}
delegate?.didTapItem(self)
}
override func copy() -> AnyObject {
let copy = ECListItemView(listItem: self.listItem)
copy.titleLabel = self.titleLabel
copy.listItemFrameHeight = self.listItemFrameHeight
copy.listItemTextAlignment = self.listItemTextAlignment
copy.overlayButton = self.overlayButton
return copy
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit |
SwifterSwift/SwifterSwift | Tests/SceneKitTests/SCNMaterialExtensionsTests.swift | 1 | 403 | // SCNMaterialExtensionsTests.swift - Copyright 2020 SwifterSwift
@testable import SwifterSwift
import XCTest
#if canImport(SceneKit)
import SceneKit
final class SCNMaterialExtensionsTests: XCTestCase {
func testInitWithColor() {
let color = SFColor.red
let material = SCNMaterial(color: color)
XCTAssertEqual(material.diffuse.contents as? SFColor, color)
}
}
#endif
| mit |
nfls/nflsers | app/v2/Controller/Practice/ProblemSearchController.swift | 1 | 6265 | //
// ProblemSearchController.swift
// NFLSers-iOS
//
// Created by Qingyang Hu on 2018/9/23.
// Copyright © 2018 胡清阳. All rights reserved.
//
import Foundation
import Eureka
class ProblemSearchController: FormViewController {
let courseProvider = CourseProvider()
let paperProvider = PaperProvider()
let problemProvider = ProblemProvider()
enum Mode: String {
case question = "题目"
case paper = "往卷"
case wrong = "错题"
}
let isNotPaper = Condition.function(["type"], { (form) -> Bool in
return (form.rowBy(tag: "type") as? SegmentedRow<String>)?.value != Mode.paper.rawValue
})
let isNotQuestion = Condition.function(["type"], { (form) -> Bool in
return (form.rowBy(tag: "type") as? SegmentedRow<String>)?.value != Mode.question.rawValue
})
override func viewDidLoad() {
super.viewDidLoad()
courseProvider.load {
self.list()
}
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(search))
}
@objc func search() {
switch (form.rowBy(tag: "type") as? SegmentedRow<String>)?.value {
case Mode.paper.rawValue:
let section = form.sectionBy(tag: "paper") as! SelectableSection<ListCheckRow<UUID>>
if let paper = section.selectedRow()?.selectableValue {
self.problemProvider.list(withPaper: paper) {
dump(self.problemProvider.list)
}
}
break
case Mode.question.rawValue:
break
case Mode.wrong.rawValue:
break
default:
break
}
}
func addCourse(withType type: Course.CourseType, name: String) {
let section = SelectableSection<ListCheckRow<UUID>>(name, selectionType: .singleSelection(enableDeselection: false)) {
$0.tag = String(describing: type)
$0.hidden = Condition.function([], { (form) -> Bool in
let section = form.sectionBy(tag: "course") as? SelectableSection<ListCheckRow<Int>>
return section?.selectedRow()?.selectableValue != type.rawValue
})
$0.onSelectSelectableRow = { (cell, cellRow) in
self.paperProvider.load(withCourse: cellRow.selectableValue!, completion: {
self.addPaperSelect()
})
}
}
let list = self.courseProvider.list.filter { (course) -> Bool in
return course.type == type
}
for course in list {
section <<< ListCheckRow<UUID>() { listRow in
listRow.title = course.name + " (" + course.remark + ")"
listRow.selectableValue = course.id
listRow.value = nil
}
}
self.form +++ section
}
func removePaperSelect() {
if let section = form.sectionBy(tag: "paper"), let index = section.index {
form.remove(at: index)
}
}
func addPaperSelect() {
self.removePaperSelect()
let section = SelectableSection<ListCheckRow<UUID>>("试卷", selectionType: .singleSelection(enableDeselection: false)) {
$0.tag = "paper"
//$0.hidden = self.isQuestion
}
for paper in paperProvider.list {
section <<< ListCheckRow<UUID>(paper.name) {
$0.title = paper.name
$0.selectableValue = paper.id
$0.value = nil
}
}
form +++ section
}
func addTypeSelect() {
let options = ["IGCSE", "A-Level", "IBDP"]
let section = SelectableSection<ListCheckRow<Int>>("课程", selectionType: .singleSelection(enableDeselection: false)) {
$0.tag = "course"
}
section <<< ListCheckRow<Int>("所有") {
$0.title = "所有"
$0.selectableValue = 0
$0.value = nil
$0.hidden = self.isNotPaper
}
for (key, option) in options.enumerated() {
section <<< ListCheckRow<Int>(option) { listRow in
listRow.title = option
listRow.selectableValue = key + 1
listRow.value = nil
}
}
section.onSelectSelectableRow = { [weak self] _, _ in
self?.form.sectionBy(tag: String(describing: Course.CourseType.alevel))?.evaluateHidden()
self?.form.sectionBy(tag: String(describing: Course.CourseType.igcse))?.evaluateHidden()
self?.form.sectionBy(tag: String(describing: Course.CourseType.ibdp))?.evaluateHidden()
}
form +++ section
}
func list() {
self.form +++ Section("类型")
<<< SegmentedRow<String>() {
$0.tag = "type"
$0.options = ["题目", "往卷", "错题"]
$0.value = "题目"
$0.onChange({ (_) in
self.removePaperSelect()
})
}
self.addTypeSelect()
self.addCourse(withType: Course.CourseType.igcse, name: "IGCSE")
self.addCourse(withType: Course.CourseType.alevel, name: "A-Level")
self.addCourse(withType: Course.CourseType.ibdp, name: "IBDP")
self.form +++ Section("题型") {$0.hidden = self.isNotQuestion}
<<< SwitchRow() { (switchRow) in
switchRow.title = "选择题"
switchRow.value = true
}
<<< SwitchRow() { (switchRow) in
switchRow.title = "填空题"
switchRow.value = true
}
+++ Section("附加") {$0.hidden = self.isNotQuestion}
<<< SwitchRow() { (switchRow) in
switchRow.title = "精确搜索"
}
+++ Section("搜索") {$0.hidden = self.isNotQuestion}
<<< TextAreaRow() { (textAreaRow) in
textAreaRow.placeholder = "题面,几个词即可"
}
<<< ButtonRow() {(buttonRow) in
buttonRow.title = "拍照"
}
}
}
| apache-2.0 |
kaojohnny/CoreStore | Sources/Internal/NSManagedObjectContext+Setup.swift | 1 | 6500 | //
// NSManagedObjectContext+Setup.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - NSManagedObjectContext
internal extension NSManagedObjectContext {
// MARK: Internal
@nonobjc
internal weak var parentStack: DataStack? {
get {
if let parentContext = self.parentContext {
return parentContext.parentStack
}
return cs_getAssociatedObjectForKey(&PropertyKeys.parentStack, inObject: self)
}
set {
guard self.parentContext == nil else {
return
}
cs_setAssociatedWeakObject(
newValue,
forKey: &PropertyKeys.parentStack,
inObject: self
)
}
}
@nonobjc
internal static func rootSavingContextForCoordinator(coordinator: NSPersistentStoreCoordinator) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
context.undoManager = nil
context.setupForCoreStoreWithContextName("com.corestore.rootcontext")
#if os(iOS) || os(OSX)
context.observerForDidImportUbiquitousContentChangesNotification = NotificationObserver(
notificationName: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
object: coordinator,
closure: { [weak context] (note) -> Void in
context?.performBlock { () -> Void in
let updatedObjectIDs = (note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObjectID>) ?? []
for objectID in updatedObjectIDs {
context?.objectWithID(objectID).willAccessValueForKey(nil)
}
context?.mergeChangesFromContextDidSaveNotification(note)
}
}
)
#endif
return context
}
@nonobjc
internal static func mainContextForRootContext(rootContext: NSManagedObjectContext) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.parentContext = rootContext
context.mergePolicy = NSRollbackMergePolicy
context.undoManager = nil
context.setupForCoreStoreWithContextName("com.corestore.maincontext")
context.observerForDidSaveNotification = NotificationObserver(
notificationName: NSManagedObjectContextDidSaveNotification,
object: rootContext,
closure: { [weak context] (note) -> Void in
guard let rootContext = note.object as? NSManagedObjectContext,
let context = context else {
return
}
let mergeChanges = { () -> Void in
let updatedObjects = (note.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? []
for object in updatedObjects {
context.objectWithID(object.objectID).willAccessValueForKey(nil)
}
context.mergeChangesFromContextDidSaveNotification(note)
}
if rootContext.isSavingSynchronously == true {
context.performBlockAndWait(mergeChanges)
}
else {
context.performBlock(mergeChanges)
}
}
)
return context
}
// MARK: Private
private struct PropertyKeys {
static var parentStack: Void?
static var observerForDidSaveNotification: Void?
static var observerForDidImportUbiquitousContentChangesNotification: Void?
}
@nonobjc
private var observerForDidSaveNotification: NotificationObserver? {
get {
return cs_getAssociatedObjectForKey(
&PropertyKeys.observerForDidSaveNotification,
inObject: self
)
}
set {
cs_setAssociatedRetainedObject(
newValue,
forKey: &PropertyKeys.observerForDidSaveNotification,
inObject: self
)
}
}
@nonobjc
private var observerForDidImportUbiquitousContentChangesNotification: NotificationObserver? {
get {
return cs_getAssociatedObjectForKey(
&PropertyKeys.observerForDidImportUbiquitousContentChangesNotification,
inObject: self
)
}
set {
cs_setAssociatedRetainedObject(
newValue,
forKey: &PropertyKeys.observerForDidImportUbiquitousContentChangesNotification,
inObject: self
)
}
}
}
| mit |
google/swift-benchmark | Tests/BenchmarkTests/BenchmarkSettingTests.swift | 1 | 6590 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import Benchmark
final class BenchmarkSettingTests: XCTestCase {
func assertNumberOfIterations(
suite: BenchmarkSuite,
counts expected: [Int],
cli: [BenchmarkSetting],
customDefaults: [BenchmarkSetting] = []
) throws {
var settings: [BenchmarkSetting] = [Format(.none), Quiet(true)]
settings.append(contentsOf: cli)
var runner = BenchmarkRunner(
suites: [suite], settings: settings, customDefaults: customDefaults)
try runner.run()
XCTAssertEqual(runner.results.count, expected.count)
let counts = Array(
runner.results.map { result in
result.measurements.count
})
XCTAssertEqual(counts, expected)
}
func testDefaultSetting() throws {
let suite = BenchmarkSuite(name: "Test") { suite in
suite.benchmark("a") {}
suite.benchmark("b") {}
}
try assertNumberOfIterations(
suite: suite,
counts: [1_000_000, 1_000_000],
cli: [])
}
func testSuiteSetting() throws {
let suite = BenchmarkSuite(name: "Test", settings: Iterations(42)) { suite in
suite.benchmark("a") {}
suite.benchmark("b") {}
}
try assertNumberOfIterations(
suite: suite,
counts: [42, 42],
cli: [])
}
func testBenchmarkSetting() throws {
let suite = BenchmarkSuite(name: "Test") { suite in
suite.benchmark("a") {}
suite.benchmark("b", settings: Iterations(42)) {}
}
try assertNumberOfIterations(
suite: suite,
counts: [1_000_000, 42],
cli: [])
}
func testBenchmarkSettingOverridesSuiteSetting() throws {
let suite = BenchmarkSuite(name: "Test", settings: Iterations(42)) { suite in
suite.benchmark("a") {}
suite.benchmark("b", settings: Iterations(21)) {}
}
try assertNumberOfIterations(
suite: suite,
counts: [42, 21],
cli: [])
}
func testCliSetting() throws {
let suite = BenchmarkSuite(name: "Test") { suite in
suite.benchmark("a") {}
suite.benchmark("b") {}
}
try assertNumberOfIterations(
suite: suite,
counts: [1, 1],
cli: [Iterations(1)])
}
func testCliOverridesSuiteSetting() throws {
let suite = BenchmarkSuite(name: "Test", settings: Iterations(2)) { suite in
suite.benchmark("a") {}
suite.benchmark("b") {}
}
try assertNumberOfIterations(
suite: suite,
counts: [1, 1],
cli: [Iterations(1)])
}
func testCliOverridesBenchmarkSetting() throws {
let suite = BenchmarkSuite(name: "Test") { suite in
suite.benchmark("a") {}
suite.benchmark("b", settings: Iterations(2)) {}
}
try assertNumberOfIterations(
suite: suite,
counts: [1, 1],
cli: [Iterations(1)])
}
func testCliOverridesBenchmarkAndSuiteSetting() throws {
let suite = BenchmarkSuite(name: "Test", settings: Iterations(2)) { suite in
suite.benchmark("a") {}
suite.benchmark("b", settings: Iterations(3)) {}
}
try assertNumberOfIterations(
suite: suite,
counts: [1, 1],
cli: [Iterations(1)])
}
func testCustomDefaults() throws {
let suite = BenchmarkSuite(name: "Test") { suite in
suite.benchmark("a") {}
suite.benchmark("b") {}
}
try assertNumberOfIterations(
suite: suite,
counts: [1, 1],
cli: [],
customDefaults: [Iterations(1)])
}
func testCustomDafaultsOverridenBySuite() throws {
let suite = BenchmarkSuite(name: "Test", settings: Iterations(3)) { suite in
suite.benchmark("a") {}
suite.benchmark("b") {}
}
try assertNumberOfIterations(
suite: suite,
counts: [3, 3],
cli: [],
customDefaults: [Iterations(1)])
}
func testCustomDafaultsOverridenByBenchmark() throws {
let suite = BenchmarkSuite(name: "Test", settings: Iterations(3)) { suite in
suite.benchmark("a") {}
suite.benchmark("b", settings: Iterations(4)) {}
}
try assertNumberOfIterations(
suite: suite,
counts: [3, 4],
cli: [],
customDefaults: [Iterations(1)])
}
func testCustomDafaultsOverridenByCli() throws {
let suite = BenchmarkSuite(name: "Test", settings: Iterations(3)) { suite in
suite.benchmark("a") {}
suite.benchmark("b", settings: Iterations(4)) {}
}
try assertNumberOfIterations(
suite: suite,
counts: [5, 5],
cli: [Iterations(5)],
customDefaults: [Iterations(1)])
}
static var allTests = [
("testDefaultSetting", testDefaultSetting),
("testSuiteSetting", testSuiteSetting),
("testBenchmarkSetting", testBenchmarkSetting),
("testBenchmarkSettingOverridesSuiteSetting", testBenchmarkSettingOverridesSuiteSetting),
("testCliSetting", testCliSetting),
("testCliOverridesSuiteSetting", testCliOverridesSuiteSetting),
("testCliOverridesBenchmarkSetting", testCliOverridesBenchmarkSetting),
("testCliOverridesBenchmarkAndSuiteSetting", testCliOverridesBenchmarkAndSuiteSetting),
("testCustomDefaults", testCustomDefaults),
("testCustomDafaultsOverridenBySuite", testCustomDafaultsOverridenBySuite),
("testCustomDafaultsOverridenByBenchmark", testCustomDafaultsOverridenByBenchmark),
("testCustomDafaultsOverridenByCli", testCustomDafaultsOverridenByCli),
]
}
| apache-2.0 |
awind/Pixel | Pixel/User.swift | 1 | 614 | //
// User.swift
// Pixel
//
// Created by SongFei on 15/12/9.
// Copyright © 2015年 SongFei. All rights reserved.
//
import Foundation
class User: NSObject {
var id: Int
var username: String
var avatar: String
var email: String?
var coverURL: String?
var photosCount: Int?
var friendsCount: Int?
var followersCount: Int?
var birthday: String?
var location: String?
var domain: String?
var following = false
init(id: Int, username: String, avatar: String) {
self.id = id
self.username = username
self.avatar = avatar
}
}
| apache-2.0 |
hadibadjian/GAlileo | subscriptions2/Subscriotions2/SwitchTableViewCell.swift | 1 | 396 | // Copyright © 2016 HB. All rights reserved.
class SwitchTableViewCell: UITableViewCell {
@IBOutlet weak var enabledSwitch: UISwitch!
var type: String?
@IBAction func switchPressed(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName(
type ?? "NON" + "Changed",
object: nil,
userInfo: ["enabled": enabledSwitch.on])
}
}
import UIKit
| mit |
panjinqiang11/Swift-WeiBo | WeiBo/WeiBo/Class/View/OAuth/CommonTool.swift | 1 | 757 | //
// CommonTool.swift
// WeiBo
//
// Created by 潘金强 on 16/7/12.
// Copyright © 2016年 潘金强. All rights reserved.
//
import UIKit
// 切换根视图控制器通知名
let SwitchRootVCNotification = "SwitchRootVCNotification"
let ScreenWidth = UIScreen.mainScreen().bounds.size.width
let SreenHeight = UIScreen.mainScreen().bounds.size.height
//随机生成颜色
func RGB(red: CGFloat,green: CGFloat, blue :CGFloat) -> UIColor{
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func RandomColor() -> UIColor{
let red = random() % 256
let green = random() % 256
let blue = random() % 256
return RGB(CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255)
} | mit |
Ben21hao/edx-app-ios-enterprise-new | Test/EnrollmentManagerTests.swift | 2 | 1268 | //
// EnrollmentManagerTests.swift
// edX
//
// Created by Akiva Leffert on 12/26/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
@testable import edX
class EnrollmentManagerTests : XCTestCase {
func testEnrollmentsLoginLogout() {
let enrollments = [
UserCourseEnrollment(course: OEXCourse.freshCourse()),
UserCourseEnrollment(course: OEXCourse.freshCourse())
]
let environment = TestRouterEnvironment()
environment.mockNetworkManager.interceptWhenMatching({_ in true }) {
return (nil, enrollments)
}
let manager = EnrollmentManager(interface: nil, networkManager: environment.networkManager, config: environment.config)
let feed = manager.feed
// starts empty
XCTAssertNil(feed.output.value)
// Log in. Enrollments should load
environment.logInTestUser()
feed.refresh()
stepRunLoop()
waitForStream(feed.output)
XCTAssertEqual(feed.output.value!!.count, enrollments.count)
// Log out. Now enrollments should be cleared
environment.session.closeAndClearSession()
XCTAssertNil(feed.output.value!)
}
}
| apache-2.0 |
brentdax/swift | test/decl/func/operator_suggestions.swift | 16 | 1520 | // RUN: %target-typecheck-verify-swift
_ = 1..<1 // OK
_ = 1…1 // expected-error {{use of unresolved operator '…'; did you mean '...'?}} {{6-9=...}}
_ = 1….1 // expected-error {{use of unresolved operator '…'; did you mean '...'?}} {{6-9=...}}
_ = 1.…1 // expected-error {{use of unresolved operator '.…'; did you mean '...'?}} {{6-10=...}}
_ = 1…<1 // expected-error {{use of unresolved operator '…<'; did you mean '..<'?}} {{6-10=..<}}
_ = 1..1 // expected-error {{use of unresolved operator '..'; did you mean '...'?}} {{6-8=...}}
_ = 1....1 // expected-error {{use of unresolved operator '....'; did you mean '...'?}} {{6-10=...}}
_ = 1...<1 // expected-error {{use of unresolved operator '...<'; did you mean '..<'?}} {{6-10=..<}}
_ = 1....<1 // expected-error {{use of unresolved operator '....<'; did you mean '..<'?}} {{6-11=..<}}
var i = 1
i++ // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}}
++i // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}}
i-- // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}}
--i // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}}
var d = 1.0
d++ // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}}
++d // expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}}
d-- // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}}
--d // expected-error {{use of unresolved operator '--'; did you mean '-= 1'?}}
| apache-2.0 |
ja-mes/experiments | iOS/RetroCalculator/RetroCalculator/ViewController.swift | 1 | 3562 | //
// ViewController.swift
// RetroCalculator
//
// Created by James Brown on 8/13/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var outputLbl: UILabel!
var buttonSound: AVAudioPlayer!
enum Operation: String {
case Divide = "/"
case Multiply = "*"
case Subtract = "-"
case Add = "+"
case Empty = "Empty"
}
var currentOperation = Operation.Empty
var runningNumber = ""
var leftValStr = ""
var rightValStr = ""
var result = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "btn", ofType: "wav")
let soundURL = URL(fileURLWithPath: path!)
do {
try buttonSound = AVAudioPlayer(contentsOf: soundURL)
buttonSound.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
outputLbl.text = "0"
}
@IBAction func numberPressed(sender: UIButton) {
playSound()
runningNumber += "\(sender.tag)"
outputLbl.text = runningNumber
}
@IBAction func onDividePress(sender: AnyObject) {
processOperation(operation: .Divide)
}
@IBAction func onMultiplyPress(sender: AnyObject) {
processOperation(operation: .Multiply)
}
@IBAction func onSubtractPress(sender: AnyObject) {
processOperation(operation: .Subtract)
}
@IBAction func onAddPress(sender: AnyObject) {
processOperation(operation: .Add)
}
@IBAction func onEqualPressed(sender: AnyObject) {
processOperation(operation: currentOperation)
}
@IBAction func clearButtonPressed(_ sender: AnyObject) {
playSound()
currentOperation = Operation.Empty
runningNumber = ""
result = ""
leftValStr = ""
rightValStr = ""
outputLbl.text = "0"
}
func playSound() {
if buttonSound.isPlaying {
buttonSound.stop()
}
buttonSound.play()
}
func processOperation(operation: Operation) {
playSound()
if currentOperation != Operation.Empty {
// A user selected a operator, but then selected another operator without first entering a number
if runningNumber != "" {
rightValStr = runningNumber
runningNumber = ""
if currentOperation == Operation.Multiply {
result = "\(Double(leftValStr)! * Double(rightValStr)!)"
} else if currentOperation == Operation.Divide {
result = "\(Double(leftValStr)! / Double(rightValStr)!)"
} else if currentOperation == Operation.Subtract {
result = "\(Double(leftValStr)! - Double(rightValStr)!)"
} else if currentOperation == Operation.Add {
result = "\(Double(leftValStr)! + Double(rightValStr)!)"
}
leftValStr = result
outputLbl.text = result
}
currentOperation = operation
} else {
// This is the first time a operator has been pressed
leftValStr = runningNumber
runningNumber = ""
currentOperation = operation
}
}
}
| mit |
mrmacete/Morte | MorteTests/MorteTests.swift | 1 | 881 | //
// MorteTests.swift
// MorteTests
//
// Created by ftamagni on 16/03/15.
// Copyright (c) 2015 morte. All rights reserved.
//
import UIKit
import XCTest
class MorteTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
jverkoey/FigmaKit | Sources/FigmaKit/Strokes.swift | 1 | 804 | /// A Figma stroke cap.
///
/// "Describes the end caps of vector paths."
public enum StrokeCap: String, Codable {
case none = "NONE"
case round = "ROUND"
case square = "SQUARE"
case lineArrow = "LINE_ARROW"
case triangleArrow = "TRIANGLE_ARROW"
}
/// A Figma stroke join.
///
/// "Describes how corners in vector paths are rendered."
public enum StrokeJoin: String, Codable {
case miter = "MITER"
case bevel = "BEVEL"
case round = "ROUND"
}
/// A Figma stroke align.
///
/// "Position of stroke relative to vector outline."
public enum StrokeAlign: String, Codable {
/// Stroke drawn inside the shape boundary.
case inside = "INSIDE"
/// Stroke drawn outside the shape boundary.
case outside = "OUTSIDE"
/// Stroke drawn along the shape boundary.
case center = "CENTER"
}
| apache-2.0 |
danger/danger-swift | Tests/DangerTests/GitHubTestResources/GitHubBot.swift | 1 | 1269 | public let GitHubBotJSON = """
{
"login": "dependabot-preview[bot]",
"id": 27856297,
"node_id": "MDM6Qm90Mjc4NTYyOTc=",
"avatar_url": "https://avatars3.githubusercontent.com/in/2141?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dependabot-preview%5Bbot%5D",
"html_url": "https://github.com/apps/dependabot-preview",
"followers_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/followers",
"following_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/following{/other_user}",
"gists_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/subscriptions",
"organizations_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/orgs",
"repos_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/repos",
"events_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/events{/privacy}",
"received_events_url": "https://api.github.com/users/dependabot-preview%5Bbot%5D/received_events",
"type": "Bot",
"site_admin": false
}
"""
| mit |
digices-llc/paqure-ios-framework | Paqure/App.swift | 1 | 4360 | //
// App.swift
// Paqure
//
// Created by Linguri Technology on 7/19/16.
// Copyright © 2016 Digices. All rights reserved.
//
import UIKit
class App: NSObject, NSCoding {
// object properties
var id : Int
var name: NSString
var major : Int
var minor : Int
var fix : Int
var copyright : Int
var company: NSString
var update : Int
// initialize in default state
override init() {
self.id = 2
self.name = NSLocalizedString("app_name", comment: "Title representing the public name of the app")
self.major = 0
self.minor = 0
self.fix = 1
self.copyright = 2016
self.company = "Digices, LLC"
self.update = 0
}
// initialize in default state
required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeIntegerForKey("id")
self.name = aDecoder.decodeObjectForKey("name") as! NSString
self.major = aDecoder.decodeIntegerForKey("major")
self.minor = aDecoder.decodeIntegerForKey("minor")
self.fix = aDecoder.decodeIntegerForKey("fix")
self.copyright = aDecoder.decodeIntegerForKey("copyright")
self.company = aDecoder.decodeObjectForKey("company") as! NSString
self.update = aDecoder.decodeIntegerForKey("update")
}
// initialize with a [String:String] dictionary
init(dict: NSDictionary) {
if let id = dict["id"] as? String {
if let idInt = Int(id) {
self.id = idInt
} else {
self.id = 0
}
} else {
self.id = 0
}
if let name = dict["name"] as? String {
self.name = name
} else {
self.name = ""
}
if let major = dict["major"] as? String {
if let majorInt = Int(major) {
self.major = majorInt
} else {
self.major = 0
}
} else {
self.major = 0
}
if let minor = dict["minor"] as? String {
if let minorInt = Int(minor) {
self.minor = minorInt
} else {
self.minor = 0
}
} else {
self.minor = 0
}
if let fix = dict["fix"] as? String {
if let fixInt = Int(fix) {
self.fix = fixInt
} else {
self.fix = 0
}
} else {
self.fix = 0
}
if let copyright = dict["copyright"] as? String {
if let copyrightInt = Int(copyright) {
self.copyright = copyrightInt
} else {
self.copyright = 0
}
} else {
self.copyright = 0
}
if let company = dict["company"] as? String {
self.company = company
} else {
self.company = ""
}
if let update = dict["update"] as? String {
if let updateInt = Int(update) {
self.update = updateInt
} else {
self.update = 0
}
} else {
self.update = 0
}
}
// NSCoding compliance when saving objects
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(self.id, forKey: "id")
aCoder.encodeObject(self.name, forKey: "name")
aCoder.encodeInteger(self.major, forKey: "major")
aCoder.encodeInteger(self.minor, forKey: "minor")
aCoder.encodeInteger(self.fix, forKey: "fix")
aCoder.encodeInteger(self.copyright, forKey: "copyright")
aCoder.encodeObject(self.company, forKey: "company")
aCoder.encodeInteger(self.update, forKey: "update")
}
// a tap to enable appending an HTTP GET string to a URL
func getSuffix() -> String {
return "id=\(self.id)&name=\(self.name)&major=\(self.major)&minor=\(self.minor)&fix=\(self.fix)©right=\(self.copyright)&company=\(self.company)&update=\(self.update)"
}
// return NSURLSession compliant HTTP Body header for object
func encodedPostBody() -> NSData {
let body = self.getSuffix()
return body.dataUsingEncoding(NSUTF8StringEncoding)! as NSData
}
}
| bsd-3-clause |
finder39/Swimgur | Swimgur/Controllers/GalleryItemView/Cells/ImgurTextCell.swift | 1 | 2078 | //
// ImgurTextCell.swift
// Swimgur
//
// Created by Joseph Neuman on 11/2/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import Foundation
import UIKit
class ImgurTextCell: UITableViewCell {
@IBOutlet var imgurText:UITextView!
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
func setup() {
imgurText.textColor = UIColorEXT.TextColor()
imgurText.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.RGBColor(red: 51, green: 102, blue: 187)]
}
override func prepareForReuse() {
super.prepareForReuse()
imgurText.text = nil
// bug fix for text maintaining old links
var newImgurTextView = UITextView()
newImgurTextView.font = imgurText.font
newImgurTextView.backgroundColor = imgurText.backgroundColor
newImgurTextView.dataDetectorTypes = imgurText.dataDetectorTypes
newImgurTextView.selectable = imgurText.selectable
newImgurTextView.editable = imgurText.editable
newImgurTextView.scrollEnabled = imgurText.scrollEnabled
newImgurTextView.textColor = imgurText.textColor
newImgurTextView.linkTextAttributes = imgurText.linkTextAttributes
newImgurTextView.setTranslatesAutoresizingMaskIntoConstraints(false)
imgurText.removeFromSuperview()
self.addSubview(newImgurTextView)
imgurText = newImgurTextView
let top = NSLayoutConstraint(item: newImgurTextView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0)
let bottom = NSLayoutConstraint(item: newImgurTextView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0)
let leading = NSLayoutConstraint(item: newImgurTextView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 0)
let trailing = NSLayoutConstraint(item: newImgurTextView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: 0)
self.addConstraints([top, bottom, leading, trailing])
}
} | mit |
hooman/swift | test/Generics/concrete_same_type_versus_anyobject.swift | 4 | 1614 | // RUN: %target-typecheck-verify-swift
// RUN: not %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s
struct S {}
class C {}
struct G1<T : AnyObject> {}
// CHECK-LABEL: Generic signature: <T where T == S>
extension G1 where T == S {}
// expected-error@-1 {{'T' requires that 'S' be a class type}}
// expected-note@-2 {{same-type constraint 'T' == 'S' implied here}}
// CHECK-LABEL: Generic signature: <T where T == C>
extension G1 where T == C {}
struct G2<U> {}
// CHECK-LABEL: Generic signature: <U where U == S>
extension G2 where U == S, U : AnyObject {}
// expected-error@-1 {{'U' requires that 'S' be a class type}}
// expected-note@-2 {{same-type constraint 'U' == 'S' implied here}}
// expected-note@-3 {{constraint 'U' : 'AnyObject' implied here}}
// CHECK-LABEL: Generic signature: <U where U == C>
extension G2 where U == C, U : AnyObject {}
// expected-warning@-1 {{redundant constraint 'U' : 'AnyObject'}}
// expected-note@-2 {{constraint 'U' : 'AnyObject' implied here}}
// CHECK-LABEL: Generic signature: <U where U : C>
extension G2 where U : C, U : AnyObject {}
// expected-warning@-1 {{redundant constraint 'U' : 'AnyObject'}}
// expected-note@-2 {{constraint 'U' : 'AnyObject' implied here}}
// Explicit AnyObject conformance vs derived same-type
protocol P {
associatedtype A where A == C
}
// CHECK-LABEL: Generic signature: <T where T : P>
func explicitAnyObjectIsRedundant<T : P>(_: T) where T.A : AnyObject {}
// expected-warning@-1 {{redundant constraint 'T.A' : 'AnyObject'}}
// expected-note@-2 {{constraint 'T.A' : 'AnyObject' implied here}}
| apache-2.0 |
col/iReSign | iReSignKit/Logger.swift | 1 | 1072 | //
// Logger.swift
// iReSign
//
// Created by Colin Harris on 15/10/15.
// Copyright © 2015 Colin Harris. All rights reserved.
//
import Foundation
public enum LogLevel: Int {
case Debug = 1
case Info = 2
case Warn = 3
case Error = 4
}
public class Logger {
static let sharedInstance = Logger()
var logLevel: LogLevel = .Info
public class func setLogLevel(level: LogLevel) {
sharedInstance.logLevel = level
}
public class func debug(message: String) {
sharedInstance.log(.Debug, message: message)
}
public class func info(message: String) {
sharedInstance.log(.Info, message: message)
}
public class func warn(message: String) {
sharedInstance.log(.Warn, message: message)
}
public class func error(message: String) {
sharedInstance.log(.Error, message: message)
}
public func log(level: LogLevel, message: String) {
if level.rawValue >= logLevel.rawValue {
print(message)
}
}
} | mit |
lorentey/swift | test/ModuleInterface/stdlib.swift | 20 | 403 | // RUN: %target-swift-frontend -typecheck -emit-module-interface-path - -parse-stdlib %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-module-interface-path - -emit-module -o /dev/null -parse-stdlib %s | %FileCheck %s
// CHECK-NOT: import Builtin
// CHECK: func test() {
// CHECK-NEXT: Builtin.sizeof
// CHECK-NEXT: {{^}$}}
@inlinable public func test() {
Builtin.sizeof(Builtin.Int8.self)
}
| apache-2.0 |
timd/ProiOSTableCollectionViews | Ch08/MVVM/MVVM/ViewController.swift | 1 | 1748 | //
// ViewController.swift
// MVVM
//
// Created by Tim on 28/10/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView!
var tableData: [Contact] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func setupData() {
for index in 1...10 {
let contact = Contact(name: "Name \(index)", number: "\(index)", notes: "The notes for contact \(index)")
tableData.append(contact)
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell
let contact = tableData[indexPath.row]
cell.contact = contact
return cell
}
}
| mit |
joshoconnor89/BoardView_DragNDrop | KDDragAndDropCollectionViews/ViewController.swift | 1 | 4944 | //
// ViewController.swift
// KDDragAndDropCollectionViews
//
// Created by Michael Michailidis on 10/04/2015.
// Copyright (c) 2015 Karmadust. All rights reserved.
//
import UIKit
class DataItem : Equatable {
var indexes : String = ""
var colour : UIColor = UIColor.clear
init(indexes : String, colour : UIColor) {
self.indexes = indexes
self.colour = colour
}
}
func ==(lhs: DataItem, rhs: DataItem) -> Bool {
return lhs.indexes == rhs.indexes && lhs.colour == rhs.colour
}
class ViewController: UIViewController, KDDragAndDropCollectionViewDataSource {
@IBOutlet weak var firstCollectionView: UICollectionView!
@IBOutlet weak var secondCollectionView: UICollectionView!
@IBOutlet weak var thirdCollectionView: UICollectionView!
var data : [[DataItem]] = [[DataItem]]()
var dragAndDropManager : KDDragAndDropManager?
override func viewDidLoad() {
super.viewDidLoad()
let colours : [UIColor] = [
UIColor(red: 53.0/255.0, green: 102.0/255.0, blue: 149.0/255.0, alpha: 1.0),
UIColor(red: 177.0/255.0, green: 88.0/255.0, blue: 39.0/255.0, alpha: 1.0),
UIColor(red: 138.0/255.0, green: 149.0/255.0, blue: 86.0/255.0, alpha: 1.0)
]
for i in 0...2 {
var items = [DataItem]()
for j in 0...20 {
let dataItem = DataItem(indexes: String(i) + ":" + String(j), colour: colours[i])
items.append(dataItem)
}
data.append(items)
}
self.dragAndDropManager = KDDragAndDropManager(canvas: self.view, collectionViews: [firstCollectionView, secondCollectionView, thirdCollectionView])
}
// MARK : UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data[collectionView.tag].count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ColorCell
let dataItem = data[collectionView.tag][indexPath.item]
cell.label.text = String(indexPath.item) + "\n\n" + dataItem.indexes
cell.backgroundColor = dataItem.colour
cell.isHidden = false
if let kdCollectionView = collectionView as? KDDragAndDropCollectionView {
if let draggingPathOfCellBeingDragged = kdCollectionView.draggingPathOfCellBeingDragged {
if draggingPathOfCellBeingDragged.item == indexPath.item {
cell.isHidden = true
}
}
}
return cell
}
// MARK : KDDragAndDropCollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject {
return data[collectionView.tag][indexPath.item]
}
func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: IndexPath) -> Void {
if let di = dataItem as? DataItem {
data[collectionView.tag].insert(di, at: indexPath.item)
}
}
func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath : IndexPath) -> Void {
data[collectionView.tag].remove(at: indexPath.item)
}
func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to : IndexPath) -> Void {
let fromDataItem: DataItem = data[collectionView.tag][from.item]
data[collectionView.tag].remove(at: from.item)
data[collectionView.tag].insert(fromDataItem, at: to.item)
}
func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath? {
if let candidate : DataItem = dataItem as? DataItem {
for item : DataItem in data[collectionView.tag] {
if candidate == item {
let position = data[collectionView.tag].index(of: item)! // ! if we are inside the condition we are guaranteed a position
let indexPath = IndexPath(item: position, section: 0)
return indexPath
}
}
}
return nil
}
}
| mit |
moriturus/Concurrent | Concurrent/Channel.swift | 1 | 2104 | //
// Channel.swift
// Concurrent
//
// Created by moriturus on 8/12/14.
// Copyright (c) 2014-2015 moriturus. All rights reserved.
//
public protocol ChannelType : Sendable, Receivable {
typealias S : Sendable
typealias R : Receivable
var sender : S { get }
var receiver : R { get }
}
public class ProtoChannel<T, D : Data, S : Sendable, R : Receivable where D.T == T, S.T == T, S.D == D, R.T == T, R.D == D> : ChannelType {
/// sender object
public private(set) var sender : S
/// receiver object
public private(set) var receiver : R
public init(_ sender : S, _ receiver : R) {
self.sender = sender
self.receiver = receiver
}
public convenience required init(_ storage: D) {
let s = S(storage)
let r = R(storage)
self.init(s,r)
}
public func send(value: T) {
sender.send(value)
}
public func receive() -> T {
return receiver.receive()
}
}
public class DataTypeReplaceableChannel<T, D: Data where D.T == T> : ProtoChannel<T, D, Sender<D>, Receiver<D>> {
public typealias S = Sender<D>
public typealias R = Receiver<D>
public required init(_ storage: D) {
let s = S(storage)
let r = R(s)
super.init(s, r)
}
}
/**
Channel class
*/
public class Channel<T> : DataTypeReplaceableChannel<T, SafeQueue<T>> {
public typealias D = SafeQueue<T>
public required init(_ storage: D) {
super.init(storage)
}
public convenience init() {
let d = D()
self.init(d)
}
}
public class StackChannel<T> : DataTypeReplaceableChannel<T, SafeStack<T>> {
public typealias D = SafeStack<T>
public required init(_ storage: D) {
super.init(storage)
}
public convenience init() {
let d = D()
self.init(d)
}
}
| mit |
gregomni/swift | test/SILGen/check_executor.swift | 9 | 3186 | // RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -disable-availability-checking -enable-actor-data-race-checks | %FileCheck --enable-var-scope %s --check-prefix=CHECK-RAW
// RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -disable-availability-checking -enable-actor-data-race-checks > %t.sil
// RUN: %target-sil-opt -enable-sil-verify-all %t.sil -lower-hop-to-actor | %FileCheck --enable-var-scope %s --check-prefix=CHECK-CANONICAL
// REQUIRES: concurrency
import Swift
import _Concurrency
// CHECK-RAW-LABEL: sil [ossa] @$s4test11onMainActoryyF
// CHECK-RAW: extract_executor [[MAIN_ACTOR:%.*]] : $MainActor
// CHECK-CANONICAL-LABEL: sil [ossa] @$s4test11onMainActoryyF
// CHECK-CANONICAL: function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF
@MainActor public func onMainActor() { }
// CHECK-CANONICAL-LABEL: sil [ossa] @$s4test17onMainActorUnsafeyyF
// CHECK-CANONICAL: function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF
@preconcurrency @MainActor public func onMainActorUnsafe() { }
func takeClosure(_ fn: @escaping () -> Int) { }
@preconcurrency func takeUnsafeMainActorClosure(_ fn: @MainActor @escaping () -> Int) { }
public actor MyActor {
var counter = 0
// CHECK-RAW-LABEL: sil private [ossa] @$s4test7MyActorC10getUpdaterSiycyFSiycfU_
// CHECK-RAW: extract_executor [[ACTOR:%.*]] : $MyActor
// CHECK-CANONICAL-LABEL: sil private [ossa] @$s4test7MyActorC10getUpdaterSiycyFSiycfU_
// CHECK-CANONICAL: function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF
public func getUpdater() -> (() -> Int) {
return {
self.counter = self.counter + 1
return self.counter
}
}
// CHECK-RAW-LABEL: sil private [ossa] @$s4test7MyActorC0A10UnsafeMainyyFSiyScMYccfU_
// CHECK-RAW: _checkExpectedExecutor
// CHECK-RAW: onMainActor
// CHECK-RAW: return
public func testUnsafeMain() {
takeUnsafeMainActorClosure {
onMainActor()
return 5
}
}
// CHECK-CANONICAL-LABEL: sil private [ossa] @$s4test7MyActorC0A13LocalFunctionyyF5localL_SiyF : $@convention(thin) (@guaranteed MyActor) -> Int
// CHECK-CANONICAL: [[CAPTURE:%.*]] = copy_value %0 : $MyActor
// CHECK-CANONICAL-NEXT: [[BORROWED_CAPTURE:%.*]] = begin_borrow [[CAPTURE]] : $MyActor
// CHECK-CANONICAL-NEXT: [[EXECUTOR:%.*]] = builtin "buildDefaultActorExecutorRef"<MyActor>([[BORROWED_CAPTURE]] : $MyActor) : $Builtin.Executor
// CHECK-CANONICAL-NEXT: [[EXECUTOR_DEP:%.*]] = mark_dependence [[EXECUTOR]] : $Builtin.Executor on [[BORROWED_CAPTURE]] : $MyActor
// CHECK-CANONICAL: [[CHECK_FN:%.*]] = function_ref @$ss22_checkExpectedExecutor14_filenameStart01_D6Length01_D7IsASCII5_line9_executoryBp_BwBi1_BwBetF : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Executor) -> ()
// CHECK-CANONICAL-NEXT: apply [[CHECK_FN]]({{.*}}, [[EXECUTOR_DEP]])
public func testLocalFunction() {
func local() -> Int {
return counter
}
print(local())
}
}
| apache-2.0 |
robertofrontado/RxSocialConnect-iOS | Sources/Core/Apis/TwitterApi.swift | 1 | 798 | //
// TwitterApi.swift
// RxSocialConnect
//
// Created by Roberto Frontado on 5/19/16.
// Copyright © 2016 Roberto Frontado. All rights reserved.
//
import OAuthSwift
open class TwitterApi: ProviderOAuth1 {
open var consumerKey: String
open var consumerSecret: String
open var callbackUrl: URL
open var requestTokenUrl: String = "https://api.twitter.com/oauth/request_token"
open var authorizeUrl: String = "https://api.twitter.com/oauth/authorize"
open var accessTokenUrl: String = "https://api.twitter.com/oauth/access_token"
required public init(consumerKey: String, consumerSecret: String, callbackUrl: URL) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.callbackUrl = callbackUrl
}
}
| apache-2.0 |
stuartjmoore/D-D | D&D/Models/Class.swift | 1 | 738 | //
// Class.swift
// D&D
//
// Created by Moore, Stuart on 2/13/15.
// Copyright (c) 2015 Stuart Moore. All rights reserved.
//
struct Class {
enum Name {
case Barbarian, Bard, Cleric, Druid, Fighter, Monk, Paladin, Ranger, Rogue, Sorcerer, Warlock, Wizard
}
unowned let character: Player
let name: Name
let hitDie: Die
var level: Int
var hitPoints: Int {
let mod = character.abilities[.Constitution].modifier
let first = hitDie.sides + mod
let rest = roundup((hitDie.sides + 1) / 2) + mod
return first + (rest * (level - 1))
}
var constitution: Int {
return level * character.abilities[.Constitution].modifier
}
}
| unlicense |
parkera/swift-corelibs-foundation | Foundation/URLSession/NativeProtocol.swift | 1 | 26009 | // Foundation/URLSession/NativeProtocol.swift - NSURLSession & libcurl
//
// 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 the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// This file has the common implementation of Native protocols like HTTP,FTP,Data
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: NSURLSession.swift
///
// -----------------------------------------------------------------------------
import CoreFoundation
import Dispatch
internal let enableLibcurlDebugOutput: Bool = {
return ProcessInfo.processInfo.environment["URLSessionDebugLibcurl"] != nil
}()
internal let enableDebugOutput: Bool = {
return ProcessInfo.processInfo.environment["URLSessionDebug"] != nil
}()
internal class _NativeProtocol: URLProtocol, _EasyHandleDelegate {
internal var easyHandle: _EasyHandle!
internal lazy var tempFileURL: URL = {
let fileName = NSTemporaryDirectory() + NSUUID().uuidString + ".tmp"
_ = FileManager.default.createFile(atPath: fileName, contents: nil)
return URL(fileURLWithPath: fileName)
}()
public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
self.internalState = .initial
super.init(request: task.originalRequest!, cachedResponse: cachedResponse, client: client)
self.task = task
self.easyHandle = _EasyHandle(delegate: self)
}
public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
self.internalState = .initial
super.init(request: request, cachedResponse: cachedResponse, client: client)
self.easyHandle = _EasyHandle(delegate: self)
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
resume()
}
override func stopLoading() {
if task?.state == .suspended {
suspend()
} else {
self.internalState = .transferFailed
guard let error = self.task?.error else { fatalError() }
completeTask(withError: error)
}
}
var internalState: _InternalState {
// We manage adding / removing the easy handle and pausing / unpausing
// here at a centralized place to make sure the internal state always
// matches up with the state of the easy handle being added and paused.
willSet {
if !internalState.isEasyHandlePaused && newValue.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
if internalState.isEasyHandleAddedToMultiHandle && !newValue.isEasyHandleAddedToMultiHandle {
task?.session.remove(handle: easyHandle)
}
}
didSet {
if !oldValue.isEasyHandleAddedToMultiHandle && internalState.isEasyHandleAddedToMultiHandle {
task?.session.add(handle: easyHandle)
}
if oldValue.isEasyHandlePaused && !internalState.isEasyHandlePaused {
fatalError("Need to solve pausing receive.")
}
}
}
func didReceive(data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(var ts) = internalState else {
fatalError("Received body data, but no transfer in progress.")
}
if let response = validateHeaderComplete(transferState:ts) {
ts.response = response
}
notifyDelegate(aboutReceivedData: data)
internalState = .transferInProgress(ts.byAppending(bodyData: data))
return .proceed
}
func validateHeaderComplete(transferState: _TransferState) -> URLResponse? {
guard transferState.isHeaderComplete else {
fatalError("Received body data, but the header is not complete, yet.")
}
return nil
}
fileprivate func notifyDelegate(aboutReceivedData data: Data) {
guard let t = self.task else {
fatalError("Cannot notify")
}
if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!),
let dataDelegate = delegate as? URLSessionDataDelegate,
let task = self.task as? URLSessionDataTask {
// Forward to the delegate:
guard let s = self.task?.session as? URLSession else {
fatalError()
}
s.delegateQueue.addOperation {
dataDelegate.urlSession(s, dataTask: task, didReceive: data)
}
} else if case .taskDelegate(let delegate) = t.session.behaviour(for: self.task!),
let downloadDelegate = delegate as? URLSessionDownloadDelegate,
let task = self.task as? URLSessionDownloadTask {
guard let s = self.task?.session as? URLSession else {
fatalError()
}
let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL)
_ = fileHandle.seekToEndOfFile()
fileHandle.write(data)
task.countOfBytesReceived += Int64(data.count)
s.delegateQueue.addOperation {
downloadDelegate.urlSession(s, downloadTask: task, didWriteData: Int64(data.count), totalBytesWritten: task.countOfBytesReceived,
totalBytesExpectedToWrite: task.countOfBytesExpectedToReceive)
}
}
}
fileprivate func notifyDelegate(aboutUploadedData count: Int64) {
guard let task = self.task as? URLSessionUploadTask,
let session = self.task?.session as? URLSession,
case .taskDelegate(let delegate) = session.behaviour(for: task) else { return }
task.countOfBytesSent += count
session.delegateQueue.addOperation {
delegate.urlSession(session, task: task, didSendBodyData: count,
totalBytesSent: task.countOfBytesSent, totalBytesExpectedToSend: task.countOfBytesExpectedToSend)
}
}
func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action {
NSRequiresConcreteImplementation()
}
func fill(writeBuffer buffer: UnsafeMutableBufferPointer<Int8>) -> _EasyHandle._WriteBufferResult {
guard case .transferInProgress(let ts) = internalState else {
fatalError("Requested to fill write buffer, but transfer isn't in progress.")
}
guard let source = ts.requestBodySource else {
fatalError("Requested to fill write buffer, but transfer state has no body source.")
}
switch source.getNextChunk(withLength: buffer.count) {
case .data(let data):
copyDispatchData(data, infoBuffer: buffer)
let count = data.count
assert(count > 0)
notifyDelegate(aboutUploadedData: Int64(count))
return .bytes(count)
case .done:
return .bytes(0)
case .retryLater:
// At this point we'll try to pause the easy handle. The body source
// is responsible for un-pausing the handle once data becomes
// available.
return .pause
case .error:
return .abort
}
}
func transferCompleted(withError error: NSError?) {
// At this point the transfer is complete and we can decide what to do.
// If everything went well, we will simply forward the resulting data
// to the delegate. But in case of redirects etc. we might send another
// request.
guard case .transferInProgress(let ts) = internalState else {
fatalError("Transfer completed, but it wasn't in progress.")
}
guard let request = task?.currentRequest else {
fatalError("Transfer completed, but there's no current request.")
}
guard error == nil else {
internalState = .transferFailed
failWith(error: error!, request: request)
return
}
if let response = task?.response {
var transferState = ts
transferState.response = response
}
guard let response = ts.response else {
fatalError("Transfer completed, but there's no response.")
}
internalState = .transferCompleted(response: response, bodyDataDrain: ts.bodyDataDrain)
let action = completionAction(forCompletedRequest: request, response: response)
switch action {
case .completeTask:
completeTask()
case .failWithError(let errorCode):
internalState = .transferFailed
let error = NSError(domain: NSURLErrorDomain, code: errorCode,
userInfo: [NSLocalizedDescriptionKey: "Completion failure"])
failWith(error: error, request: request)
case .redirectWithRequest(let newRequest):
redirectFor(request: newRequest)
}
}
func redirectFor(request: URLRequest) {
NSRequiresConcreteImplementation()
}
func completeTask() {
guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete.")
}
task?.response = response
// We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled.
easyHandle.timeoutTimer = nil
// because we deregister the task with the session on internalState being set to taskCompleted
// we need to do the latter after the delegate/handler was notified/invoked
if case .inMemory(let bodyData) = bodyDataDrain {
var data = Data()
if let body = bodyData {
data = Data(bytes: body.bytes, count: body.length)
}
self.client?.urlProtocol(self, didLoad: data)
self.internalState = .taskCompleted
} else if case .toFile(let url, let fileHandle?) = bodyDataDrain {
self.properties[.temporaryFileURL] = url
fileHandle.closeFile()
} else if task is URLSessionDownloadTask {
let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL)
fileHandle.closeFile()
self.properties[.temporaryFileURL] = self.tempFileURL
}
self.client?.urlProtocolDidFinishLoading(self)
self.internalState = .taskCompleted
}
func completionAction(forCompletedRequest request: URLRequest, response: URLResponse) -> _CompletionAction {
return .completeTask
}
func seekInputStream(to position: UInt64) throws {
// We will reset the body source and seek forward.
guard let session = task?.session as? URLSession else { fatalError() }
var currentInputStream: InputStream?
if let delegate = session.delegate as? URLSessionTaskDelegate {
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
delegate.urlSession(session, task: task!, needNewBodyStream: { inputStream in
currentInputStream = inputStream
dispatchGroup.leave()
})
_ = dispatchGroup.wait(timeout: .now() + 7)
}
if let url = self.request.url, let inputStream = currentInputStream {
switch self.internalState {
case .transferInProgress(let currentTransferState):
switch currentTransferState.requestBodySource {
case is _BodyStreamSource:
try inputStream.seek(to: position)
let drain = self.createTransferBodyDataDrain()
let source = _BodyStreamSource(inputStream: inputStream)
let transferState = _TransferState(url: url, bodyDataDrain: drain, bodySource: source)
self.internalState = .transferInProgress(transferState)
default:
NSUnimplemented()
}
default:
//TODO: it's possible?
break
}
}
}
func updateProgressMeter(with propgress: _EasyHandle._Progress) {
//TODO: Update progress. Note that a single URLSessionTask might
// perform multiple transfers. The values in `progress` are only for
// the current transfer.
}
/// The data drain.
///
/// This depends on what the delegate / completion handler need.
fileprivate func createTransferBodyDataDrain() -> _DataDrain {
guard let task = task else {
fatalError()
}
let s = task.session as! URLSession
switch s.behaviour(for: task) {
case .noDelegate:
return .ignore
case .taskDelegate:
// Data will be forwarded to the delegate as we receive it, we don't
// need to do anything about it.
return .ignore
case .dataCompletionHandler:
// Data needs to be concatenated in-memory such that we can pass it
// to the completion handler upon completion.
return .inMemory(nil)
case .downloadCompletionHandler:
// Data needs to be written to a file (i.e. a download task).
let fileHandle = try! FileHandle(forWritingTo: self.tempFileURL)
return .toFile(self.tempFileURL, fileHandle)
}
}
func createTransferState(url: URL, workQueue: DispatchQueue) -> _TransferState {
let drain = createTransferBodyDataDrain()
guard let t = task else {
fatalError("Cannot create transfer state")
}
switch t.body {
case .none:
return _TransferState(url: url, bodyDataDrain: drain)
case .data(let data):
let source = _BodyDataSource(data: data)
return _TransferState(url: url, bodyDataDrain: drain,bodySource: source)
case .file(let fileURL):
let source = _BodyFileSource(fileURL: fileURL, workQueue: workQueue, dataAvailableHandler: { [weak self] in
// Unpause the easy handle
self?.easyHandle.unpauseSend()
})
return _TransferState(url: url, bodyDataDrain: drain,bodySource: source)
case .stream(let inputStream):
let source = _BodyStreamSource(inputStream: inputStream)
return _TransferState(url: url, bodyDataDrain: drain, bodySource: source)
}
}
/// Start a new transfer
func startNewTransfer(with request: URLRequest) {
guard let t = task else {
fatalError()
}
t.currentRequest = request
guard let url = request.url else {
fatalError("No URL in request.")
}
self.internalState = .transferReady(createTransferState(url: url, workQueue: t.workQueue))
if let authRequest = task?.authRequest {
configureEasyHandle(for: authRequest)
} else {
configureEasyHandle(for: request)
}
if (t.suspendCount) < 1 {
resume()
}
}
func resume() {
if case .initial = self.internalState {
guard let r = task?.originalRequest else {
fatalError("Task has no original request.")
}
startNewTransfer(with: r)
}
if case .transferReady(let transferState) = self.internalState {
self.internalState = .transferInProgress(transferState)
}
}
func suspend() {
if case .transferInProgress(let transferState) = self.internalState {
self.internalState = .transferReady(transferState)
}
}
func configureEasyHandle(for: URLRequest) {
NSRequiresConcreteImplementation()
}
}
extension _NativeProtocol {
/// Action to be taken after a transfer completes
enum _CompletionAction {
case completeTask
case failWithError(Int)
case redirectWithRequest(URLRequest)
}
func completeTask(withError error: Error) {
task?.error = error
guard case .transferFailed = self.internalState else {
fatalError("Trying to complete the task, but its transfer isn't complete / failed.")
}
//We don't want a timeout to be triggered after this. The timeout timer needs to be cancelled.
easyHandle.timeoutTimer = nil
self.internalState = .taskCompleted
}
func failWith(error: NSError, request: URLRequest) {
//TODO: Error handling
let userInfo: [String : Any]? = request.url.map {
[
NSUnderlyingErrorKey: error,
NSURLErrorFailingURLErrorKey: $0,
NSURLErrorFailingURLStringErrorKey: $0.absoluteString,
NSLocalizedDescriptionKey: NSLocalizedString(error.localizedDescription, comment: "N/A")
]
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: error.code, userInfo: userInfo))
completeTask(withError: urlError)
self.client?.urlProtocol(self, didFailWithError: urlError)
}
/// Give the delegate a chance to tell us how to proceed once we have a
/// response / complete header.
///
/// This will pause the transfer.
func askDelegateHowToProceedAfterCompleteResponse(_ response: URLResponse, delegate: URLSessionDataDelegate) {
// Ask the delegate how to proceed.
// This will pause the easy handle. We need to wait for the
// delegate before processing any more data.
guard case .transferInProgress(let ts) = self.internalState else {
fatalError("Transfer not in progress.")
}
self.internalState = .waitingForResponseCompletionHandler(ts)
let dt = task as! URLSessionDataTask
// We need this ugly cast in order to be able to support `URLSessionTask.init()`
guard let s = task?.session as? URLSession else {
fatalError()
}
s.delegateQueue.addOperation {
delegate.urlSession(s, dataTask: dt, didReceive: response, completionHandler: { [weak self] disposition in
guard let task = self else { return }
self?.task?.workQueue.async {
task.didCompleteResponseCallback(disposition: disposition)
}
})
}
}
/// This gets called (indirectly) when the data task delegates lets us know
/// how we should proceed after receiving a response (i.e. complete header).
func didCompleteResponseCallback(disposition: URLSession.ResponseDisposition) {
guard case .waitingForResponseCompletionHandler(let ts) = self.internalState else {
fatalError("Received response disposition, but we're not waiting for it.")
}
switch disposition {
case .cancel:
let error = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled))
self.completeTask(withError: error)
self.client?.urlProtocol(self, didFailWithError: error)
case .allow:
// Continue the transfer. This will unpause the easy handle.
self.internalState = .transferInProgress(ts)
case .becomeDownload:
/* Turn this request into a download */
NSUnimplemented()
case .becomeStream:
/* Turn this task into a stream task */
NSUnimplemented()
}
}
}
extension _NativeProtocol {
enum _InternalState {
/// Task has been created, but nothing has been done, yet
case initial
/// The easy handle has been fully configured. But it is not added to
/// the multi handle.
case transferReady(_TransferState)
/// The easy handle is currently added to the multi handle
case transferInProgress(_TransferState)
/// The transfer completed.
///
/// The easy handle has been removed from the multi handle. This does
/// not necessarily mean the task completed. A task that gets
/// redirected will do multiple transfers.
case transferCompleted(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain)
/// The transfer failed.
///
/// Same as `.transferCompleted`, but without response / body data
case transferFailed
/// Waiting for the completion handler of the HTTP redirect callback.
///
/// When we tell the delegate that we're about to perform an HTTP
/// redirect, we need to wait for the delegate to let us know what
/// action to take.
case waitingForRedirectCompletionHandler(response: URLResponse, bodyDataDrain: _NativeProtocol._DataDrain)
/// Waiting for the completion handler of the 'did receive response' callback.
///
/// When we tell the delegate that we received a response (i.e. when
/// we received a complete header), we need to wait for the delegate to
/// let us know what action to take. In this state the easy handle is
/// paused in order to suspend delegate callbacks.
case waitingForResponseCompletionHandler(_TransferState)
/// The task is completed
///
/// Contrast this with `.transferCompleted`.
case taskCompleted
}
}
extension _NativeProtocol._InternalState {
var isEasyHandleAddedToMultiHandle: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return true
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
var isEasyHandlePaused: Bool {
switch self {
case .initial: return false
case .transferReady: return false
case .transferInProgress: return false
case .transferCompleted: return false
case .transferFailed: return false
case .waitingForRedirectCompletionHandler: return false
case .waitingForResponseCompletionHandler: return true
case .taskCompleted: return false
}
}
}
extension _NativeProtocol {
enum _Error: Error {
case parseSingleLineError
case parseCompleteHeaderError
}
func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
}
extension _NativeProtocol._ResponseHeaderLines {
func createURLResponse(for URL: URL, contentLength: Int64) -> URLResponse? {
return URLResponse(url: URL, mimeType: nil, expectedContentLength: Int(contentLength), textEncodingName: nil)
}
}
internal extension _NativeProtocol {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
fileprivate extension _NativeProtocol._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
extension _NativeProtocol {
/// Set request body length.
///
/// An unknown length
func set(requestBodyLength length: _HTTPURLProtocol._RequestBodyLength) {
switch length {
case .noBody:
easyHandle.set(upload: false)
easyHandle.set(requestBodyLength: 0)
case .length(let length):
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: Int64(length))
case .unknown:
easyHandle.set(upload: true)
easyHandle.set(requestBodyLength: -1)
}
}
enum _RequestBodyLength {
case noBody
///
case length(UInt64)
/// Will result in a chunked upload
case unknown
}
}
extension URLSession {
static func printDebug(_ text: @autoclosure () -> String) {
guard enableDebugOutput else { return }
debugPrint(text())
}
}
| apache-2.0 |
britez/sdk-ios | Example/Example/HomeViewController.swift | 1 | 1064 | //
// HomeViewController.swift
//
//
// Created by Maxi on 4/25/17.
//
//
import UIKit
import sdk_ios_v2
class HomeViewController: UIViewController, CyberSourceDelegate {
var cyberSource:CyberSource?
override func viewDidLoad() {
super.viewDidLoad()
self.cyberSource = CyberSource()
self.cyberSource?.delegate = self
self.cyberSource?.auth(publicKey: "e9cdb99fff374b5f91da4480c8dca741")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func authFinished(sessionId: String) {
NSLog("Session id created: %s", sessionId)
}
@IBAction func cardTokenButtonTapped(_ sender: UIButton) {
performSegue(withIdentifier: "tokenPayment", sender: self)
}
@IBAction func defaultButtonTapped(_ sender: UIButton) {
performSegue(withIdentifier: "defaultPayment", sender: self)
}
}
| mit |
khizkhiz/swift | validation-test/compiler_crashers_fixed/00716-swift-archetypetype-setnestedtypes.swift | 1 | 315 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a<l : T) {
protocol a {
struct d: a = c(start: B
case s(seq: Sequence, T>()"foo"")
func a<e: d
| apache-2.0 |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Views/Cells/AAHeaderCell.swift | 4 | 1284 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
open class AAHeaderCell: AATableViewCell {
open var titleView = UILabel()
open var iconView = UIImageView()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = appStyle.vcBackyardColor
selectionStyle = UITableViewCellSelectionStyle.none
titleView.textColor = appStyle.cellHeaderColor
titleView.font = UIFont.systemFont(ofSize: 14)
contentView.addSubview(titleView)
iconView.contentMode = UIViewContentMode.scaleAspectFill
contentView.addSubview(iconView)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func layoutSubviews() {
super.layoutSubviews()
let height = self.contentView.bounds.height
let width = self.contentView.bounds.width
titleView.frame = CGRect(x: 15, y: height - 28, width: width - 48, height: 24)
iconView.frame = CGRect(x: width - 18 - 15, y: height - 18 - 4, width: 18, height: 18)
}
}
| agpl-3.0 |
slavapestov/swift | validation-test/IDE/crashers/009-swift-performdelayedparsing.swift | 4 | 132 | // RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
enum b:a{var f={static#^A^# | apache-2.0 |
ahayman/RxStream | RxStream/Models/OpSignal.swift | 1 | 1497 | //
// OpSignal.swift
// RxStream
//
// Created by Aaron Hayman on 4/20/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import Foundation
/**
OpValue represents a value or flattened array of values returned as part of a OpSignal.
We're using this enum embedded into the OpSignal in order to represent what events should be pushed down stream.
It's necessary because both the .push and the .terminate can push events
*/
enum OpValue<T> {
/// Represents a single value that should be pushed down stream
case value(T)
/// Represents an array of values that should be sequentially pushed down stream as individual events
case flatten([T])
/// Convenience function used to retrieve an array of the event
var events: [Event<T>] {
switch self {
case .value(let value): return [.next(value)]
case .flatten(let values): return values.map{ .next($0) }
}
}
}
/// Signal returned from stream operations. The Stream processor will use the signal to determine what it should do with the triggering event
enum OpSignal<T> {
/// Map the event to a new value or a flattened
case push(OpValue<T>)
/// Event triggered an error
case error(Error)
/// Cancel the event. Don't terminate or push anything into the down streams.
case cancel
/// Mainly used my merged Future, used to signal that a merge is pending
case merging
/// Event triggered termination with optional OpValue to be first pushed
case terminate(OpValue<T>?, Termination)
}
| mit |
DOLOisSOLO/FrameAccessor | FrameAccessor-OSX/main.swift | 1 | 199 | //
// main.swift
// FrameAccessor-OSX
//
// Created by Adedayo Olumide on 6/23/14.
// Copyright (c) 2014 Adedayo Olumide. All rights reserved.
//
import Cocoa
NSApplicationMain(C_ARGC, C_ARGV)
| mit |
cgossain/AppController | AppController/Classes/AppController.swift | 1 | 12569 | //
// AppController.swift
//
// Copyright (c) 2021 Christian Gossain
//
// 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 AppController {
public struct Configuration {
/// The animation duration when transitionning between logged in/out states. A duration of zero
/// indicates no animation should occur.
public var transitionDuration: TimeInterval = 0.6
/// The animation delay when transitioning between logged in/out states. The default value of 0.0 generally
/// works well, however they may be times when an additional delay is required. This is provided
/// as an additional transition configuration point.
public var transitionDelay: TimeInterval = 0.0
/// Indicates if the any presented view controllers should first be dismissed before performing
/// the interface transition. The default value of `true` should work well for most cases. This
/// is provided as an additional transition configuration point.
public var dismissesPresentedViewControllerOnTransition = true
/// Initializes the configuration with the given options.
public init(transitionDuration: TimeInterval = 0.6, dismissesPresentedViewControllerOnTransition: Bool = true) {
self.transitionDuration = transitionDuration
self.dismissesPresentedViewControllerOnTransition = dismissesPresentedViewControllerOnTransition
}
}
/// The object that acts as the interface provider for the controller.
public let interfaceProvider: AppControllerInterfaceProviding
/// A closure that is called just before the transition to the _logged in_ interface begins. The view
/// controller that is about to be presented is passed to the block as the targetViewController.
///
/// - Note: This handler is called just before the transition begins, this means that if configured accordingly
/// a presented view controller would first be dismissed before this handler is called.
public var willLoginHandler: ((_ targetViewController: UIViewController) -> Void)?
/// A closure that is called after the transition to the _logged in_ interface completes.
public var didLoginHandler: (() -> Void)?
/// A closure that is called just before the transition to the _logged out_ interface begins. The view
/// controller that is about to be presented is passed to the block as the targetViewController.
///
/// - Note: This handler is called just before the transition begins, this means that if configured accordingly
/// a presented view controller would first be dismissed before this handler is called.
public var willLogoutHandler: ((_ targetViewController: UIViewController) -> Void)?
/// A closure that is called after the transition to the _logged out_ interface completes.
public var didLogoutHandler: (() -> Void)?
/// The view controller that should be installed as your window's rootViewController.
public lazy var rootViewController: AppViewController = {
if let storyboard = self.storyboard {
// get the rootViewController from the storyboard
return storyboard.instantiateInitialViewController() as! AppViewController
}
// if there is no storyboard, just create an instance of the app view controller (using the custom class if provided)
return self.appViewControllerClass.init()
}()
/// Returns the storyboard instance being used if the controller was initialized using the convenience storyboad initializer, otherwise retuns `nil`.
public var storyboard: UIStoryboard? {
return (interfaceProvider as? StoryboardInterfaceProvider)?.storyboard
}
// MARK: - Lifecycle
/// Initializes the controller using the specified storyboard name, and uses the given `loggedOutInterfaceID`, and `loggedInInterfaceID` values to instantiate
/// the appropriate view controller from the storyboad.
///
/// - Parameters:
/// - storyboardName: The name of the storyboard that contains the view controllers.
/// - loggedOutInterfaceID: The storyboard identifier of the view controller to use as the _logged out_ view controller.
/// - loggedInInterfaceID: The storyboard identifier of the view controller to use as the _logged in_ view controller.
/// - Note: The controller automatically installs the _initial view controller_ from the storyboard as the root view
/// controller. Therfore, the _initial view controller_ in the specified storyboard MUST be an instance
/// of `AppViewController`, otherwise a crash will occur.
public convenience init(storyboardName: String, loggedOutInterfaceID: String, loggedInInterfaceID: String, configuration: AppController.Configuration = Configuration()) {
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let provider = StoryboardInterfaceProvider(storyboard: storyboard, loggedOutInterfaceID: loggedOutInterfaceID, loggedInInterfaceID: loggedInInterfaceID, configuration: configuration)
self.init(interfaceProvider: provider)
}
/// Initializes the controller with closures that return the view controllers to install for the _logged out_ and _logged in_ states.
///
/// - Parameters:
/// - interfaceProvider: The object that will act as the interface provider for the controller.
/// - appViewControllerClass: Specify a custom `AppViewController` subclass to use as the rootViewController, or `nil` to use the standard `AppViewController`.
public init(interfaceProvider: AppControllerInterfaceProviding, appViewControllerClass: AppViewController.Type? = nil) {
self.interfaceProvider = interfaceProvider
// replace the default AppViewController class with the custom class, if provided
if let customAppViewControllerClass = appViewControllerClass {
self.appViewControllerClass = customAppViewControllerClass
}
// observe login notifications
loginNotificationObserver =
NotificationCenter.default.addObserver(
forName: AppController.shouldLoginNotification,
object: nil,
queue: .main,
using: { [weak self] notification in
guard let strongSelf = self else {
return
}
strongSelf.transitionToLoggedInInterface()
})
// observe logout notifications
logoutNotificationObserver =
NotificationCenter.default.addObserver(
forName: AppController.shouldLogoutNotification,
object: nil,
queue: .main,
using: { [weak self] notification in
guard let strongSelf = self else {
return
}
strongSelf.transitionToLoggedOutInterface()
})
}
deinit {
NotificationCenter.default.removeObserver(loginNotificationObserver!)
NotificationCenter.default.removeObserver(logoutNotificationObserver!)
}
// MARK: - Internal
private var appViewControllerClass = AppViewController.self
private var loginNotificationObserver: AnyObject?
private var logoutNotificationObserver: AnyObject?
}
extension AppController {
/// Internal notification that is posted on `AppController.login()`.
private static let shouldLoginNotification = Notification.Name(rawValue: "AppControllerShouldLoginNotification")
/// Internal notification that is posted on `AppController.logout()`.
private static let shouldLogoutNotification = Notification.Name(rawValue: "AppControllerShouldLogoutNotification")
/// Installs the receivers' instance of `AppViewController` as the windows' `rootViewController`, then calls `makeKeyAndVisible()` on
/// the window, and finally transtitions to the initial interface.
public func installRootViewController(in window: UIWindow) {
// setting the root view controller before transitioning allows the target interface to have access to a fully defined trait collection if needed
window.rootViewController = rootViewController
window.makeKeyAndVisible()
// transtion to the initial interface; since handlers should already be aware of their desired initial interface, they shouldn't be notified here
if interfaceProvider.isInitiallyLoggedIn(for: self) {
transitionToLoggedInInterface(notify: false)
}
else {
transitionToLoggedOutInterface(notify: false)
}
}
/// Posts a notification that notifies any active AppController instance to switch to its _logged in_ interface.
/// Note that any given app should only have a single active AppController instance. Therefore that single instance
/// will be the one that receives and handles the notification.
public static func login() {
NotificationCenter.default.post(name: AppController.shouldLoginNotification, object: nil, userInfo: nil)
}
/// Posts a notification that notifies any active AppController instance to switch to its _logged out_ interface.
/// Note that any given app should only have a single active AppController instance. Therefore that single instance
/// will be the one that receives and handles the notification.
public static func logout() {
NotificationCenter.default.post(name: AppController.shouldLogoutNotification, object: nil, userInfo: nil)
}
}
extension AppController {
private func transitionToLoggedInInterface(notify: Bool = true) {
let target = interfaceProvider.loggedInInterfaceViewController(for: self)
let configuration = interfaceProvider.configuration(for: self, traitCollection: rootViewController.traitCollection)
rootViewController.transition(to: target, configuration: configuration, willBeginTransition: { [weak self] in
guard let strongSelf = self else {
return
}
if notify {
strongSelf.willLoginHandler?(target)
}
}, completionHandler: { [weak self] in
guard let strongSelf = self else {
return
}
if notify {
strongSelf.didLoginHandler?()
}
})
}
private func transitionToLoggedOutInterface(notify: Bool = true) {
let target = interfaceProvider.loggedOutInterfaceViewController(for: self)
let configuration = interfaceProvider.configuration(for: self, traitCollection: rootViewController.traitCollection)
rootViewController.transition(to: target, configuration: configuration, willBeginTransition: { [weak self] in
guard let strongSelf = self else {
return
}
if notify {
strongSelf.willLogoutHandler?(target)
}
}, completionHandler: { [weak self] in
guard let strongSelf = self else {
return
}
if notify {
strongSelf.didLogoutHandler?()
}
})
}
}
| mit |
IGRSoft/IGRPhotoTweaks | IGRPhotoTweaks/PhotoTweakView/CropView/Mask/IGRCropMaskView.swift | 1 | 218 | //
// IGRCropMaskView.swift
// IGRPhotoTweaks
//
// Created by Vitalii Parovishnyk on 2/7/17.
// Copyright © 2017 IGR Software. All rights reserved.
//
import UIKit
public class IGRCropMaskView: UIView {
}
| mit |
openxc/openxc-ios-app-demo | openXCenabler/AppDelegate.swift | 1 | 2692 | //
// AppDelegate.swift
// openXCenabler
//
// Created by Tim Buick on 2016-08-04.
// Copyright (c) 2016 Ford Motor Company Licensed under the BSD license.
//
import UIKit
import HockeySDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.setUpHockeySDK()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func setUpHockeySDK() {
BITHockeyManager.shared().configure(withIdentifier: "8684d9e9ea0b4c3bbc9484ccb16965df")
//enable crash reporting
BITHockeyManager.shared().isCrashManagerDisabled = false
BITHockeyManager.shared().crashManager.crashManagerStatus = BITCrashManagerStatus.alwaysAsk
BITHockeyManager.shared().start()
//This line is obsolete in the crash only builds
BITHockeyManager.shared().authenticator.authenticateInstallation()
}
}
| bsd-3-clause |
eofster/Telephone | Telephone/CallHistoryOutgoingCallCellView.swift | 1 | 995 | //
// CallHistoryOutgoingCallCellView.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone 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.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Cocoa
final class CallHistoryOutgoingCallCellView: NSTableCellView {
@IBOutlet private weak var outgoingCallView: NSImageView!
override func awakeFromNib() {
super.awakeFromNib()
if #available(macOS 10.14, *) {
outgoingCallView.contentTintColor = NSColor.secondaryLabelColor
}
}
}
| gpl-3.0 |
kstaring/swift | stdlib/public/core/Print.swift | 4 | 11798 | //===--- Print.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Writes the textual representations of the given items into the standard
/// output.
///
/// You can pass zero or more items to the `print(_:separator:terminator:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a string,
/// a closed range of integers, and a group of floating-point values to
/// standard output:
///
/// print("One two three four five")
/// // Prints "One two three four five"
///
/// print(1...5)
/// // Prints "1...5"
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `print(_:separator:terminator:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// for n in 1...5 {
/// print(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
///
/// - SeeAlso: `debugPrint(_:separator:terminator:)`, `TextOutputStreamable`,
/// `CustomStringConvertible`, `CustomDebugStringConvertible`
@inline(never)
@_semantics("stdlib_binary_only")
public func print(
_ items: Any...,
separator: String = " ",
terminator: String = "\n"
) {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_print(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_print(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the standard output.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:)` function. The textual representation
/// for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints the debugging
/// representation of a string, a closed range of integers, and a group of
/// floating-point values to standard output:
///
/// debugPrint("One two three four five")
/// // Prints "One two three four five"
///
/// debugPrint(1...5)
/// // Prints "CountableClosedRange(1...5)"
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `debugPrint(_:separator:terminator:)` includes
/// a newline by default. To print the items without a trailing newline, pass
/// an empty string as `terminator`.
///
/// for n in 1...5 {
/// debugPrint(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
///
/// - SeeAlso: `print(_:separator:terminator:)`, `TextOutputStreamable`,
/// `CustomStringConvertible`, `CustomDebugStringConvertible`
@inline(never)
@_semantics("stdlib_binary_only")
public func debugPrint(
_ items: Any...,
separator: String = " ",
terminator: String = "\n") {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items into the given output
/// stream.
///
/// You can pass zero or more items to the `print(_:separator:terminator:to:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a closed
/// range of integers to a string:
///
/// var range = "My range: "
/// print(1...5, to: &range)
/// // range == "My range: 1...5\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `print(_:separator:terminator:to:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// print(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
///
/// - SeeAlso: `print(_:separator:terminator:)`,
/// `debugPrint(_:separator:terminator:to:)`,
/// `TextOutputStream`, `TextOutputStreamable`,
/// `CustomStringConvertible`, `CustomDebugStringConvertible`
@inline(__always)
public func print<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_print(items, separator: separator, terminator: terminator, to: &output)
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the given output stream.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:to:)` function. The textual
/// representation for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints a closed range of
/// integers to a string:
///
/// var range = "My range: "
/// debugPrint(1...5, to: &range)
/// // range == "My range: CountableClosedRange(1...5)\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `debugPrint(_:separator:terminator:to:)`
/// includes a newline by default. To print the items without a trailing
/// newline, pass an empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// debugPrint(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
///
/// - SeeAlso: `debugPrint(_:separator:terminator:)`,
/// `print(_:separator:terminator:to:)`,
/// `TextOutputStream`, `TextOutputStreamable`,
/// `CustomStringConvertible`, `CustomDebugStringConvertible`
@inline(__always)
public func debugPrint<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
@_versioned
@inline(never)
@_semantics("stdlib_binary_only")
internal func _print<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_print_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
@_versioned
@inline(never)
@_semantics("stdlib_binary_only")
internal func _debugPrint<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_debugPrint_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
//===----------------------------------------------------------------------===//
//===--- Migration Aids ---------------------------------------------------===//
@available(*, unavailable, renamed: "print(_:separator:terminator:to:)")
public func print<Target : TextOutputStream>(
_ items: Any...,
separator: String = "",
terminator: String = "",
toStream output: inout Target
) {}
@available(*, unavailable, renamed: "debugPrint(_:separator:terminator:to:)")
public func debugPrint<Target : TextOutputStream>(
_ items: Any...,
separator: String = "",
terminator: String = "",
toStream output: inout Target
) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'print((...), terminator: \"\")'")
public func print<T>(_: T, appendNewline: Bool = true) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'debugPrint((...), terminator: \"\")'")
public func debugPrint<T>(_: T, appendNewline: Bool = true) {}
//===--- FIXME: Not working due to <rdar://22101775> ----------------------===//
@available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'")
public func print<T>(_: T, _: inout TextOutputStream) {}
@available(*, unavailable, message: "Please use the 'to' label for the target stream: 'debugPrint((...), to: &...))'")
public func debugPrint<T>(_: T, _: inout TextOutputStream) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'print((...), terminator: \"\", to: &...)'")
public func print<T>(_: T, _: inout TextOutputStream, appendNewline: Bool = true) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'debugPrint((...), terminator: \"\", to: &...)'")
public func debugPrint<T>(
_: T, _: inout TextOutputStream, appendNewline: Bool = true
) {}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
| apache-2.0 |
Dormmate/DORMLibrary | DORM/Classes/UITextField+Extension.swift | 1 | 3687 | //
// UITextField+Extension.swift
// DORM
//
// Created by Dormmate on 2017. 5. 4..
// Copyright © 2017 Dormmate. All rights reserved.
//
import UIKit
private var targetView: UIView!
private var emojiFlag: Int = 0
extension UITextField: UITextFieldDelegate{
public func setTextField(fontName: String = ".SFUIText", size: CGFloat, placeholderText: String = "NO_PLACEHOLDER", _ targetView: UIView){
if placeholderText != "NO_PLACEHOLDER"{
self.placeholder = placeholderText
}
self.font = UIFont(name: fontName, size: size*widthRatio)
self.autocorrectionType = UITextAutocorrectionType.no
self.keyboardType = UIKeyboardType.default
self.returnKeyType = UIReturnKeyType.done
self.delegate = self
targetView.addSubview(self)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/*
키보드 올라갈 때 화면 올림
사용법 : textField.setKeyboardNotification(target: self.view)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
textField.endEditing(true)
textField.setEmojiFlag()
}
*/
public func setKeyboardNotification(target: UIView!){
targetView = target
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
public func setEmojiFlag(){
emojiFlag = 0
}
public func keyboardWillShow(notification:NSNotification,target: UIView) {
adjustingHeight(show: false, notification: notification)
}
public func keyboardWillHide(notification:NSNotification) {
targetView.y = 0
}
public func adjustingHeight(show:Bool, notification:NSNotification) {
var userInfo = notification.userInfo!
let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
let changeInHeight = -(keyboardFrame.height)
let changeInEmoji : CGFloat = -(42 * heightRatio)
let initialLanguage = self.textInputMode?.primaryLanguage
UIView.animate(withDuration: animationDuration, animations: { () -> Void in
if self.textInputMode?.primaryLanguage == nil{
targetView.frame.origin.y += changeInEmoji
emojiFlag = 1
} else if self.textInputMode?.primaryLanguage == initialLanguage && emojiFlag == 0 {
targetView.frame.origin.y += changeInHeight
} else if self.textInputMode?.primaryLanguage == initialLanguage && emojiFlag == 1 {
targetView.frame.origin.y += (42 * heightRatio)
emojiFlag = 0
} else{
targetView.frame.origin.y += changeInHeight
emojiFlag = 0
}
})
//범위 밖 충돌 현상 또는 3rd party keyboard 버그 발생시
if targetView.frame.origin.y < -258.0 || keyboardFrame.height == 0.0{
targetView.frame.origin.y = -216.0
}
}
}
| mit |
allbto/ios-swiftility | SwiftilityTests/Extensions/UIViewAutoLayoutExtensionsTests.swift | 2 | 4079 | //
// UIViewAutoLayoutExtensionsTests.swift
// Swiftility
//
// Created by Allan Barbato on 11/10/16.
// Copyright © 2016 Allan Barbato. All rights reserved.
//
import XCTest
import Nimble
@testable import Swiftility
final class UIViewAutoLayoutExtensionsTests: XCTestCase
{
var view: UIView!
var superview: UIView!
override func setUp()
{
super.setUp()
superview = UIView()
view = UIView()
}
func testAutoAttach()
{
view.autoAttach(to: superview)
XCTAssert(view.superview == superview)
XCTAssert(view.translatesAutoresizingMaskIntoConstraints == false)
}
func testAutoPinFailure()
{
XCTAssert(view.superview == nil)
expect {
self.view.autoPin(.top)
}.to(throwAssertion())
}
func testAutoPinSimple()
{
var constraint: NSLayoutConstraint!
view.autoAttach(to: superview) {
constraint = $0.autoPin(.top)
}
XCTAssertEqual((constraint.firstItem as! UIView), view)
XCTAssertEqual(constraint.firstAttribute, .top)
XCTAssertEqual(constraint.relation, .equal)
XCTAssertEqual((constraint.secondItem as! UIView), superview)
XCTAssertEqual(constraint.secondAttribute, .top)
XCTAssertEqual(constraint.multiplier, 1)
XCTAssertEqual(constraint.constant, 0)
XCTAssertEqual(constraint.priority, .required)
constraint = view.autoPin(.bottom)
XCTAssertEqual((constraint.firstItem as! UIView), view)
XCTAssertEqual(constraint.firstAttribute, .bottom)
XCTAssertEqual(constraint.relation, .equal)
XCTAssertEqual((constraint.secondItem as! UIView), superview)
XCTAssertEqual(constraint.secondAttribute, .bottom)
XCTAssertEqual(constraint.multiplier, 1)
XCTAssertEqual(constraint.constant, 0)
XCTAssertEqual(constraint.priority, .required)
}
func testAutoPinFull()
{
var constraint: NSLayoutConstraint!
let otherView = UIView()
view.autoAttach(to: superview) {
constraint = $0.autoPin(.top, relatedBy: .greaterThanOrEqual, toItem: otherView, toAttribute: .bottom, multiplier: 2, constant: 25, priority: .defaultLow)
}
XCTAssertEqual((constraint.firstItem as! UIView), view)
XCTAssertEqual(constraint.firstAttribute, .top)
XCTAssertEqual(constraint.relation, .greaterThanOrEqual)
XCTAssertEqual((constraint.secondItem as! UIView), otherView)
XCTAssertEqual(constraint.secondAttribute, .bottom)
XCTAssertEqual(constraint.multiplier, 2)
XCTAssertEqual(constraint.constant, 25)
XCTAssertEqual(constraint.priority, .defaultLow)
}
func testAutoPinNotAnAttribute()
{
var constraint: NSLayoutConstraint!
var constraint2: NSLayoutConstraint!
view.autoAttach(to: superview) {
constraint = $0.autoPin(.width, toItem: nil, toAttribute: .bottom)
constraint2 = $0.autoPin(.height, toItem: nil)
}
XCTAssertEqual((constraint.firstItem as! UIView), view)
XCTAssertEqual(constraint.firstAttribute, .width)
XCTAssertEqual(constraint.relation, .equal)
XCTAssert(constraint.secondItem == nil)
XCTAssertEqual(constraint.secondAttribute, .notAnAttribute)
XCTAssertEqual(constraint.multiplier, 1)
XCTAssertEqual(constraint.constant, 0)
XCTAssertEqual(constraint.priority, .required)
XCTAssertEqual((constraint2.firstItem as! UIView), view)
XCTAssertEqual(constraint2.firstAttribute, .height)
XCTAssertEqual(constraint2.relation, .equal)
XCTAssert(constraint2.secondItem == nil)
XCTAssertEqual(constraint2.secondAttribute, .notAnAttribute)
XCTAssertEqual(constraint2.multiplier, 1)
XCTAssertEqual(constraint2.constant, 0)
XCTAssertEqual(constraint2.priority, .required)
}
}
| mit |
cikelengfeng/HTTPIDL | Sources/Runtime/Observer/Observer.swift | 1 | 579 | //
// HTTPMessageObserver.swift
// everfilter
//
// Created by 徐 东 on 2017/1/3//
import Foundation
public protocol RequestObserver: class {
func willSend(request: Request)
func didSend(request: Request)
func willEncode(request: Request)
func didEncode(request: Request, encoded: HTTPRequest)
}
public protocol ResponseObserver: class {
func receive(error: HIError, request: Request)
func receive(rawResponse: HTTPResponse)
func willDecode(rawResponse: HTTPResponse)
func didDecode(rawResponse: HTTPResponse, decodedResponse: Response)
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/25147-swift-genericsignature-getcanonical.swift | 7 | 215 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A{func n
class A}
class d:A
import F
| mit |
tapwork/WikiLocation | WikiManager/WikiManager.swift | 1 | 2655 | //
// WikiManager.swift
// WikiLocation
//
// Created by Christian Menschel on 29.06.14.
// Copyright (c) 2014 enterprise. All rights reserved.
//
import Foundation
let kWikilocationBaseURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&list=geosearch&gsradius=10000&gscoord="
let kBackgrounddownloadID = "net.tapwork.wikilocation.backgrounddownload.config"
public class WikiManager : NSObject {
//MARK: - Properties
public class var sharedInstance: WikiManager {
struct SharedInstance {
static let instance = WikiManager()
}
return SharedInstance.instance
}
//MARK: - Download
func downloadURL(#url:NSURL,completion:((NSData!, NSError!) -> Void)) {
let request: NSURLRequest = NSURLRequest(URL:url)
var config = NSURLSessionConfiguration.defaultSessionConfiguration()
if UIApplication.sharedApplication().applicationState == .Background {
config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(kBackgrounddownloadID)
}
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
completion(data, error)
})
});
task.resume()
}
// NOTE: #major forces first parameter to be named in function call
public func downloadWikis(#latitude:Double,longitude:Double,completion:(([WikiArticle]) -> Void)) {
let path = "\(latitude)%7C\(longitude)"
let fullURLString = kWikilocationBaseURL + path
let url = NSURL(string: fullURLString)
self.downloadURL(url: url!) { (data, error) -> Void in
var articles = NSMutableOrderedSet()
if (data.length > 0) {
var error:NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error:&error) as NSDictionary
if let result = jsonResult["query"] as? NSDictionary {
if let jsonarticles = result["geosearch"]! as? NSArray {
for item : AnyObject in jsonarticles {
var article = WikiArticle(json: item as Dictionary<String, AnyObject>)
articles.addObject(article)
}
}
}
}
completion(articles.array as [WikiArticle])
}
}
} | mit |
tfmalt/garage-door-opener-ble | iOS/GarageOpener/GOOpenerController.swift | 1 | 20039 | //
// OpenerViewController.swift
// GarageOpener
//
// Created by Thomas Malt on 10/01/15.
// Copyright (c) 2015 Thomas Malt. All rights reserved.
//
import UIKit
import CoreBluetooth
import AVFoundation
// Constructing global singleton of this
var captureCtrl : GOCaptureController = GOCaptureController()
// Struct containing the colors I use.
struct Colors {
static let wait = UIColor.colorWithHex("#D00000")!
static let waitHighlight = UIColor.colorWithHex("#D00000")!
static let open = UIColor.colorWithHex("#33BB33")!
static let openHighlight = UIColor.colorWithHex("#208840")!
static let scanning = UIColor.colorWithHex("#D00000")!
static let scanningHighlight = UIColor.colorWithHex("#D00000")!
static let start = UIColor.colorWithHex("#1080C0")! // FFAA00
static let startHighlight = UIColor.colorWithHex("#0C4778")! // 0C4778 FFDD00
}
class GOOpenerController: UIViewController {
@IBOutlet weak var openButton: UIButton!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var rssiLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var lumValueLabel: UILabel!
@IBOutlet weak var lumLabel: UILabel!
let AnimationDuration = 0.5
// An enum to keep track of the application states defined.
enum States {
case Connected
case Initializing
case Scanning
case Waiting
case DeviceNotFound
case DeviceFound
case BluetoothOff
case Disconnected
}
var currentState = States.Disconnected
var discovery : BTDiscoveryManager?
var captureCtrl : GOCaptureController = GOCaptureController()
var needToShowCameraNotAuthorizedAlert : Bool = false
var hasShownCameraNotAuthorized : Bool = false
var config = NSUserDefaults.standardUserDefaults()
let nc = NSNotificationCenter.defaultCenter()
let DEMO : Bool = false
let STATE : States = States.Scanning
override func viewDidLoad() {
super.viewDidLoad()
self.initLabels()
self.makeButtonCircular()
if DEMO == true {
self.setTheme()
switch (STATE) {
case States.Connected:
self.updateOpenButtonNormal()
self.setupWithoutAutoTheme()
self.setSignalLevel(3)
self.activityIndicator.stopAnimating()
self.setStatusLabel("Connected to Home")
break
case States.Scanning:
self.updateOpenButtonScanning()
self.setupWithoutAutoTheme()
self.setStatusLabel("Scanning")
break
default:
self.updateOpenButtonWait()
break
}
} else {
self.updateOpenButtonWait()
self.registerObservers()
self.setTheme()
self.checkAndConfigureAutoTheme()
self.discovery = BTDiscoveryManager()
}
}
func checkAndConfigureAutoTheme() {
if self.config.boolForKey("useAutoTheme") == true {
self.initAutoThemeLabels()
self.captureCtrl.initializeCaptureSession()
} else {
self.setupWithoutAutoTheme()
}
}
func initLabels() {
self.lumValueLabel.text = ""
self.setStatusLabel("Initializing")
self.setSignalLevel(0)
}
/// updates the rssiLabel with the signal meter number
func setSignalLevel(strength: Int) {
assert(
(strength >= 0 && strength <= 5),
"argument strength need to be an Integer between 0 and 5."
)
if let label = self.rssiLabel {
label.text = self.getConnectionBar(strength)
}
}
/// updates the status label with new text.
func setStatusLabel(text: String) {
if let label = self.statusLabel {
label.text = text
}
}
override func viewDidAppear(animated: Bool) {
if self.needToShowCameraNotAuthorizedAlert == true {
self.showCameraNotAuthorizedAlert()
}
self.hasShownCameraNotAuthorized = true
}
func showCameraNotAuthorizedAlert() {
let alert = self.captureCtrl.getCameraNotAuthorizedAlert()
self.presentViewController(alert, animated: true, completion: { () -> Void in
self.needToShowCameraNotAuthorizedAlert = false
})
}
func handleCaptureDeviceNotAuthorized(notification: NSNotification) {
config.setBool(false, forKey: "useAutoTheme")
self.setupWithoutAutoTheme()
if self.hasShownCameraNotAuthorized == false {
if (self.isViewLoaded() && (self.view.window != nil)) {
self.showCameraNotAuthorizedAlert()
} else {
self.needToShowCameraNotAuthorizedAlert = true
}
}
}
func handleCaptureDeviceAuthorizationNotDetermined(notification: NSNotification) {
setupWithoutAutoTheme()
config.setBool(false, forKey: "useAutoTheme")
}
func initAutoThemeLabels() {
lumLabel.text = "Lum:"
}
func setupWithoutAutoTheme() {
lumLabel.text = ""
lumValueLabel.text = ""
}
///////////////////////////////////////////////////////////////////////
//
// Functions relating to theming and adjusting the visual style
// depending on settings
//
func setTheme() {
if (config.boolForKey("useDarkTheme")) {
self.setDarkTheme()
} else {
self.setLightTheme()
}
self.setNeedsStatusBarAppearanceUpdate()
}
/// Updates the automatic theme settings based on the luminance value
func updateAutoTheme(luminance: Float) {
if self.config.boolForKey("useAutoTheme") == false {
return
}
if (luminance >= 0.50) {
self.setLightThemeAnimated()
}
else if (luminance <= 0.40) {
self.setDarkThemeAnimated()
}
delay(0.5) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
func setDarkThemeAnimated() {
UIView.animateWithDuration(AnimationDuration, animations: {
self.view.backgroundColor = UIColor.blackColor()
})
statusLabel.textColor = UIColor.colorWithHex("#CCCCCC")
activityIndicator.color = UIColor.colorWithHex("#CCCCCC")
}
func setLightThemeAnimated() {
UIView.animateWithDuration(AnimationDuration, animations: {
self.view.backgroundColor = UIColor.whiteColor()
})
statusLabel.textColor = UIColor.colorWithHex("#888888")
activityIndicator.color = UIColor.colorWithHex("#888888")
}
func setDarkTheme() {
self.view.backgroundColor = UIColor.blackColor()
statusLabel.textColor = UIColor.colorWithHex("#CCCCCC")
activityIndicator.color = UIColor.colorWithHex("#CCCCCC")
}
func setLightTheme() {
self.view.backgroundColor = UIColor.whiteColor()
statusLabel.textColor = UIColor.colorWithHex("#888888")
activityIndicator.color = UIColor.colorWithHex("#888888")
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
if self.view.backgroundColor == UIColor.blackColor() {
return UIStatusBarStyle.LightContent
} else {
return UIStatusBarStyle.Default
}
}
///////////////////////////////////////////////////////////////////////
//
// Observers and their handlers
//
/// The full list of events the app is listening to.
func registerObservers() {
nc.addObserver(
self,
selector: Selector("appWillEnterForeground:"),
name: UIApplicationWillEnterForegroundNotification,
object: nil
)
nc.addObserver(
self,
selector: Selector("appDidEnterBackground:"),
name: UIApplicationDidEnterBackgroundNotification,
object: nil
)
nc.addObserver(
self,
selector: Selector("btStateChanged:"),
name: "btStateChangedNotification",
object: nil
)
nc.addObserver(
self,
selector: "handleBTScanningTimedOut:",
name: "BTDiscoveryScanningTimedOutNotification",
object: nil
)
nc.addObserver(
self,
selector: Selector("btConnectionChanged:"),
name: "btConnectionChangedNotification",
object: nil
)
nc.addObserver(
self,
selector: Selector("btFoundDevice:"),
name: "btFoundDeviceNotification",
object: nil
)
nc.addObserver(
self,
selector: Selector("btUpdateRSSI:"),
name: "btRSSIUpdateNotification",
object: nil
)
nc.addObserver(
self,
selector: "handleSettingsUpdated",
name: "SettingsUpdatedNotification",
object: nil
)
nc.addObserver(
self,
selector: "handleLightLevelUpdate:",
name: "GOCaptureCalculatedLightLevelNotification",
object: nil
)
nc.addObserver(
self,
selector: "handleCaptureDeviceNotAuthorized:",
name: "GOCaptureDeviceNotAuthorizedNotification",
object: nil
)
nc.addObserver(
self,
selector: "handleCaptureDeviceAuthorizationNotDetermined:",
name: "GOCaptureDeviceAuthorizationNotDetermined",
object: nil
)
}
///////////////////////////////////////////////////////////////////////
//
// App activity notifications
//
func appWillEnterForeground(notification: NSNotification) {
self.updateOpenButtonWait()
self.checkAndConfigureAutoTheme()
}
func appDidEnterBackground(notification: NSNotification) {
self.updateOpenButtonWait()
self.captureCtrl.removeImageCaptureTimer()
self.captureCtrl.endCaptureSession()
}
///////////////////////////////////////////////////////////////////////
//
// Settings view notification handlers
//
func handleSettingsUpdated() {
self.setTheme()
if self.config.boolForKey("useAutoTheme") == true {
self.initAutoThemeLabels()
} else {
self.setupWithoutAutoTheme()
}
}
///////////////////////////////////////////////////////////////////////
func handleLightLevelUpdate(notification: NSNotification) {
var info = notification.userInfo as [String : AnyObject]
var luminance = info["luminance"] as Float
dispatch_async(dispatch_get_main_queue(), {
self.updateAutoTheme(luminance)
self.lumValueLabel.text = String(format: "%.2f", luminance)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getConnectionBar(strength: Int) -> String {
let s : String = "\u{25A1}"
let b : String = "\u{25A0}"
var result : String = ""
for (var i = 0; i < 5; i++) {
if i < strength {
result = result + b;
} else {
result = result + s;
}
}
return result
}
@IBAction func openButtonPressed(sender: UIButton) {
if self.currentState == States.Connected {
self.sendOpenCommand()
return
}
if self.currentState == States.DeviceNotFound {
if let discovery = self.discovery {
discovery.startScanning()
}
return
}
}
func sendOpenCommand() {
if let rx = self.getRXCharacteristic() {
if let peripheral = self.getActivePeripheral() {
if let pass = config.valueForKey("password") as? String {
var str = "0" + pass;
var data : NSData = str.dataUsingEncoding(NSUTF8StringEncoding)!
peripheral.writeValue(
data,
forCharacteristic: rx,
type: CBCharacteristicWriteType.WithoutResponse
)
}
}
}
}
func getActivePeripheral() -> CBPeripheral? {
if self.discovery == nil { return nil }
if let peripheral = self.discovery!.activePeripheral {
if peripheral.state != CBPeripheralState.Connected { return nil }
return peripheral
}
return nil
}
func getRXCharacteristic() -> CBCharacteristic? {
if let peripheral = self.getActivePeripheral() {
if let service = self.discovery?.activeService {
if let rx = service.rxCharacteristic {
return rx
}
}
}
return nil
}
func updateOpenButtonWait() {
UIView.animateWithDuration(AnimationDuration, animations: {
self.openButton.backgroundColor = Colors.wait
})
openButton.setBackgroundImage(
UIImage.imageWithColor(Colors.wait),
forState: UIControlState.Highlighted
)
openButton.setTitle("Wait", forState: UIControlState.Normal)
}
func updateOpenButtonNormal() {
UIView.animateWithDuration(AnimationDuration, animations: {
self.openButton.backgroundColor = Colors.open
})
openButton.setBackgroundImage(
UIImage.imageWithColor(Colors.openHighlight),
forState: UIControlState.Highlighted
)
self.openButton.setTitle("Open", forState: UIControlState.Normal)
}
func updateOpenButtonScanning() {
UIView.animateWithDuration(AnimationDuration, animations: {
self.openButton.backgroundColor = Colors.scanning
})
self.openButton.setBackgroundImage(
UIImage.imageWithColor(Colors.scanning),
forState: UIControlState.Highlighted
)
self.openButton.setTitle("Wait", forState: UIControlState.Normal)
}
func updateOpenButtonStartScan() {
UIView.animateWithDuration(AnimationDuration, animations: {
self.openButton.backgroundColor = Colors.start
})
self.openButton.setBackgroundImage(
UIImage.imageWithColor(Colors.startHighlight),
forState: UIControlState.Highlighted
)
openButton.setTitle("Connect", forState: UIControlState.Normal)
}
/// Updates the button to make size and layout is correct.
func makeButtonCircular() {
openButton.frame = CGRectMake(0, 0, 180, 180);
openButton.clipsToBounds = true;
openButton.layer.cornerRadius = 90
}
/// Listens to notifications about CoreBluetooth state changes
///
/// :param: notification The NSNotification object
/// :returns: nil
func btStateChanged(notification: NSNotification) {
var msg = notification.object as String
dispatch_async(dispatch_get_main_queue(), {
if (msg.hasPrefix("Low Signal")) {
self.currentState = States.Scanning
return
}
self.setStatusLabel(msg)
if (msg != "Scanning") {
self.activityIndicator.stopAnimating()
}
if (msg == "Disconnected") {
self.currentState = States.Disconnected
self.updateOpenButtonWait()
}
else if (msg == "Bluetooth Off") {
self.currentState = States.BluetoothOff
self.updateOpenButtonWait()
self.setSignalLevel(0)
}
else if (msg == "Scanning") {
self.currentState = States.Scanning
self.updateOpenButtonScanning()
self.setSignalLevel(0)
self.activityIndicator.startAnimating()
}
})
}
func handleBTScanningTimedOut(notification: NSNotification) {
self.currentState = States.DeviceNotFound
dispatch_async(dispatch_get_main_queue(), {
self.updateOpenButtonWait()
self.setSignalLevel(0)
self.activityIndicator.stopAnimating()
self.setStatusLabel("Device Not Found")
self.delay(2.0) {
self.updateOpenButtonStartScan()
self.setStatusLabel("Scan Finished")
}
})
}
/// Handler for the connection.
func btConnectionChanged(notification: NSNotification) {
let info = notification.userInfo as [String: AnyObject]
var name = info["name"] as NSString
if name.length < 1 {
name = ""
} else {
name = " to " + name
}
if let isConnected = info["isConnected"] as? Bool {
self.currentState = States.Connected
dispatch_async(dispatch_get_main_queue(), {
self.updateOpenButtonNormal()
self.setStatusLabel("Connected\(name)")
self.activityIndicator.stopAnimating()
})
}
}
func btFoundDevice(notification: NSNotification) {
let info = notification.userInfo as [String: AnyObject]
var peripheral = info["peripheral"] as CBPeripheral
var rssi = info["RSSI"] as NSNumber
var name = String(peripheral.name)
self.currentState = States.DeviceFound
dispatch_async(dispatch_get_main_queue(), {
self.openButton.backgroundColor = UIColor.orangeColor()
self.setStatusLabel("Found Device...")
})
}
func getQualityFromRSSI(RSSI: NSNumber!) -> Int {
var quality = 2 * (RSSI.integerValue + 100);
if quality < 0 { quality = 0 }
if quality > 100 { quality = 100 }
return quality
}
func btUpdateRSSI(notification: NSNotification) {
let info = notification.userInfo as [String: NSNumber]
let peripheral = notification.object as CBPeripheral
var rssi : NSNumber! = info["rssi"]
if peripheral.state != CBPeripheralState.Connected {
return
}
var quality : Int = self.getQualityFromRSSI(rssi)
var strength : Int = Int(ceil(Double(quality) / 20))
dispatch_async(dispatch_get_main_queue(), {
self.setSignalLevel(strength)
})
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure
)
}
}
| mit |
SunshineYG888/YG_NetEaseOpenCourse | YG_NetEaseOpenCourse/YG_NetEaseOpenCourse/Classes/View/Category/YGSearchView.swift | 1 | 7268 | //
// YGSearchView.swift
// YG_NetEaseOpenCourse
//
// Created by male on 16/4/13.
// Copyright © 2016年 yg. All rights reserved.
//
import UIKit
import SnapKit
enum SearchViewType {
case Home
case Category
}
let SearchViewMargin = 12
class YGSearchView: UIView, UITextFieldDelegate {
/* 属性 */
var textFieldTailCons: Constraint?
var textFieldLeadCons: Constraint?
var type: SearchViewType = SearchViewType.Home
lazy var searchKeyWordsTableVC: YGSearchKeyWordsTableViewController = YGSearchKeyWordsTableViewController()
/* 构造函数 */
convenience init(searViewType: SearchViewType, frame: CGRect) {
self.init(frame: frame)
type = searViewType
setupUI()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/* 点击"取消按钮" */
func cancelBtnDidClick(sender: UIButton) {
textField.resignFirstResponder()
textFieldLeadCons?.uninstall()
textFieldTailCons?.uninstall()
textField.snp_makeConstraints(closure: { (make) -> Void in
textFieldLeadCons = make.left.equalTo(logoImageView.snp_right).offset(SearchViewMargin).constraint
if type == SearchViewType.Home {
textFieldTailCons = make.right.equalTo(historyBtn.snp_left).offset(-SearchViewMargin).constraint
} else {
textFieldTailCons = make.right.equalTo(self.snp_right).offset(-SearchViewMargin).constraint
}
})
textField.text = ""
UIView.animateWithDuration(0.5) { () -> Void in
self.logoImageView.alpha = 1
self.cancelBtn.hidden = true
if self.type == SearchViewType.Home {
self.historyBtn.alpha = 1
self.downloadBtn.alpha = 1
}
}
searchKeyWordsTableVC.dismiss()
}
/* 懒加载子控件 */
// logo
private lazy var logoImageView: UIImageView = UIImageView(image: UIImage(named: "home_logo"))
// textField
private lazy var textField: UITextField = {
let textField = UITextField()
textField.backgroundColor = UIColor.colorWithRGB(39, green: 95, blue: 62)
textField.placeholder = "Ted"
textField.textColor = UIColor.whiteColor()
textField.layer.cornerRadius = 5
textField.layer.masksToBounds = true
return textField
}()
// textField 中的放大镜
private lazy var searchImageView: UIImageView = UIImageView(image: UIImage(named: "home_search"))
// 播放记录
private lazy var historyBtn: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "home_history"), forState: .Normal)
return btn
}()
// 已下载
private lazy var downloadBtn: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "home_download"), forState: .Normal)
return btn
}()
// "取消"按钮
private lazy var cancelBtn: UIButton = {
let btn = UIButton()
btn.setTitle("取消", forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
btn.titleLabel?.font = UIFont.systemFontOfSize(14)
btn.hidden = true
btn.sizeToFit()
return btn
}()
}
/* 设置界面 */
extension YGSearchView {
private func setupUI() {
addSubview(logoImageView)
addSubview(textField)
addSubview(cancelBtn)
textField.delegate = self
cancelBtn.addTarget(self, action: "cancelBtnDidClick:", forControlEvents: .TouchUpInside)
logoImageView.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self.snp_centerY)
make.left.equalTo(self.snp_left)
make.width.height.equalTo(35)
}
cancelBtn.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self.snp_centerY)
make.right.equalTo(self.snp_right)
}
textField.snp_makeConstraints { (make) -> Void in
textFieldLeadCons = make.left.equalTo(logoImageView.snp_right).offset(SearchViewMargin).constraint
make.centerY.equalTo(self.snp_centerY)
make.height.equalTo(28)
textFieldTailCons = make.right.equalTo(self.snp_right).offset(-SearchViewMargin).constraint
}
setupLeftView()
if type == SearchViewType.Home {
addSubview(downloadBtn)
addSubview(historyBtn)
downloadBtn.snp_makeConstraints(closure: { (make) -> Void in
make.centerY.equalTo(self.snp_centerY)
make.right.equalTo(self.snp_right)
make.width.height.equalTo(20)
})
historyBtn.snp_makeConstraints(closure: { (make) -> Void in
make.centerY.equalTo(self.snp_centerY)
make.width.height.equalTo(20)
make.right.equalTo(downloadBtn.snp_left).offset(-SearchViewMargin)
})
textFieldTailCons?.uninstall()
textField.snp_makeConstraints(closure: { (make) -> Void in
textFieldTailCons = make.right.equalTo(historyBtn.snp_left).offset(-SearchViewMargin).constraint
})
}
}
/* 设置 textField 的左图 */
private func setupLeftView() {
textField.leftView = searchImageView
textField.leftView?.contentMode = .Center
textField.leftViewMode = .Always
searchImageView.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(textField.leftView!.snp_centerY)
make.left.equalTo(textField.leftView!.snp_left)
make.width.height.equalTo(30)
}
}
}
/* UITextFieldDelegate */
extension YGSearchView {
/* textField 开始编辑时调用的代理方法 */
func textFieldDidBeginEditing(textField: UITextField) {
adjustNavigationBar()
searchKeyWordsTableVC.show()
}
private func adjustNavigationBar() {
if type == SearchViewType.Home {
historyBtn.alpha = 0
downloadBtn.alpha = 0
}
logoImageView.alpha = 0
cancelBtn.hidden = false
textFieldLeadCons?.uninstall()
textFieldTailCons?.uninstall()
textField.snp_makeConstraints(closure: { (make) -> Void in
textFieldLeadCons = make.left.equalTo(self.snp_left).offset(SearchViewMargin).constraint
textFieldTailCons = make.right.equalTo(cancelBtn.snp_left).offset(-SearchViewMargin).constraint
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let searchWord = textField.text!
if searchWord != "" {
print("search " + searchWord)
YGSearchHistoryManager.sharedSearchHistoryManager.addSearchedKeyWords(searchWord)
} else {
print("search \"TED\"")
}
return true
}
} | mit |
mrdekk/DataKernel | DataKernel/Classes/Contracts/Refs/StoreRef.swift | 1 | 576 | //
// Store.swift
// DataKernel
//
// Created by Denis Malykh on 30/04/16.
// Copyright © 2016 mrdekk. All rights reserved.
//
import Foundation
public enum StoreRef: Equatable {
case named(String)
case url(URL)
public func location() -> URL {
switch self {
case .url(let url): return url
case .named(let name): return Foundation.URL(fileURLWithPath: FileUtils.documents()).appendingPathComponent(name)
}
}
}
public func == (lhs: StoreRef, rhs: StoreRef) -> Bool {
return lhs.location() == rhs.location()
}
| mit |
jeffreybergier/Hipstapaper | Hipstapaper/Packages/V3Model/Sources/V3Model/Website.swift | 1 | 2774 | //
// Created by Jeffrey Bergier on 2022/06/17.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public struct Website: Identifiable, Hashable, Equatable {
public typealias Selection = Set<Website.Identifier>
public struct Identifier: Hashable, Equatable, Codable, RawRepresentable, Identifiable {
public var id: String { self.rawValue }
public var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
}
public var id: Identifier
public var isArchived: Bool
public var originalURL: URL?
public var resolvedURL: URL?
public var title: String?
public var thumbnail: Data?
public var dateCreated: Date?
public var dateModified: Date?
public init(id: Identifier,
isArchived: Bool = false,
originalURL: URL? = nil,
resolvedURL: URL? = nil,
title: String? = nil,
thumbnail: Data? = nil,
dateCreated: Date? = nil,
dateModified: Date? = nil)
{
self.id = id
self.isArchived = isArchived
self.originalURL = originalURL
self.resolvedURL = resolvedURL
self.title = title
self.thumbnail = thumbnail
self.dateCreated = dateCreated
self.dateModified = dateModified
}
}
extension Website {
public var preferredURL: URL? { self.resolvedURL ?? self.originalURL }
}
extension Website.Identifier: Comparable {
public static func < (lhs: Website.Identifier, rhs: Website.Identifier) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
| mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Route53/Route53_Paginator.swift | 1 | 14741 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension Route53 {
/// Retrieve a list of the health checks that are associated with the current AWS account.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listHealthChecksPaginator<Result>(
_ input: ListHealthChecksRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListHealthChecksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listHealthChecks,
tokenKey: \ListHealthChecksResponse.nextMarker,
moreResultsKey: \ListHealthChecksResponse.isTruncated,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listHealthChecksPaginator(
_ input: ListHealthChecksRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListHealthChecksResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listHealthChecks,
tokenKey: \ListHealthChecksResponse.nextMarker,
moreResultsKey: \ListHealthChecksResponse.isTruncated,
on: eventLoop,
onPage: onPage
)
}
/// Retrieves a list of the public and private hosted zones that are associated with the current AWS account. The response includes a HostedZones child element for each hosted zone. Amazon Route 53 returns a maximum of 100 items in each response. If you have a lot of hosted zones, you can use the maxitems parameter to list them in groups of up to 100.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listHostedZonesPaginator<Result>(
_ input: ListHostedZonesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListHostedZonesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listHostedZones,
tokenKey: \ListHostedZonesResponse.nextMarker,
moreResultsKey: \ListHostedZonesResponse.isTruncated,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listHostedZonesPaginator(
_ input: ListHostedZonesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListHostedZonesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listHostedZones,
tokenKey: \ListHostedZonesResponse.nextMarker,
moreResultsKey: \ListHostedZonesResponse.isTruncated,
on: eventLoop,
onPage: onPage
)
}
/// Lists the configurations for DNS query logging that are associated with the current AWS account or the configuration that is associated with a specified hosted zone. For more information about DNS query logs, see CreateQueryLoggingConfig. Additional information, including the format of DNS query logs, appears in Logging DNS Queries in the Amazon Route 53 Developer Guide.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listQueryLoggingConfigsPaginator<Result>(
_ input: ListQueryLoggingConfigsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListQueryLoggingConfigsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listQueryLoggingConfigs,
tokenKey: \ListQueryLoggingConfigsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listQueryLoggingConfigsPaginator(
_ input: ListQueryLoggingConfigsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListQueryLoggingConfigsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listQueryLoggingConfigs,
tokenKey: \ListQueryLoggingConfigsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the resource record sets in a specified hosted zone. ListResourceRecordSets returns up to 100 resource record sets at a time in ASCII order, beginning at a position specified by the name and type elements. Sort order ListResourceRecordSets sorts results first by DNS name with the labels reversed, for example: com.example.www. Note the trailing dot, which can change the sort order when the record name contains characters that appear before . (decimal 46) in the ASCII table. These characters include the following: ! " # $ % & ' ( ) * + , - When multiple records have the same DNS name, ListResourceRecordSets sorts results by the record type. Specifying where to start listing records You can use the name and type elements to specify the resource record set that the list begins with: If you do not specify Name or Type The results begin with the first resource record set that the hosted zone contains. If you specify Name but not Type The results begin with the first resource record set in the list whose name is greater than or equal to Name. If you specify Type but not Name Amazon Route 53 returns the InvalidInput error. If you specify both Name and Type The results begin with the first resource record set in the list whose name is greater than or equal to Name, and whose type is greater than or equal to Type. Resource record sets that are PENDING This action returns the most current version of the records. This includes records that are PENDING, and that are not yet available on all Route 53 DNS servers. Changing resource record sets To ensure that you get an accurate listing of the resource record sets for a hosted zone at a point in time, do not submit a ChangeResourceRecordSets request while you're paging through the results of a ListResourceRecordSets request. If you do, some pages may display results without the latest changes while other pages display results with the latest changes. Displaying the next page of results If a ListResourceRecordSets command returns more than one page of results, the value of IsTruncated is true. To display the next page of results, get the values of NextRecordName, NextRecordType, and NextRecordIdentifier (if any) from the response. Then submit another ListResourceRecordSets request, and specify those values for StartRecordName, StartRecordType, and StartRecordIdentifier.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listResourceRecordSetsPaginator<Result>(
_ input: ListResourceRecordSetsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListResourceRecordSetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listResourceRecordSets,
tokenKey: \ListResourceRecordSetsResponse.nextRecordName,
moreResultsKey: \ListResourceRecordSetsResponse.isTruncated,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listResourceRecordSetsPaginator(
_ input: ListResourceRecordSetsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListResourceRecordSetsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listResourceRecordSets,
tokenKey: \ListResourceRecordSetsResponse.nextRecordName,
moreResultsKey: \ListResourceRecordSetsResponse.isTruncated,
on: eventLoop,
onPage: onPage
)
}
}
extension Route53.ListHealthChecksRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Route53.ListHealthChecksRequest {
return .init(
marker: token,
maxItems: self.maxItems
)
}
}
extension Route53.ListHostedZonesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Route53.ListHostedZonesRequest {
return .init(
delegationSetId: self.delegationSetId,
marker: token,
maxItems: self.maxItems
)
}
}
extension Route53.ListQueryLoggingConfigsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Route53.ListQueryLoggingConfigsRequest {
return .init(
hostedZoneId: self.hostedZoneId,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Route53.ListResourceRecordSetsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Route53.ListResourceRecordSetsRequest {
return .init(
hostedZoneId: self.hostedZoneId,
maxItems: self.maxItems,
startRecordIdentifier: self.startRecordIdentifier,
startRecordName: token,
startRecordType: self.startRecordType
)
}
}
| apache-2.0 |
DrabWeb/Booru-chan | Booru-chan/Booru-chan/ViewerController.swift | 1 | 1202 | //
// ViewerController.swift
// Booru-chan
//
// Created by Ushio on 2017-12-05.
//
import Cocoa
import Alamofire
class ViewerController: NSViewController {
private var thumbnailDownloader: ImageDownloader?
private var imageDownloader: ImageDownloader?
@IBOutlet private weak var imageView: NSImageView!
//todo: fix bug where a blank thumbnail is displayed when switching posts while the image is loading
func display(post: BooruPost?, progressHandler: ((Double) -> Void)? = nil) {
thumbnailDownloader?.cancel();
imageDownloader?.cancel();
if post == nil {
imageView.image = nil;
return;
}
thumbnailDownloader = ImageDownloader(url: URL(string: post!.thumbnailUrl)!);
thumbnailDownloader?.download(complete: { thumbnail in
self.imageView.image = thumbnail;
});
imageDownloader = ImageDownloader(url: URL(string: post!.imageUrl)!);
imageDownloader?.download(progress: { progress in
progressHandler?(progress);
}, complete: { image in
self.thumbnailDownloader?.cancel();
self.imageView.image = image;
});
}
}
| gpl-3.0 |
bay2/LetToDo | LetToDo/Define/ImageDefine.swift | 1 | 977 | // Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIImage
typealias Image = UIImage
#elseif os(OSX)
import AppKit.NSImage
typealias Image = NSImage
#endif
// swiftlint:disable file_length
// swiftlint:disable type_body_length
enum Asset: String {
case toDoListAdd = "ToDoListAdd"
case toDoListDone = "ToDoListDone"
case toDoListInProgess = "ToDoListInProgess"
case homeAdd = "HomeAdd"
case launchScreen = "LaunchScreen"
case navBarMuen = "NavBarMuen"
case navBarSetting = "NavBarSetting"
case swipeDelBtn = "SwipeDelBtn"
case swipeDelBtnHighligt = "SwipeDelBtnHighligt"
case taskChangeBtn = "TaskChangeBtn"
case taskChangeHighlightBtn = "TaskChangeHighlightBtn"
var image: Image {
return Image(asset: self)
}
}
// swiftlint:enable type_body_length
extension Image {
convenience init!(asset: Asset) {
self.init(named: asset.rawValue)
}
}
| mit |
netguru/inbbbox-ios | Inbbbox/Source Files/Views/Custom/SeparatorView.swift | 1 | 1274 | //
// SeparatorView.swift
// Inbbbox
//
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
final class SeparatorView: UIView {
private let axis: Axis
private let thickness: Double
private let color: UIColor
@available(*, unavailable, message: "Use init(axis: thickness: color:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(axis: Axis, thickness: Double, color: UIColor) {
self.axis = axis
self.thickness = thickness
self.color = color
super.init(frame: .zero)
setupProperties()
}
private func setupProperties() {
backgroundColor = color
setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: axis == .vertical ? .vertical : .horizontal)
}
override var intrinsicContentSize: CGSize {
switch axis {
case .vertical:
return CGSize(width: UIViewNoIntrinsicMetric, height: CGFloat(thickness))
case .horizontal:
return CGSize(width: CGFloat(thickness), height: UIViewNoIntrinsicMetric)
}
}
}
extension SeparatorView {
enum Axis {
case vertical
case horizontal
}
}
| gpl-3.0 |
vimeo/VimeoNetworking | Sources/Shared/Models/VIMUpload.swift | 1 | 5160 | //
// VIMUpload.swift
// Pods
//
// Created by Lehrer, Nicole on 4/18/18.
//
// 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
/// Encapsulates the upload-related information on a video object.
public class VIMUpload: VIMModelObject {
/// The approach for uploading the video, expressed as a Swift-only enum
///
/// - streaming: Two-step upload without using tus; this will be deprecated
/// - post: Upload with an HTML form or POST
/// - pull: Upload from a video file that already exists on the internet
/// - tus: Upload using the open-source tus protocol
public struct UploadApproach: RawRepresentable, Equatable {
public typealias RawValue = String
public init?(rawValue: String) {
self.rawValue = rawValue
}
public var rawValue: String
public static let Streaming = UploadApproach(rawValue: "streaming")!
public static let Post = UploadApproach(rawValue: "post")!
public static let Pull = UploadApproach(rawValue: "pull")!
public static let Tus = UploadApproach(rawValue: "tus")!
}
/// The status code for the availability of the uploaded video, expressed as a Swift-only enum
///
/// - complete: The upload is complete
/// - error: The upload ended with an error
/// - underway: The upload is in progress
public enum UploadStatus: String {
case complete
case error
case inProgress = "in_progress"
}
/// The approach for uploading the video
@objc dynamic public private(set) var approach: String?
/// The file size in bytes of the uploaded video
@objc dynamic public private(set) var size: NSNumber?
/// The status code for the availability of the uploaded video
@objc dynamic public private(set) var status: String?
/// The HTML form for uploading a video through the post approach
@objc dynamic public private(set) var form: String?
/// The link of the video to capture through the pull approach
@objc dynamic public private(set) var link: String?
/// The URI for completing the upload
@objc dynamic public private(set) var completeURI: String?
/// The redirect URL for the upload app
@objc dynamic public private(set) var redirectURL: String?
/// The link for sending video file data
@objc dynamic public private(set) var uploadLink: String?
/// The approach for uploading the video, mapped to a Swift-only enum
public private(set) var uploadApproach: UploadApproach?
/// The status code for the availability of the uploaded video, mapped to a Swift-only enum
public private(set) var uploadStatus: UploadStatus?
public private(set) var gcs: [GCS]?
@objc internal private(set) var gcsStorage: NSArray?
// MARK: - VIMMappable Protocol Conformance
/// Called when automatic object mapping completes
public override func didFinishMapping() {
if let approachString = self.approach {
self.uploadApproach = UploadApproach(rawValue: approachString)
}
if let statusString = self.status {
self.uploadStatus = UploadStatus(rawValue: statusString)
}
self.gcs = [GCS]()
self.gcsStorage?.forEach({ (object) in
guard let dictionary = object as? [String: Any], let gcsObject = try? VIMObjectMapper.mapObject(responseDictionary: dictionary) as GCS else {
return
}
self.gcs?.append(gcsObject)
})
}
/// Maps the property name that mirrors the literal JSON response to another property name.
/// Typically used to rename a property to one that follows this project's naming conventions.
///
/// - Returns: A dictionary where the keys are the JSON response names and the values are the new property names.
public override func getObjectMapping() -> Any {
return ["complete_uri": "completeURI", "redirect_url": "redirectURL", "gcs": "gcsStorage"]
}
}
| mit |
Ben21hao/edx-app-ios-enterprise-new | Source/RouterEnvironment.swift | 3 | 1267 | //
// RouterEnvironment.swift
// edX
//
// Created by Akiva Leffert on 11/30/15.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
@objc class RouterEnvironment: NSObject, OEXAnalyticsProvider, OEXConfigProvider, DataManagerProvider, OEXInterfaceProvider, NetworkManagerProvider, ReachabilityProvider, OEXRouterProvider, OEXSessionProvider, OEXStylesProvider {
let analytics: OEXAnalytics
let config: OEXConfig
let dataManager: DataManager
let reachability: Reachability
let interface: OEXInterface?
let networkManager: NetworkManager
weak var router: OEXRouter?
let session: OEXSession
let styles: OEXStyles
init(
analytics: OEXAnalytics,
config: OEXConfig,
dataManager: DataManager,
interface: OEXInterface?,
networkManager: NetworkManager,
reachability: Reachability,
session: OEXSession,
styles: OEXStyles
)
{
self.analytics = analytics
self.config = config
self.dataManager = dataManager
self.interface = interface
self.networkManager = networkManager
self.reachability = reachability
self.session = session
self.styles = styles
super.init()
}
}
| apache-2.0 |
iCrany/iOSExample | iOSExample/Module/CoreTextExample/VC/ICAttachmentLabelDemoVC.swift | 1 | 22362 | //
// ICAttachmentLabelDemoVC.swift
// iOSExample
//
// Created by iCrany on 2018/9/12.
// Copyright © 2018年 iCrany. All rights reserved.
//
import Foundation
enum ICAttachmentDemoType {
case example1 //主要是 UIView / UIImage 的 alignment demo测试
case example2 //主要是 图文混排的实际应用测试,例如是否正确显示 ..., 在文本前面添加图片,在文本背后添加图片,文本的 lineSpacing 参数的设置
case example3 //主要用于测试 UIImage 的布局使用
}
//swiftlint:disable force_cast
class ICAttachmentLabelDemoVC: UIViewController {
private var attachmentDemoType: ICAttachmentDemoType
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(attachmentDemoType: ICAttachmentDemoType = .example1) {
self.attachmentDemoType = attachmentDemoType
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
private func setupUI() {
self.view.backgroundColor = UIColor.white
switch self.attachmentDemoType {
case .example1:
self.setupExample1UI()
case .example2:
self.setupExample2UI()
case .example3:
self.setupExample3UI()
}
}
private func setupExample1UI() {
let attrText: NSMutableAttributedString = NSMutableAttributedString(string: "abg123展开可代发辽阔的积分dkd hfkjahdfjadiuyreiuhsahdkjfhkjhkfsdahsfjh")
let appendAttrText: NSAttributedString = NSAttributedString(string: "--last line change")
let kLabelInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
let kScreenWidth: CGFloat = UIScreen.main.bounds.size.width
let kContentInset: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
let kCustomViewSize: CGSize = CGSize(width: 40, height: 40)
let kLineSpacing: CGFloat = 10
let image = UIImage(named: "jucat.jpeg")
let attachment: ICLabelAttachment = ICLabelAttachment(content: image, contentInset: kContentInset, alignment: ICAttachmentAlignment_CenterY, referenceFont: UIFont.systemFont(ofSize: 15))
attachment.limitSize = CGSize(width: 50, height: 50)
let testAttr: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
testAttr.ic_append(attachment)
testAttr.append(appendAttrText)
let icLabel: ICLabel = ICLabel()
icLabel.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel)
icLabel.attributedString = testAttr
icLabel.lineSpacing = kLineSpacing
let size = icLabel.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(100)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size)
}
let customView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kCustomViewSize.width, height: kCustomViewSize.height))
customView.backgroundColor = UIColor.blue
let viewAttachment: ICLabelAttachment = ICLabelAttachment(content: customView,
contentInset: kContentInset,
alignment: ICAttachmentAlignment_Top,
referenceFont: UIFont.systemFont(ofSize: 15))
let testAttr2: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
testAttr2.ic_append(viewAttachment)
testAttr2.append(appendAttrText)
let icLabel2: ICLabel = ICLabel()
icLabel2.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel2)
icLabel2.font = UIFont.systemFont(ofSize: 20)
icLabel2.lineSpacing = kLineSpacing
icLabel2.attributedString = testAttr2
let size2: CGSize = icLabel2.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel2.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size2)
}
let customView2: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kCustomViewSize.width, height: kCustomViewSize.height))
customView2.backgroundColor = UIColor.blue
let viewAttachment2: ICLabelAttachment = ICLabelAttachment(content: customView2,
contentInset: kContentInset,
alignment: ICAttachmentAlignment_CenterY,
referenceFont: UIFont.systemFont(ofSize: 20))
let testAttr3: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
testAttr3.ic_append(viewAttachment2)
testAttr3.append(appendAttrText)
let icLabel3: ICLabel = ICLabel()
icLabel3.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel3)
icLabel3.font = UIFont.systemFont(ofSize: 20)
icLabel3.lineSpacing = kLineSpacing
icLabel3.attributedString = testAttr3
let size3: CGSize = icLabel3.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel3.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel2.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size3)
}
let customView3: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kCustomViewSize.width, height: kCustomViewSize.height))
customView3.backgroundColor = UIColor.blue
let viewAttachment3: ICLabelAttachment = ICLabelAttachment(content: customView3,
contentInset: kContentInset,
alignment: ICAttachmentAlignment_Bottom,
referenceFont: UIFont.systemFont(ofSize: 20))
let testAttr4: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
testAttr4.ic_append(viewAttachment3)
testAttr4.append(appendAttrText)
let icLabel4: ICLabel = ICLabel()
icLabel4.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel4)
icLabel4.font = UIFont.systemFont(ofSize: 20)
icLabel4.lineSpacing = kLineSpacing
icLabel4.attributedString = testAttr4
let size4: CGSize = icLabel4.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel4.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel3.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size4)
}
//支持 UIView 里面添加图片的形式
let customView4: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kCustomViewSize.width, height: kCustomViewSize.height))
let customImgView: UIImageView = UIImageView(image: UIImage(named: "jucat.jpeg"))
customView4.addSubview(customImgView)
customImgView.snp.makeConstraints { (maker) in
maker.center.equalToSuperview()
maker.size.equalTo(CGSize(width: 20, height: 20))
}
customView4.backgroundColor = UIColor.blue
let viewAttachment4: ICLabelAttachment = ICLabelAttachment(content: customView4,
contentInset: kContentInset,
alignment: ICAttachmentAlignment_CenterY,
referenceFont: UIFont.systemFont(ofSize: 20))
let testAttr5: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
testAttr5.ic_append(viewAttachment4)
testAttr5.append(appendAttrText)
let icLabel5: ICLabel = ICLabel()
icLabel5.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel5)
icLabel5.font = UIFont.systemFont(ofSize: 20)
icLabel5.lineSpacing = kLineSpacing
icLabel5.attributedString = testAttr5
let size5: CGSize = icLabel5.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel5.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel4.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size5)
}
}
private func setupExample2UI() {
let attrText: NSMutableAttributedString = NSMutableAttributedString(string: "哈中test中文强势进入😁😁😁😁😁😁😀😀😀😀😀🧀🧀🧀🧀🥔🥔🥔🥔🥔🥔🥔🥔🥔🥔🥔🍑🍑🍑🍎🍎🍎🍎🍎🍏🍏🍏🍏🍏( ̄︶ ̄)↗( ̄︶ ̄)↗( ̄︶ ̄)↗( ̄︶ ̄)↗[]~( ̄▽ ̄)~*[]~( ̄▽ ̄)~*[]~( ̄▽ ̄)~*b╭╮( ̄▽ ̄)╭╮( ̄▽ ̄)╭╮( ̄▽ ̄)╭╮( ̄▽ ̄)╭( ̄. ̄)( ̄. ̄)( ̄. ̄)( ̄. ̄)🀏🀏🀏🀏🀏🀡🀡🀡🀡🀡🀞🀞🀔🀊🀀速度快回复肯定会开发可来得及分类的空间烂大街法律框架爱离开对方就流口水的了肯定是解放路口就冻死了卡减肥了空间了空间大浪费空间了空间撒蝶恋蜂狂氪金大佬开房记录卡机了看见对方立刻据了解")
let kLabelInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
let kScreenWidth: CGFloat = UIScreen.main.bounds.size.width
let kContentInset: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
let kCustomViewSize: CGSize = CGSize(width: 40, height: 40)
let kLabelFont: UIFont = UIFont.systemFont(ofSize: 15)
let kLabelLineSpacing: CGFloat = 0
let maxSize: CGSize = CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude)
let customView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kCustomViewSize.width, height: kCustomViewSize.height))
let customImgView: UIImageView = UIImageView(image: UIImage(named: "jucat.jpeg"))
customView.backgroundColor = UIColor.blue
customView.addSubview(customImgView)
customImgView.snp.makeConstraints { (maker) in
maker.center.equalToSuperview()
maker.size.equalTo(kCustomViewSize)
}
let viewAttachment: ICLabelAttachment = ICLabelAttachment(content: customView,
contentInset: kContentInset,
alignment: ICAttachmentAlignment_Top,
referenceFont: kLabelFont)
let tempAttrText: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
let attachmentHighlight: ICHighlight = ICHighlight()
attachmentHighlight.tapAction = { [weak self] in
guard let sSelf = self else { return }
let vc = UIAlertController(title: "You click attachment view", message: nil, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: UIAlertAction.Style.default, handler: { (_) in
vc.dismiss(animated: true, completion: nil)
})
vc.addAction(confirmAction)
sSelf.present(vc, animated: true, completion: nil)
}
tempAttrText.ic_insert(viewAttachment, highlight: attachmentHighlight, at: 0)
let linkStr: String = "\(kEllipsisCharacter)全文"
let seeMore: NSMutableAttributedString = NSMutableAttributedString(string: linkStr)
let expendLabel: ICLabel = ICLabel()
expendLabel.font = kLabelFont
expendLabel.attributedString = seeMore //TODO: 考虑一下这里的这个接口设计的问题,字体、颜色竟然跟 attributedString 的设置先后有关系
expendLabel.backgroundColor = UIColor.clear
seeMore.ic_setFont(kLabelFont)
seeMore.ic_setForegroundColor(UIColor.blue, range: NSRange(location: kEllipsisCharacter.count, length: linkStr.count - kEllipsisCharacter.count))
let expendLabelSize: CGSize = expendLabel.sizeThatFits(maxSize)
let expendLabelRect: CGRect = seeMore.boundingRect(with: maxSize,
options: [.usesFontLeading, .usesLineFragmentOrigin],
context: nil) //不能使用该值 expendLabelRect 中的 size 字段,则会导致绘制的文字显示不出来
// expendLabel.frame = CGRect(origin: .zero, size: expendLabelRect.size)
expendLabel.frame = CGRect(origin: .zero, size: expendLabelSize)
print("expendLabelSize: \(expendLabelSize) expendLabelRect: \(expendLabelRect)")
let truncationToken: NSMutableAttributedString = NSMutableAttributedString()
truncationToken.ic_appendAttachmentContent(expendLabel,
contentInsets: UIEdgeInsets(top: 4, left: 0, bottom: 0, right: 0), //这里做一下微调,因为 ICLabel 的 sizeThatFits: 函数计算出来的大小并不是 sizeThatFits 的那种,所以这里需要进行微调
alignment: ICAttachmentAlignment_CenterY,
referenceFont: expendLabel.font)
let icLabel: ICLabel = ICLabel()
icLabel.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel)
icLabel.font = kLabelFont
icLabel.lineSpacing = kLabelLineSpacing
icLabel.numberOfLines = 2
icLabel.truncationToken = truncationToken
icLabel.attributedString = tempAttrText.mutableCopy() as? NSMutableAttributedString
let size: CGSize = icLabel.sizeThatFits(maxSize)
icLabel.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(100)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size)
}
let hightlight: ICHighlight = ICHighlight()
hightlight.tapAction = {
icLabel.numberOfLines = 0
let canClickLabelSize = icLabel.sizeThatFits(maxSize)
icLabel.snp.updateConstraints { (maker) in
maker.size.equalTo(canClickLabelSize)
}
}
seeMore.ic_setHightlight(hightlight, range: NSRange(location: kEllipsisCharacter.count, length: seeMore.length - kEllipsisCharacter.count))
let customView2: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kCustomViewSize.width, height: kCustomViewSize.height))
let customImgView2: UIImageView = UIImageView(image: UIImage(named: "jucat.jpeg"))
customView2.addSubview(customImgView2)
customImgView2.snp.makeConstraints { (maker) in
maker.center.equalToSuperview()
maker.size.equalTo(kCustomViewSize)
}
let viewAttachment2: ICLabelAttachment = ICLabelAttachment(content: customView2,
contentInset: kContentInset,
alignment: ICAttachmentAlignment_CenterY,
referenceFont: kLabelFont)
let tempAttrText2: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
tempAttrText2.ic_insert(viewAttachment2, at: 0)
let icLabel2: ICLabel = ICLabel()
icLabel2.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel2)
icLabel2.font = kLabelFont
icLabel2.lineSpacing = kLabelLineSpacing
icLabel2.attributedString = tempAttrText2.mutableCopy() as? NSMutableAttributedString
let size2: CGSize = icLabel2.sizeThatFits(maxSize)
icLabel2.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size2)
}
let customView3: UIView = UIView(frame: CGRect(x: 0, y: 0, width: kCustomViewSize.width, height: kCustomViewSize.height))
let customImgView3: UIImageView = UIImageView(image: UIImage(named: "jucat.jpeg"))
customView3.backgroundColor = UIColor.blue
customView3.addSubview(customImgView3)
customImgView3.snp.makeConstraints { (maker) in
maker.center.equalToSuperview()
maker.size.equalTo(kCustomViewSize)
}
let viewAttachment3: ICLabelAttachment = ICLabelAttachment(content: customView3, contentInset: kContentInset, alignment: ICAttachmentAlignment_Bottom, referenceFont: kLabelFont)
let tempAttrText3: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
tempAttrText3.ic_insert(viewAttachment3, at: 0)
let icLabel3: ICLabel = ICLabel()
icLabel3.backgroundColor = UIColor.lightGray
self.view.addSubview(icLabel3)
icLabel3.font = kLabelFont
icLabel3.lineSpacing = kLabelLineSpacing
icLabel3.attributedString = tempAttrText3.mutableCopy() as? NSMutableAttributedString
let size3: CGSize = icLabel3.sizeThatFits(maxSize)
icLabel3.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel2.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size3)
}
}
private func setupExample3UI() {
let attrText: NSMutableAttributedString = NSMutableAttributedString(string: "abg123展开可代发辽阔的积分dkd hfkjahdfjadiuyreiuhsahdkjfhkjhkfsdahsfjh")
let kLabelInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
let kScreenWidth: CGFloat = UIScreen.main.bounds.size.width
let kContentInset: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
let kFont: UIFont = UIFont.systemFont(ofSize: 15)
let kLabelLineSpacing: CGFloat = 10
let testAttr: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
let image = UIImage(named: "jucat.jpeg")
let attachment: ICLabelAttachment = ICLabelAttachment(content: image, contentInset: kContentInset, alignment: ICAttachmentAlignment_Top, referenceFont: kFont)
attachment.limitSize = CGSize(width: 50, height: 50)
testAttr.ic_insert(attachment, at: 0)
let appendAttrText: NSAttributedString = NSAttributedString(string: "--last line change")
testAttr.append(appendAttrText.mutableCopy() as! NSMutableAttributedString)
let icLabel: ICLabel = ICLabel()
icLabel.backgroundColor = UIColor.lightGray
icLabel.lineSpacing = kLabelLineSpacing
self.view.addSubview(icLabel)
icLabel.attributedString = testAttr
let size = icLabel.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(100)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size)
}
let testAttr2: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
let image2 = UIImage(named: "jucat.jpeg")
let attachment2: ICLabelAttachment = ICLabelAttachment(content: image2, contentInset: kContentInset, alignment: ICAttachmentAlignment_CenterY, referenceFont: kFont)
attachment2.limitSize = CGSize(width: 50, height: 50)
testAttr2.ic_insert(attachment2, at: 0)
testAttr2.append(appendAttrText.mutableCopy() as! NSMutableAttributedString)
let icLabel2: ICLabel = ICLabel()
icLabel2.backgroundColor = UIColor.lightGray
icLabel2.lineSpacing = kLabelLineSpacing
self.view.addSubview(icLabel2)
icLabel2.attributedString = testAttr2
let size2 = icLabel.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel2.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size2)
}
let testAttr3: NSMutableAttributedString = attrText.mutableCopy() as! NSMutableAttributedString
let image3 = UIImage(named: "jucat.jpeg")
let attachment3: ICLabelAttachment = ICLabelAttachment(content: image3, contentInset: kContentInset, alignment: ICAttachmentAlignment_Bottom, referenceFont: kFont)
attachment3.limitSize = CGSize(width: 50, height: 50)
testAttr3.ic_insert(attachment3, at: 0)
testAttr3.append(appendAttrText.mutableCopy() as! NSMutableAttributedString)
let icLabel3: ICLabel = ICLabel()
icLabel3.backgroundColor = UIColor.lightGray
icLabel3.lineSpacing = kLabelLineSpacing
self.view.addSubview(icLabel3)
icLabel3.attributedString = testAttr3
let size3 = icLabel.sizeThatFits(CGSize(width: kScreenWidth - kLabelInsets.left - kLabelInsets.right, height: CGFloat.greatestFiniteMagnitude))
icLabel3.snp.makeConstraints { (maker) in
maker.top.equalTo(icLabel2.snp.bottom).offset(20)
maker.left.equalToSuperview().offset(kLabelInsets.left)
maker.size.equalTo(size3)
}
}
}
| mit |
mobilabsolutions/jenkins-ios | JenkinsiOS/Model/Favorite.swift | 1 | 1993 | //
// Favorite.swift
// JenkinsiOS
//
// Created by Robert on 01.10.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import Foundation
class Favorite: NSObject, NSCoding {
/// An enum describing the type of a favorite
///
/// - job: The favorite is a job
/// - build: The favorite is a build
enum FavoriteType: String {
case job = "Job"
case build = "Build"
case folder = "Folder"
}
/// The type of the Favorite
var type: FavoriteType
/// The url that the favorite is associated with
var url: URL
/// The account that the account is associated with
var account: Account?
/// Initialize a Favorite
///
/// - parameter url: The url that the favorite should be associated with
/// - parameter type: The favorite's type
/// - parameter account: The account associated with the favorite
///
/// - returns: An initialized Favorite object
init(url: URL, type: FavoriteType, account: Account?) {
self.type = type
self.url = url
self.account = account
}
required init?(coder aDecoder: NSCoder) {
guard let url = aDecoder.decodeObject(forKey: "url") as? URL, let type = aDecoder.decodeObject(forKey: "type") as? String, let accountUrl = aDecoder.decodeObject(forKey: "accountUrl") as? URL
else { return nil }
self.url = url
self.type = FavoriteType(rawValue: type)!
AccountManager.manager.update()
account = AccountManager.manager.accounts.first(where: { $0.baseUrl == accountUrl })
}
func encode(with aCoder: NSCoder) {
aCoder.encode(url, forKey: "url")
aCoder.encode(type.rawValue, forKey: "type")
aCoder.encode(account?.baseUrl, forKey: "accountUrl")
}
override func isEqual(_ object: Any?) -> Bool {
guard let fav = object as? Favorite
else { return false }
return (fav.url == url) && (fav.type == type)
}
}
| mit |
borglab/SwiftFusion | Tests/SwiftFusionTests/Inference/GaussianFactorGraphTests.swift | 1 | 5018 | // Copyright 2020 The SwiftFusion Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import _Differentiation
import Foundation
import TensorFlow
import XCTest
import PenguinStructures
import SwiftFusion
class GaussianFactorGraphTests: XCTestCase {
/// Stores a factor in the graph and evaluates the graph error vector.
func testStoreFactors() {
var x = VariableAssignments()
let id1 = x.store(Vector1(1))
let id2 = x.store(Vector2(2, 3))
let A = Array2(
Tuple2(Vector1(10), Vector2(100, 1000)),
Tuple2(Vector1(-10), Vector2(-100, -1000))
)
let b = Vector2(8, 9)
var graph = GaussianFactorGraph(zeroValues: x.tangentVectorZeros)
let f1 = JacobianFactor(jacobian: A, error: b, edges: Tuple2(id1, id2))
graph.store(f1)
// `b - A * x`
let expected = Vector2(
3210 - 8,
-3210 - 9
)
XCTAssertEqual(graph.errorVectors(at: x)[0, factorType: type(of: f1)], expected)
}
/// Adds some scalar jacobians and tests that the resulting graph produces the correct error
/// vectors.
func testAddScalarJacobians() {
var x = VariableAssignments()
let id1 = x.store(Vector2(1, 2))
let id2 = x.store(Vector2(3, 4))
let id3 = x.store(Vector3(5, 6, 7))
var jacobians = GaussianFactorGraph(zeroValues: x.tangentVectorZeros)
jacobians.addScalarJacobians(10)
let errorVectors = jacobians.errorVectors(at: x)
XCTAssertEqual(
errorVectors[0, factorType: ScalarJacobianFactor<Vector2>.self], Vector2(10, 20))
XCTAssertEqual(
errorVectors[1, factorType: ScalarJacobianFactor<Vector2>.self], Vector2(30, 40))
XCTAssertEqual(
errorVectors[0, factorType: ScalarJacobianFactor<Vector3>.self], Vector3(50, 60, 70))
let linearComponent = jacobians.errorVectors_linearComponent(at: x)
XCTAssertEqual(
linearComponent[0, factorType: ScalarJacobianFactor<Vector2>.self], Vector2(10, 20))
XCTAssertEqual(
linearComponent[1, factorType: ScalarJacobianFactor<Vector2>.self], Vector2(30, 40))
XCTAssertEqual(
linearComponent[0, factorType: ScalarJacobianFactor<Vector3>.self], Vector3(50, 60, 70))
let linearComponent_adjoint =
jacobians.errorVectors_linearComponent_adjoint(linearComponent)
XCTAssertEqual(linearComponent_adjoint[id1], Vector2(100, 200))
XCTAssertEqual(linearComponent_adjoint[id2], Vector2(300, 400))
XCTAssertEqual(linearComponent_adjoint[id3], Vector3(500, 600, 700))
}
func testJacobianFactorSanity() {
var x = VariableAssignments()
let id0 = x.store(Vector3(1.0, 1.0, 1.0))
let id1 = x.store(Vector3(0.5, 0.5, 0.5))
let id2 = x.store(Vector3(1.0/3, 1.0/3, 1.0/3))
// let terms = [Matrix3.identity, 2 * Matrix3.identity, 3 * Matrix3.identity]
let jf = JacobianFactor<Array3<Tuple3<Vector3, Vector3, Vector3>>, Vector3>(
jacobians: Matrix3.identity, 2 * Matrix3.identity, 3 * Matrix3.identity,
error: Vector3(1, 2, 3), edges: Tuple3(id0, id1, id2))
var gfg = GaussianFactorGraph(zeroValues: x)
gfg.store(jf)
let r = gfg.errorVectors(at: x)
assertAllKeyPathEqual(r[0, factorType: JacobianFactor<Array3<Tuple3<Vector3, Vector3, Vector3>>, Vector3>.self],
Vector3(2, 1, 0), accuracy: 1e-10)
}
/// Test Ax.
func testMultiplication() {
let A = SimpleGaussianFactorGraph.create()
let Ax = A.errorVectors_linearComponent(at: SimpleGaussianFactorGraph.correctDelta())
XCTAssertEqual(Ax[0, factorType: JacobianFactor2x2_1.self], Vector2(-1, -1))
XCTAssertEqual(Ax[0, factorType: JacobianFactor2x2_2.self], Vector2(2, -1))
XCTAssertEqual(Ax[1, factorType: JacobianFactor2x2_2.self], Vector2(0, 1))
XCTAssertEqual(Ax[2, factorType: JacobianFactor2x2_2.self], Vector2(-1, 1.5))
}
/// Test A^Ty
func testTransposeMultiplication() {
var y = AllVectors()
y.store(Vector2(0, 0), factorType: JacobianFactor2x2_1.self)
y.store(Vector2(15, 0), factorType: JacobianFactor2x2_2.self)
y.store(Vector2(0, -5), factorType: JacobianFactor2x2_2.self)
y.store(Vector2(-7.5, -5), factorType: JacobianFactor2x2_2.self)
let A = SimpleGaussianFactorGraph.create()
let ATy = A.errorVectors_linearComponent_adjoint(y)
XCTAssertEqual(ATy[SimpleGaussianFactorGraph.l1ID], Vector2(-37.5, -50))
XCTAssertEqual(ATy[SimpleGaussianFactorGraph.x1ID], Vector2(-150, 25))
XCTAssertEqual(ATy[SimpleGaussianFactorGraph.x2ID], Vector2(187.5, 25))
}
}
| apache-2.0 |
slavapestov/swift | test/SILGen/unowned.swift | 3 | 5221 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func takeClosure(fn: () -> Int) {}
class C {
func f() -> Int { return 42 }
}
struct A {
unowned var x: C
}
_ = A(x: C())
// CHECK-LABEL: sil hidden @_TFV7unowned1AC
// CHECK: bb0([[X:%.*]] : $C, %1 : $@thin A.Type):
// CHECK: [[X_UNOWNED:%.*]] = ref_to_unowned [[X]] : $C to $@sil_unowned C
// CHECK: unowned_retain [[X_UNOWNED]]
// CHECK: strong_release [[X]]
// CHECK: [[A:%.*]] = struct $A ([[X_UNOWNED]] : $@sil_unowned C)
// CHECK: return [[A]]
// CHECK: }
protocol P {}
struct X: P {}
struct AddressOnly {
unowned var x: C
var p: P
}
_ = AddressOnly(x: C(), p: X())
// CHECK-LABEL: sil hidden @_TFV7unowned11AddressOnlyC
// CHECK: bb0([[RET:%.*]] : $*AddressOnly, [[X:%.*]] : $C, {{.*}}):
// CHECK: [[X_ADDR:%.*]] = struct_element_addr [[RET]] : $*AddressOnly, #AddressOnly.x
// CHECK: [[X_UNOWNED:%.*]] = ref_to_unowned [[X]] : $C to $@sil_unowned C
// CHECK: unowned_retain [[X_UNOWNED]] : $@sil_unowned C
// CHECK: store [[X_UNOWNED]] to [[X_ADDR]]
// CHECK: strong_release [[X]]
// CHECK: }
// CHECK-LABEL: sil hidden @_TF7unowned5test0FT1cCS_1C_T_ : $@convention(thin) (@owned C) -> () {
func test0(let c c: C) {
// CHECK: bb0(%0 : $C):
var a: A
// CHECK: [[A1:%.*]] = alloc_box $A
// CHECK: [[PBA:%.*]] = project_box [[A1]]
// CHECK: [[A:%.*]] = mark_uninitialized [var] [[PBA]]
unowned var x = c
// CHECK: [[X:%.*]] = alloc_box $@sil_unowned C
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK-NEXT: [[T2:%.*]] = ref_to_unowned %0 : $C to $@sil_unowned C
// CHECK-NEXT: unowned_retain [[T2]] : $@sil_unowned C
// CHECK-NEXT: store [[T2]] to [[PBX]] : $*@sil_unowned C
a.x = c
// CHECK-NEXT: [[T1:%.*]] = struct_element_addr [[A]] : $*A, #A.x
// CHECK-NEXT: [[T2:%.*]] = ref_to_unowned %0 : $C
// CHECK-NEXT: unowned_retain [[T2]] : $@sil_unowned C
// CHECK-NEXT: assign [[T2]] to [[T1]] : $*@sil_unowned C
a.x = x
// CHECK-NEXT: [[T2:%.*]] = load [[PBX]] : $*@sil_unowned C
// CHECK-NEXT: strong_retain_unowned [[T2]] : $@sil_unowned C
// CHECK-NEXT: [[T3:%.*]] = unowned_to_ref [[T2]] : $@sil_unowned C to $C
// CHECK-NEXT: [[XP:%.*]] = struct_element_addr [[A]] : $*A, #A.x
// CHECK-NEXT: [[T4:%.*]] = ref_to_unowned [[T3]] : $C to $@sil_unowned C
// CHECK-NEXT: unowned_retain [[T4]] : $@sil_unowned C
// CHECK-NEXT: assign [[T4]] to [[XP]] : $*@sil_unowned C
// CHECK-NEXT: strong_release [[T3]] : $C
}
// CHECK-LABEL: sil hidden @{{.*}}unowned_local
func unowned_local() -> C {
// CHECK: [[c:%.*]] = apply
let c = C()
// CHECK: [[uc:%.*]] = alloc_box $@sil_unowned C, let, name "uc"
// CHECK-NEXT: [[PB:%.*]] = project_box [[uc]]
// CHECK-NEXT: [[tmp1:%.*]] = ref_to_unowned [[c]] : $C to $@sil_unowned C
// CHECK-NEXT: unowned_retain [[tmp1]]
// CHECK-NEXT: store [[tmp1]] to [[PB]]
unowned let uc = c
// CHECK-NEXT: [[tmp2:%.*]] = load [[PB]]
// CHECK-NEXT: strong_retain_unowned [[tmp2]]
// CHECK-NEXT: [[tmp3:%.*]] = unowned_to_ref [[tmp2]]
return uc
// CHECK-NEXT: strong_release [[uc]]
// CHECK-NEXT: strong_release [[c]]
// CHECK-NEXT: return [[tmp3]]
}
// <rdar://problem/16877510> capturing an unowned let crashes in silgen
func test_unowned_let_capture(aC : C) {
unowned let bC = aC
takeClosure { bC.f() }
}
// CHECK-LABEL: sil shared @_TFF7unowned24test_unowned_let_captureFCS_1CT_U_FT_Si : $@convention(thin) (@owned @sil_unowned C) -> Int {
// CHECK: bb0([[ARG:%.*]] : $@sil_unowned C):
// CHECK-NEXT: debug_value %0 : $@sil_unowned C, let, name "bC", argno 1
// CHECK-NEXT: strong_retain_unowned [[ARG]] : $@sil_unowned C
// CHECK-NEXT: [[UNOWNED_ARG:%.*]] = unowned_to_ref [[ARG]] : $@sil_unowned C to $C
// CHECK-NEXT: [[FUN:%.*]] = class_method [[UNOWNED_ARG]] : $C, #C.f!1 : (C) -> () -> Int , $@convention(method) (@guaranteed C) -> Int
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[UNOWNED_ARG]]) : $@convention(method) (@guaranteed C) -> Int
// CHECK-NEXT: strong_release [[UNOWNED_ARG]]
// CHECK-NEXT: unowned_release [[ARG]] : $@sil_unowned C
// CHECK-NEXT: return [[RESULT]] : $Int
// <rdar://problem/16880044> unowned let properties don't work as struct and class members
class TestUnownedMember {
unowned let member : C
init(inval: C) {
self.member = inval
}
}
// CHECK-LABEL: sil hidden @_TFC7unowned17TestUnownedMemberc
// CHECK: bb0(%0 : $C, %1 : $TestUnownedMember):
// CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] %1 : $TestUnownedMember
// CHECK: [[FIELDPTR:%.*]] = ref_element_addr [[SELF]] : $TestUnownedMember, #TestUnownedMember.member
// CHECK: [[INVAL:%.*]] = ref_to_unowned %0 : $C to $@sil_unowned C
// CHECK: unowned_retain [[INVAL]] : $@sil_unowned C
// CHECK: assign [[INVAL]] to [[FIELDPTR]] : $*@sil_unowned C
// CHECK: strong_release %0 : $C
// CHECK: return [[SELF]] : $TestUnownedMember
// Just verify that lowering an unowned reference to a type parameter
// doesn't explode.
struct Unowned<T: AnyObject> {
unowned var object: T
}
func takesUnownedStruct(z: Unowned<C>) {}
// CHECK-LABEL: sil hidden @_TF7unowned18takesUnownedStructFGVS_7UnownedCS_1C_T_ : $@convention(thin) (@owned Unowned<C>) -> ()
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/01170-getselftypeforcontainer.swift | 11 | 985 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class k<g>: d {
var f: g
init(f: g) {
l. d {
typealias j = je: Int -> Int = {
}
let d: Int = { c, b in
}(f, e)
}
class d {
func l<j where j: h, j: d>(l: j) {
}
func i(k: b) -> <j>(() -> j) -> b {
}
class j {
func y((Any, j))(v: (Any, AnyObject)) {
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
}
y q<x> {
}
o n {
}
class r {
func s() -> p {
}
}
class w: r, n {
}
func b<c {
enum b {
}
}
}
class d<j : i, f : i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
}
protocol e {
}
protocol i : d { func d
| apache-2.0 |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blog Details/BlogDetailsViewController+FAB.swift | 1 | 1513 |
extension BlogDetailsViewController {
/// Make a create button coordinator with
/// - Returns: CreateButtonCoordinator with new post, page, and story actions.
@objc func makeCreateButtonCoordinator() -> CreateButtonCoordinator {
let newPage = { [weak self] in
let controller = self?.tabBarController as? WPTabBarController
let blog = controller?.currentOrLastBlog()
controller?.showPageEditor(forBlog: blog)
}
let newPost = { [weak self] in
let controller = self?.tabBarController as? WPTabBarController
controller?.showPostTab(completion: {
self?.startAlertTimer()
})
}
let newStory = { [weak self] in
let controller = self?.tabBarController as? WPTabBarController
let blog = controller?.currentOrLastBlog()
controller?.showStoryEditor(forBlog: blog)
}
let source = "my_site"
var actions: [ActionSheetItem] = []
if shouldShowNewStory {
actions.append(StoryAction(handler: newStory, source: source))
}
actions.append(PostAction(handler: newPost, source: source))
actions.append(PageAction(handler: newPage, source: source))
let coordinator = CreateButtonCoordinator(self, actions: actions, source: source)
return coordinator
}
private var shouldShowNewStory: Bool {
return blog.supports(.stories) && !UIDevice.isPad()
}
}
| gpl-2.0 |
AdaptiveMe/adaptive-arp-darwin | adaptive-arp-rt/AdaptiveArpRtiOSTests/FileSystemTest.swift | 1 | 3063 | /*
* =| ADAPTIVE RUNTIME PLATFORM |=======================================================================================
*
* (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
*
* 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.
*
* Original author:
*
* * Carlos Lozano Diez
* <http://github.com/carloslozano>
* <http://twitter.com/adaptivecoder>
* <mailto:carlos@adaptive.me>
*
* Contributors:
*
* * Ferran Vila Conesa
* <http://github.com/fnva>
* <http://twitter.com/ferran_vila>
* <mailto:ferran.vila.conesa@gmail.com>
*
* =====================================================================================================================
*/
import XCTest
import AdaptiveArpApi
/**
* FileSystem delegate tests class
*/
class FileSystemTest: XCTestCase {
/**
Constructor.
*/
override func setUp() {
super.setUp()
AppRegistryBridge.sharedInstance.getLoggingBridge().setDelegate(LoggingDelegate())
AppRegistryBridge.sharedInstance.getPlatformContext().setDelegate(AppContextDelegate())
AppRegistryBridge.sharedInstance.getPlatformContextWeb().setDelegate(AppContextWebviewDelegate())
AppRegistryBridge.sharedInstance.getFileSystemBridge().setDelegate(FileSystemDelegate())
}
/**
Test for obtaining the current display orientation
*/
func testFileSystem() {
XCTAssert(AppRegistryBridge.sharedInstance.getFileSystemBridge().getApplicationCacheFolder() != nil, "Error getting the cache folder. See log")
XCTAssert(AppRegistryBridge.sharedInstance.getFileSystemBridge().getApplicationCloudFolder() != nil, "Error getting the cloud folder. See log")
XCTAssert(AppRegistryBridge.sharedInstance.getFileSystemBridge().getApplicationDocumentsFolder() != nil, "Error getting the documents folder. See log")
XCTAssert(AppRegistryBridge.sharedInstance.getFileSystemBridge().getApplicationFolder() != nil, "Error getting the application folder. See log")
XCTAssert(AppRegistryBridge.sharedInstance.getFileSystemBridge().getApplicationProtectedFolder() != nil, "Error getting the protected folder. See log")
XCTAssert(AppRegistryBridge.sharedInstance.getFileSystemBridge().getSystemExternalFolder() != nil, "Error getting the external folder. See log")
XCTAssert(AppRegistryBridge.sharedInstance.getFileSystemBridge().getSeparator() == "/", "Error getting the separator. See log")
}
}
| apache-2.0 |
thorfroelich/TaylorSource | Sources/Base/Factory.swift | 2 | 20470 | //
// Created by Daniel Thorpe on 16/04/2015.
//
// MARK: - Protocols
/// Protocol to expose a reuse identifier for cells and views.
public protocol ReusableElement {
/// reuseIdentifier a String property
static var reuseIdentifier: String { get }
}
/// Protocol Protocol to expose a nib for a view.
public protocol ReusableView: ReusableElement {
static var nib: UINib { get }
}
/**
Utility function to instanctiate a view.
*/
public func loadReusableViewFromNib<T: UIView where T: ReusableView>(owner: AnyObject? = .None, options: [NSObject: AnyObject]? = .None) -> T? {
return NSBundle(forClass: T.self).loadNibNamed(T.reuseIdentifier, owner: owner, options: options).last as? T
}
/**
An enum type for describing cells or views as either classes, nibs or dynamic.
A dynamic view is anything the cell based host view already knows how to create.
This includes storyboard prototype cells and manually registered classes or nibs.
It helps if ReusableView is implemented on custom cells. E.g.
.DynamicWithIdentifier(MyCell.reuseIdentifier)
.ClassWithIdentifier(MyCell.self, MyCell.reuseIdentifier)
.NibWithIdentifier(MyCell.nib, MyCell.reuseIdentifier)
*/
public enum ReusableViewDescriptor {
case DynamicWithIdentifier(String)
case ClassWithIdentifier(AnyClass, String)
case NibWithIdentifier(UINib, String)
}
/**
An enum type which describes supplementary elements. For standard
headers and footers in UITableView and UICollectionView its simple
to use .Header and .Footer, but for arbitrary supplementary element
kinds. There is .Custom("My Custom Supplementary View").
*/
public enum SupplementaryElementKind {
case Header, Footer
case Custom(String)
}
struct SupplementaryElementIndex {
let kind: SupplementaryElementKind
let key: String
}
/**
Protocol for registering and dequeuing cells from a cell based view.
TaylorSource has implementations for UITableView and UICollectionView.
*/
public protocol ReusableCellBasedView: class {
/// The generic type of the Cell.
associatedtype CellType
/**
Registers a nib in the view.
- parameter nib A UINib to register.
- parameter reuseIdentifier A String for the reuseIdentifier.
*/
func registerNib(nib: UINib, withIdentifier reuseIdentifier: String)
/**
Registers a class in the view.
- parameter aClass A AnyClass to register.
- parameter reuseIdentifier A String for the reuseIdentifier.
*/
func registerClass(aClass: AnyClass, withIdentifier reuseIdentifier: String)
/**
Dequeues a cell with an identifier at an index path.
- parameter id A String the reuse identifier
- parameter indexPath the NSIndexPath which is required.
- returns: an instance of the CellType.
*/
func dequeueCellWithIdentifier(id: String, atIndexPath indexPath: NSIndexPath) -> CellType
}
public protocol ReusableSupplementaryViewBasedView: class {
/// The generic type of the SupplementaryView.
associatedtype SupplementaryViewType
/**
Registers a nib in the view for a supplementary element kind, with a reuse identifier.
- parameter nib A UINib to register.
- parameter kind the SupplementaryElementKind
- parameter reuseIdentifier the String.
*/
func registerNib(nib: UINib, forSupplementaryViewKind kind: SupplementaryElementKind, withIdentifier reuseIdentifier: String)
/**
Registers a class in the view for a supplementary element kind, with a reuse identifier.
- parameter aClass A AnyClass to register.
- parameter kind the SupplementaryElementKind
- parameter reuseIdentifier the String.
*/
func registerClass(aClass: AnyClass, forSupplementaryViewKind kind: SupplementaryElementKind, withIdentifier reuseIdentifier: String)
/**
Dequeues a view for a supplementary element kind with an identifier at an index path.
- parameter kind the SupplementaryElementKind
- parameter id A String the reuse identifier
- parameter indexPath the NSIndexPath which is required.
- returns: an instance of the SupplementaryViewType.
*/
func dequeueSupplementaryViewWithKind(kind: SupplementaryElementKind, identifier id: String, atIndexPath indexPath: NSIndexPath) -> SupplementaryViewType?
}
/**
Base protocol which the container view must implement.
*/
public protocol CellBasedView: ReusableCellBasedView, ReusableSupplementaryViewBasedView {
func reloadData()
}
/**
A constraining protocol for the cell & supplementary view
index type. It must expose an indexPath.
*/
public protocol IndexPathIndexType {
var indexPath: NSIndexPath { get }
}
// MARK: - Factory Type
/**
Generic protocol for Factory types.
The purpose of the factory is to enable the registration and dequeuing
of cells, supplementary view and texts. This protocol is generic over
the item, cell, supplementary view, container view, cell index and
supplementary index.
The container view, e.g. UITableView, has constraints that it must
implement CellBasedView.
The CellIndexType and SupplementaryIndexType allow for the index
parameter of the configuration blocks to be generic.
*/
public protocol _FactoryType {
associatedtype ItemType
associatedtype CellType
associatedtype SupplementaryViewType
associatedtype ViewType: CellBasedView
associatedtype CellIndexType: IndexPathIndexType
associatedtype SupplementaryIndexType: IndexPathIndexType
/// Cell configuration closure typealias.
associatedtype CellConfiguration = (cell: CellType, item: ItemType, index: CellIndexType) -> Void
/// Supplmentary view configuration closure typealias.
associatedtype SupplementaryViewConfiguration = (supplementaryView: SupplementaryViewType, index: SupplementaryIndexType) -> Void
/// Supplmentary text configuration closure typealias.
associatedtype SupplementaryTextConfiguration = (index: SupplementaryIndexType) -> TextType?
/// The type of the text returned, could be a String, or NSAttributedString for instance.
associatedtype TextType
// Registration
/**
Registers the cell in the view, and stores the configuration block in the factory.
The key parameter is used to look up the configuration, as multiple configurations
can be stored for the same base cell.
- parameter descriptor: a ReusableViewDescriptor which descibes the cell with either nib or class.
- parameter view: the CellBasedView conforming view.
- parameter key: a String used for lookup
- parameter configuration: the cell configuration closure.
*/
mutating func registerCell(descriptor: ReusableViewDescriptor, inView view: ViewType, withKey key: String, configuration: CellConfiguration)
/**
Registers a supplementary view in the view, and stores the configuration block in the factory.
The key parameter is used to look up the configuration, as multiple configurations
can be stored for the same base cell.
- parameter descriptor: a ReusableViewDescriptor which descibes the cell with either nib or class.
- parameter kind: the SupplementaryElementKind kind.
- parameter view: the CellBasedView conforming view.
- parameter key: a String used for lookup
- parameter configuration: the supplementary view configuration closure.
*/
mutating func registerSupplementaryView(descriptor: ReusableViewDescriptor, kind: SupplementaryElementKind, inView: ViewType, withKey key: String, configuration: SupplementaryViewConfiguration)
/**
Registers the text configuration block.
The text configuration block receives the SupplementaryIndexType, e.g. an NSIndexPath.
- parameter kind: the SupplementaryElementKind kind.
- parameter configuration: the text configuration closure.
*/
mutating func registerTextWithKind(kind: SupplementaryElementKind, configuration: SupplementaryTextConfiguration)
// Vending
/**
Returns a configured cell for the item at the index.
- parameter item: the dataum ItemType.
- parameter view: the cell based view, ViewType
- parameter index: the index a CellIndexType.
*/
func cellForItem(item: ItemType, inView view: ViewType, atIndex index: CellIndexType) -> CellType
/**
Returns a configured supplementary view for the item at the index.
- parameter kind: the SupplementaryElementKind kind
- parameter view: the cell based view, ViewType
- parameter index: the index a CellIndexType.
*/
func supplementaryViewForKind(kind: SupplementaryElementKind, inView view: ViewType, atIndex index: SupplementaryIndexType) -> SupplementaryViewType?
/**
Returns a configured text for the supplementary element of kind at index.
- parameter view: the cell based view, ViewType
- parameter index: the index a CellIndexType.
*/
func supplementaryTextForKind(kind: SupplementaryElementKind, atIndex: SupplementaryIndexType) -> TextType?
}
/**
Concrete implementation of _FactoryType. Should be
subclassed to constrain the CellIndexType and
SupplementaryIndexType.
*/
public class Factory<
Item, Cell, SupplementaryView, View, CellIndex, SupplementaryIndex
where
View: CellBasedView,
CellIndex: IndexPathIndexType,
SupplementaryIndex: IndexPathIndexType>: _FactoryType {
public typealias TextType = String
public typealias ItemType = Item
public typealias CellType = Cell
public typealias SupplementaryViewType = SupplementaryView
public typealias ViewType = View
public typealias CellIndexType = CellIndex
public typealias SupplementaryIndexType = SupplementaryIndex
public typealias CellConfig = (cell: Cell, item: Item, index: CellIndexType) -> Void
public typealias SupplementaryViewConfig = (supplementaryView: SupplementaryView, index: SupplementaryIndexType) -> Void
public typealias SupplementaryTextConfig = (index: SupplementaryIndexType) -> String?
public typealias GetCellKey = (Item, CellIndexType) -> String
public typealias GetSupplementaryKey = (SupplementaryIndexType) -> String
typealias ReuseIdentifier = String
static var defaultCellKey: String {
return "Default Cell Key"
}
static var defaultSuppplementaryViewKey: String {
return "Default Suppplementary View Key"
}
let getCellKey: GetCellKey?
let getSupplementaryKey: GetSupplementaryKey?
var cells = [String: (reuseIdentifier: ReuseIdentifier, configure: CellConfig)]()
var views = [SupplementaryElementIndex: (reuseIdentifier: ReuseIdentifier, configure: SupplementaryViewConfig)]()
var texts = [SupplementaryElementKind: SupplementaryTextConfig]()
init(cell: GetCellKey? = .None, supplementary: GetSupplementaryKey? = .None) {
getCellKey = cell
getSupplementaryKey = supplementary
}
// Registration
public func registerCell(descriptor: ReusableViewDescriptor, inView view: View, configuration: CellConfig) {
registerCell(descriptor, inView: view, withKey: self.dynamicType.defaultCellKey, configuration: configuration)
}
public func registerCell(descriptor: ReusableViewDescriptor, inView view: View, withKey key: String, configuration: CellConfig) {
descriptor.registerInView(view)
cells[key] = (descriptor.identifier, configuration)
}
public func registerSupplementaryView(descriptor: ReusableViewDescriptor, kind: SupplementaryElementKind, inView view: View, configuration: SupplementaryViewConfig) {
registerSupplementaryView(descriptor, kind: kind, inView: view, withKey: self.dynamicType.defaultSuppplementaryViewKey, configuration: configuration)
}
public func registerSupplementaryView(descriptor: ReusableViewDescriptor, kind: SupplementaryElementKind, inView view: View, withKey key: String, configuration: SupplementaryViewConfig) {
descriptor.registerInView(view, kind: kind)
views[SupplementaryElementIndex(kind: kind, key: key)] = (descriptor.identifier, configuration)
}
public func registerTextWithKind(kind: SupplementaryElementKind, configuration: SupplementaryTextConfig) {
texts[kind] = configuration
}
// Vending
public func cellForItem(item: Item, inView view: View, atIndex index: CellIndex) -> Cell {
let key = getCellKey?(item, index) ?? self.dynamicType.defaultCellKey
if let info = cells[key] {
let cell = view.dequeueCellWithIdentifier(info.reuseIdentifier, atIndexPath: index.indexPath) as! Cell
info.configure(cell: cell, item: item, index: index)
return cell
}
fatalError("No cell factory registered with key: \(key). Currently registered keys: \(([String])(cells.keys))")
}
public func supplementaryViewForKind(kind: SupplementaryElementKind, inView view: View, atIndex index: SupplementaryIndex) -> SupplementaryView? {
let key = getSupplementaryKey?(index) ?? self.dynamicType.defaultSuppplementaryViewKey
if let info = views[SupplementaryElementIndex(kind: kind, key: key)] {
if let supplementaryView = view.dequeueSupplementaryViewWithKind(kind, identifier: info.reuseIdentifier, atIndexPath: index.indexPath) as? SupplementaryView {
info.configure(supplementaryView: supplementaryView, index: index)
return supplementaryView
}
}
return .None
}
public func supplementaryTextForKind(kind: SupplementaryElementKind, atIndex index: SupplementaryIndex) -> String? {
if let configure: SupplementaryTextConfig = texts[kind] {
return configure(index: index)
}
return .None
}
// Convenience
public func registerHeaderView(descriptor: ReusableViewDescriptor, inView view: View, configuration: SupplementaryViewConfig) {
registerSupplementaryView(descriptor, kind: .Header, inView: view, configuration: configuration)
}
public func registerHeaderView(descriptor: ReusableViewDescriptor, inView view: View, withKey key: String, configuration: SupplementaryViewConfig) {
registerSupplementaryView(descriptor, kind: .Header, inView: view, withKey: key, configuration: configuration)
}
public func registerFooterView(descriptor: ReusableViewDescriptor, inView view: View, configuration: SupplementaryViewConfig) {
registerSupplementaryView(descriptor, kind: .Footer, inView: view, configuration: configuration)
}
public func registerFooterView(descriptor: ReusableViewDescriptor, inView view: View, withKey key: String, configuration: SupplementaryViewConfig) {
registerSupplementaryView(descriptor, kind: .Footer, inView: view, withKey: key, configuration: configuration)
}
public func registerHeaderText(configuration: SupplementaryTextConfig) {
registerTextWithKind(.Header, configuration: configuration)
}
public func registerFooterText(configuration: SupplementaryTextConfig) {
registerTextWithKind(.Footer, configuration: configuration)
}
}
/**
Basic Factory with NSIndexPath as the CellIndexType and SupplementaryIndexType.
*/
public class BasicFactory<
Item, Cell, SupplementaryView, View
where
View: CellBasedView>: Factory<Item, Cell, SupplementaryView, View, NSIndexPath, NSIndexPath> {
public override init(cell: GetCellKey? = .None, supplementary: GetSupplementaryKey? = .None) {
super.init(cell: cell, supplementary: supplementary)
}
}
// MARK: - Helpers
extension SupplementaryElementKind {
init(_ kind: String) {
switch kind {
case UICollectionElementKindSectionHeader:
self = .Header
case UICollectionElementKindSectionFooter:
self = .Footer
default:
self = .Custom(kind)
}
}
}
extension SupplementaryElementKind: CustomStringConvertible {
public var description: String {
switch self {
case .Header: return UICollectionElementKindSectionHeader
case .Footer: return UICollectionElementKindSectionFooter
case .Custom(let custom): return custom
}
}
}
extension SupplementaryElementKind: Hashable {
public var hashValue: Int {
return description.hashValue
}
}
public func == (a: SupplementaryElementKind, b: SupplementaryElementKind) -> Bool {
return a.description == b.description
}
extension SupplementaryElementIndex: Hashable {
var hashValue: Int {
return "\(kind): \(key)".hashValue
}
}
func == (a: SupplementaryElementIndex, b: SupplementaryElementIndex) -> Bool {
return (a.key == b.key) && (a.kind == b.kind)
}
extension ReusableViewDescriptor {
var identifier: String {
switch self {
case let .DynamicWithIdentifier(identifier): return identifier
case let .ClassWithIdentifier(_, identifier): return identifier
case let .NibWithIdentifier(_, identifier): return identifier
}
}
func registerInView<View: ReusableCellBasedView>(view: View) {
switch self {
case .DynamicWithIdentifier(_):
break
case let .ClassWithIdentifier(aClass, identifier):
view.registerClass(aClass, withIdentifier: identifier)
case let .NibWithIdentifier(nib, identifier):
view.registerNib(nib, withIdentifier: identifier)
}
}
func registerInView<View: ReusableSupplementaryViewBasedView>(view: View, kind: SupplementaryElementKind) {
switch self {
case .DynamicWithIdentifier(_):
break
case let .ClassWithIdentifier(aClass, identifier):
view.registerClass(aClass, forSupplementaryViewKind: kind, withIdentifier: identifier)
case let .NibWithIdentifier(nib, identifier):
view.registerNib(nib, forSupplementaryViewKind: kind, withIdentifier: identifier)
}
}
}
extension NSIndexPath: IndexPathIndexType {
public var indexPath: NSIndexPath {
return self
}
}
extension UITableView: CellBasedView {
public func registerNib(nib: UINib, withIdentifier id: String) {
registerNib(nib, forCellReuseIdentifier: id)
}
public func registerClass(aClass: AnyClass, withIdentifier id: String) {
registerClass(aClass, forCellReuseIdentifier: id)
}
public func dequeueCellWithIdentifier(id: String, atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return dequeueReusableCellWithIdentifier(id, forIndexPath: indexPath)
}
public func registerNib(nib: UINib, forSupplementaryViewKind: SupplementaryElementKind, withIdentifier id: String) {
registerNib(nib, forHeaderFooterViewReuseIdentifier: id)
}
public func registerClass(aClass: AnyClass, forSupplementaryViewKind: SupplementaryElementKind, withIdentifier id: String) {
registerClass(aClass, forHeaderFooterViewReuseIdentifier: id)
}
public func dequeueSupplementaryViewWithKind(kind: SupplementaryElementKind, identifier: String, atIndexPath: NSIndexPath) -> UITableViewHeaderFooterView? {
return dequeueReusableHeaderFooterViewWithIdentifier(identifier)
}
}
extension UICollectionView: CellBasedView {
public func registerNib(nib: UINib, withIdentifier id: String) {
registerNib(nib, forCellWithReuseIdentifier: id)
}
public func registerClass(aClass: AnyClass, withIdentifier id: String) {
registerClass(aClass, forCellWithReuseIdentifier: id)
}
public func dequeueCellWithIdentifier(id: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return dequeueReusableCellWithReuseIdentifier(id, forIndexPath: indexPath)
}
public func registerNib(nib: UINib, forSupplementaryViewKind kind: SupplementaryElementKind, withIdentifier id: String) {
registerNib(nib, forSupplementaryViewOfKind: "\(kind)", withReuseIdentifier: id)
}
public func registerClass(aClass: AnyClass, forSupplementaryViewKind kind: SupplementaryElementKind, withIdentifier id: String) {
registerClass(aClass, forSupplementaryViewOfKind: "\(kind)", withReuseIdentifier: id)
}
public func dequeueSupplementaryViewWithKind(kind: SupplementaryElementKind, identifier: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView? {
return dequeueReusableSupplementaryViewOfKind("\(kind)", withReuseIdentifier: identifier, forIndexPath: indexPath)
}
}
| mit |
megavolt605/CNLUIKitTools | CNLUIKitTools/CNLCodeScanner.swift | 1 | 9122 | //
// CNLCodeScanner.swift
// CNLUIKitTools
//
// Created by Igor Smirnov on 12/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
import AVFoundation
import ImageIO
import CNLFoundationTools
public protocol CNLCodeScannerDelegate: class {
func codeScanner(_ codeScanner: CNLCodeScanner, didScanObject object: AVMetadataObject, screenshot: UIImage?)
func codeScanner(_ codeScanner: CNLCodeScanner, didTakePhoto image: UIImage?)
func codeScannerError(_ codeScanner: CNLCodeScanner)
}
public enum CNLCodeScannerMode {
case scanCode
case takePhoto
}
open class CNLCodeScanner: NSObject, AVCaptureMetadataOutputObjectsDelegate {
open weak var delegate: CNLCodeScannerDelegate?
var captureSession: AVCaptureSession!
var captureDevice: AVCaptureDevice!
var captureMetadataOutput: AVCaptureMetadataOutput!
var captureImageOutput: AVCaptureStillImageOutput!
var videoPreviewView: UIView!
var videoPreviewLayer: AVCaptureVideoPreviewLayer!
open private(set) var isReading = false
open var userData: Any?
open var mode: CNLCodeScannerMode = .scanCode
open var metadataTypes: [AVMetadataObject.ObjectType] = [
AVMetadataObject.ObjectType.qr,
AVMetadataObject.ObjectType.upce,
AVMetadataObject.ObjectType.code39,
AVMetadataObject.ObjectType.code39Mod43,
AVMetadataObject.ObjectType.ean13,
AVMetadataObject.ObjectType.ean8,
AVMetadataObject.ObjectType.code93,
AVMetadataObject.ObjectType.code128,
AVMetadataObject.ObjectType.pdf417,
AVMetadataObject.ObjectType.aztec
]
@discardableResult
open func startReading(_ inView: UIView, isFront: Bool) -> Bool {
let devices = AVCaptureDevice.devices(for: AVMediaType.video)
// most cases: we run in simulator
guard devices.count != 0 else {
delegate?.codeScannerError(self)
return false
}
captureDevice = nil
for device in devices {
if isFront {
if device.position == .front {
captureDevice = device
break
}
} else {
if device.position == .back {
captureDevice = device
break
}
}
}
if captureDevice == nil {
// most cases: we run in simulator
delegate?.codeScannerError(self)
return false
}
do {
try captureDevice.lockForConfiguration()
} catch _ as NSError {
}
captureDevice.videoZoomFactor = 1.0
// capability check
if captureDevice.isFocusModeSupported(.continuousAutoFocus) {
captureDevice.focusMode = .continuousAutoFocus
} else {
if captureDevice.isFocusModeSupported(.autoFocus) {
captureDevice.focusMode = .autoFocus
} else {
if captureDevice.isFocusModeSupported(.locked) {
captureDevice.focusMode = .locked
}
}
}
// capability check
if captureDevice.isExposureModeSupported(.continuousAutoExposure) {
captureDevice.exposureMode = .continuousAutoExposure
} else {
if captureDevice.isExposureModeSupported(.autoExpose) {
captureDevice.exposureMode = .autoExpose
} else {
if captureDevice.isExposureModeSupported(.locked) {
captureDevice.exposureMode = .locked
}
}
}
captureDevice?.unlockForConfiguration()
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession.sessionPreset = AVCaptureSession.Preset.high
captureSession.addInput(input)
captureImageOutput = AVCaptureStillImageOutput()
captureSession?.addOutput(captureImageOutput)
switch mode {
case .scanCode:
let dispatchQueue = DispatchQueue(label: "barCodeQueue", attributes: [])
captureMetadataOutput = AVCaptureMetadataOutput()
captureSession.addOutput(captureMetadataOutput)
captureMetadataOutput.metadataObjectTypes = metadataTypes.filter { captureMetadataOutput.availableMetadataObjectTypes.contains($0) }
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatchQueue)
case .takePhoto: break
}
captureImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer.frame = inView.layer.bounds
inView.layer.addSublayer(videoPreviewLayer)
videoPreviewView = inView
updateOrientation()
captureSession.startRunning()
return true
} catch _ as NSError {
return false
}
}
open func stopReading() {
captureSession?.stopRunning()
captureSession = nil
videoPreviewLayer?.removeFromSuperlayer()
videoPreviewLayer = nil
captureMetadataOutput = nil
captureImageOutput = nil
videoPreviewView = nil
isReading = false
}
// AVCaptureMetadataOutputObjectsDelegate delegate
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if !isReading {
isReading = true
guard
let metadataObj = metadataObjects.first as? AVMetadataMachineReadableCodeObject
else { return }
asyncMain {
let objectFrame = UIView()
objectFrame.backgroundColor = UIColor.clear
//self.highlightView.frame = self.videoPreviewLayer.transformedMetadataObjectForMetadataObject(metadataObj).bounds
//self.highlightView.hidden = false
self.captureImage { image in
self.delegate?.codeScanner(self, didScanObject: metadataObj, screenshot: image)
self.stopReading()
}
}
}
}
open func setFocusPoint(_ point: CGPoint) {
do {
try captureDevice.lockForConfiguration()
} catch _ as NSError {
}
if captureDevice.isFocusPointOfInterestSupported {
captureDevice.focusPointOfInterest = point
}
if captureDevice.isExposurePointOfInterestSupported {
captureDevice.exposurePointOfInterest = point
}
captureDevice.unlockForConfiguration()
}
func updateOrientation() {
guard
videoPreviewLayer != nil,
let connection = videoPreviewLayer.connection
else { return }
videoPreviewLayer.frame = videoPreviewView.bounds
switch UIApplication.shared.statusBarOrientation {
case .portrait: connection.videoOrientation = .portrait
case .landscapeLeft: connection.videoOrientation = .landscapeLeft
case .landscapeRight: connection.videoOrientation = .landscapeRight
case .portraitUpsideDown: connection.videoOrientation = .portraitUpsideDown
default: break //videoPreviewLayer.connection.videoOrientation = lastOrientation
}
}
open func captureImage(_ completion: @escaping (_ image: UIImage?) -> Void) {
guard let captureImageOutput = captureImageOutput else {
completion(nil)
return
}
var videoConnection: AVCaptureConnection? = nil
for connection in captureImageOutput.connections {
if (connection.inputPorts.contains { $0.mediaType == AVMediaType.video }) {
videoConnection = connection
break
}
if videoConnection != nil {
break
}
}
captureImageOutput.captureStillImageAsynchronously(from: videoConnection!) { (imageSampleBuffer: CMSampleBuffer?, _: Error?) -> Void in
//let exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, nil)
guard
let sampleBuffer = imageSampleBuffer,
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer),
let image = UIImage(data: imageData)
else {
completion(nil)
return
}
completion(image.adoptToDevice(CGSize(width: image.size.width / 2.0, height: image.size.height / 2.0), scale: 1.0))
}
}
}
| mit |
sjtu-meow/iOS | Pods/PKHUD/PKHUD/PKHUDAnimation.swift | 1 | 1172 | //
// PKHUDAnimation.swift
// PKHUD
//
// Created by Piergiuseppe Longo on 06/01/16.
// Copyright © 2016 Piergiuseppe Longo, NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import Foundation
import QuartzCore
public final class PKHUDAnimation {
public static let discreteRotation: CAAnimation = {
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.values = [NSNumber]()
animation.keyTimes = [NSNumber]()
for i in 0..<12 {
animation.values!.append(NSNumber(value: Double(i) * .pi / 6.0))
animation.keyTimes!.append(NSNumber(value: Double(i) / 12.0))
}
animation.duration = 1.2
animation.calculationMode = "discrete"
animation.repeatCount = Float(INT_MAX)
return animation
}()
static let continuousRotation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = 0
animation.toValue = 2.0 * .pi
animation.duration = 1.2
animation.repeatCount = Float(INT_MAX)
return animation
}()
}
| apache-2.0 |
wer0858/mySelect | mySelect/mySelect/classes/Tools/Extension/UIColor-Extension.swift | 1 | 323 |
//
// UIColor-Extension.swift
// mySelect
//
// Created by huangsw on 17/4/12.
// Copyright © 2017年 首誉光控科技. All rights reserved.
//
import UIKit
extension UIColor{
convenience init(r:CGFloat,g:CGFloat,b:CGFloat) {
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}
}
| mit |
rhcad/SwiftGraphics | SwiftGraphics/GeometryProtocols.swift | 4 | 223 | //
// Geometry.swift
// SwiftGraphics
//
// Created by Jonathan Wight on 1/24/15.
// Copyright (c) 2015 schwa.io. All rights reserved.
//
import CoreGraphics
public protocol Geometry {
var frame:CGRect { get }
}
| bsd-2-clause |
jianghuihon/DYZB | DYZB/Classes/Home/View/RecommendGameView.swift | 1 | 1743 | //
// RecommendGameView.swift
// DYZB
//
// Created by Enjoy on 2017/3/27.
// Copyright © 2017年 SZCE. All rights reserved.
//
import UIKit
private let collectionGameViewCellID = "CollectionGameViewCell"
private let GameMagin : CGFloat = 10
class RecommendGameView: UIView {
@IBOutlet weak var collectionGameView: UICollectionView!
var anthorGroups : [GameBaseModel]? {
didSet{
collectionGameView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing()
collectionGameView.register(UINib.init(nibName: collectionGameViewCellID, bundle: nil), forCellWithReuseIdentifier: collectionGameViewCellID)
collectionGameView.contentInset = UIEdgeInsets(top: GameMagin, left: 10, bottom: 0, right: GameMagin);
}
}
///加载游戏选择
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)!.first as! RecommendGameView
}
}
///MARK - UICollectionViewDataSource
extension RecommendGameView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return anthorGroups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionGameViewCellID, for: indexPath) as! CollectionGameViewCell
cell.baseModel = anthorGroups?[indexPath.item]
return cell
}
}
| mit |
zorac/PastePad | PastePad/NSFont+Name.swift | 1 | 1229 | import AppKit
/**
* NSFont extension for converting to/from names.
*
* - Author: Mark Rigby-Jones
* - Copyright: © 2019 Mark Rigby-Jones. All rights reserved.
*/
extension NSFont {
/// The maximum point size to allow.
static let maxPoints = 288.0
/// The name of this font.
var name: String {
return "\(self.pointSize)pt \(self.displayName!)"
}
/**
* Create a font for a given name.
*
* - Parameter name: A font name.
* - Parameter textMode: A text mode.
* - Returns: The named font, or the default font for the given text mode
*/
static func fromName(_ name: String, textMode: TextMode) -> NSFont {
let scanner = Scanner(string:name)
var points: Double = 0.0
var face: NSString?
scanner.scanDouble(&points)
scanner.scanString("pt", into: nil);
scanner.scanUpToCharacters(from: .newlines, into: &face)
if points > maxPoints {
points = maxPoints
}
if let font = NSFont(name: face! as String, size: CGFloat(points)) {
return font
} else {
return textMode.userFontOfSize(CGFloat(points))
}
}
}
| mit |
vector-im/vector-ios | Riot/Modules/Room/TimelineCells/RoomCreationIntro/RoomCreationIntroViewData.swift | 1 | 873 | //
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
enum DiscussionType {
case directMessage
case multipleDirectMessage
case room(topic: String?)
}
struct RoomCreationIntroViewData {
let dicussionType: DiscussionType
let roomDisplayName: String
let avatarViewData: RoomAvatarViewData
}
| apache-2.0 |
barkingiguana/BIVerify | BIVerify/BIVerify.swift | 1 | 368 | //
// Verify.swift
// Verify
//
// Created by Craig Webster on 14/10/2015.
// Copyright © 2015 Barking Iguana. All rights reserved.
//
import Foundation
public class BIVerify {
public static func expressIntent(verb:String, path:String, parameters:[String:String]) -> BIIntent {
return BIIntent(verb: verb, path: path, parameters: parameters)
}
} | mit |
uasys/swift | test/DebugInfo/prologue.swift | 18 | 531 | // RUN: %target-swift-frontend -primary-file %s -S -g -o - | %FileCheck %s
// REQUIRES: CPU=x86_64
func markUsed<T>(_ t: T) {}
// CHECK: .file [[F:[0-9]+]] "{{.*}}prologue.swift"
func bar<T, U>(_ x: T, y: U) { markUsed("bar") }
// CHECK: _T08prologue3baryx_q_1ytr0_lF:
// CHECK: .loc [[F]] 0 0 prologue_end
// Make sure there is no allocation happening between the end of
// prologue and the beginning of the function body.
// CHECK-NOT: callq *
// CHECK: .loc [[F]] [[@LINE-6]] {{.}}
// CHECK: callq {{.*}}builtinStringLiteral
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.