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 |
---|---|---|---|---|---|
Baglan/MCLocalization2 | Classes/MCLocalizationProviders.swift | 1 | 7160 | //
// MCLocalizationProviders.swift
// MCLocalization2
//
// Created by Baglan on 12/12/15.
// Copyright © 2015 Mobile Creators. All rights reserved.
//
import Foundation
extension MCLocalization {
/// Placeholder provider designed to be put as the last one in queue
/// to "catch" unlocalized strings and display a placeholder for them
/// that would look something like this:
///
/// [en: some_unlocalized_key]
class PlaceholderProvider: MCLocalizationProvider {
var languages: [String] { get { return [] } }
func string(for key: String, language: String) -> String? {
return "[\(language): \(key)]"
}
}
/// Provider for the default main bundle localization.
///
/// *Does not support switching languages*
class MainBundleProvider: MCLocalizationProvider {
fileprivate var table: String?
required init(table: String?) {
self.table = table
}
let uniqueString = UUID().uuidString
var languages: [String] { get { return Bundle.main.localizations } }
func string(for key: String, language: String) -> String? {
// The 'defaultValue' "trickery" is here because 'localizedStringForKey'
// will always return a string even if there is no localization available
// and we want to capture this condition
let defaultValue = "\(uniqueString)-\(key)"
let localizedString = Bundle.main.localizedString(forKey: key, value: defaultValue, table: table)
if localizedString == defaultValue {
return nil
}
return localizedString
}
}
/// Provider for single- and multiple-language JSON sources
class JSONProvider: MCLocalizationProvider {
fileprivate var strings = [String:[String:String]]()
fileprivate let synchronousURL: URL?
fileprivate let asynchronousURL: URL?
fileprivate let language: String?
/// Main init
///
/// - parameter synchronousURL URL to be fetched synchronously (perhaps a local file)
/// - parameter asynchronousURL URL to be fetched asynchronously (perhaps a remote resource)
/// - parameter language for single language JSON resources
required init(synchronousURL: URL?, asynchronousURL: URL?, language: String?) {
self.synchronousURL = synchronousURL
self.asynchronousURL = asynchronousURL
self.language = language
guard synchronousURL != nil || asynchronousURL != nil else { return }
if let synchronousURL = synchronousURL, let data = try? Data(contentsOf: synchronousURL), let JSONObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) {
adoptJSONObject(JSONObject as AnyObject)
}
}
/// Convenience init for a file in the main bundle
///
/// - parameter language for a single language JSON resource
/// - parameter fileName file name for a file in the main bundle
convenience init(language: String?, fileName: String) {
self.init(synchronousURL: Bundle.main.url(forResource: fileName, withExtension: nil), asynchronousURL: nil, language: language)
}
/// Convenience init for a multiple language file in the main bundle
///
/// - parameter fileName file name for a file in the main bundle
convenience init(fileName: String) {
self.init(language: nil, fileName: fileName)
}
/// Convenience init for a remote URL resource with an optional local cache
///
/// - parameter language for a single language JSON resource
/// - parameter remoteURL URL for a remote resource
/// - parameter localName file name for the local cache (will be stored in the 'Application Support' directory)
convenience init(language: String?, remoteURL: URL, localName: String?) {
let directoryURL = try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let localURL: URL?
if let directoryURL = directoryURL, let localName = localName {
localURL = directoryURL.appendingPathComponent(localName)
} else {
localURL = nil
}
self.init(synchronousURL: localURL, asynchronousURL: remoteURL, language: language)
}
/// Convenience init for a multiple language remote URL resource with an optional local cache
///
/// - parameter remoteURL URL for a remote resource
/// - parameter localName file name for the local cache (will be stored in the 'Application Support' directory)
convenience init(remoteURL: URL, localName: String?) {
self.init(language: nil, remoteURL: remoteURL, localName: localName)
}
@discardableResult func adoptJSONObject(_ JSONObject: AnyObject) -> Bool {
if let multipleLanguages = JSONObject as? [String:[String:String]] {
self.strings = multipleLanguages
return true
} else if let singleLanguage = JSONObject as? [String:String], let language = self.language {
self.strings[language] = singleLanguage
return true
}
return false
}
/// Request asynchronousURL and, optionally, store it in a local cache
func fetchAsynchronously() {
if let asynchronousURL = asynchronousURL {
OperationQueue().addOperation({ () -> Void in
if let data = try? Data(contentsOf: asynchronousURL), let JSONObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) {
if self.adoptJSONObject(JSONObject as AnyObject) {
OperationQueue.main.addOperation({ () -> Void in
MCLocalization.sharedInstance.providerUpdated(self)
})
// If synchronous URL (e.g. cache) is configured, attempt to save data to it
if let synchronousURL = self.synchronousURL {
try? data.write(to: synchronousURL, options: [.atomic])
}
}
}
})
}
}
var languages: [String] {
get {
return strings.map { (key: String, _) -> String in
return key
}
}
}
func string(for key: String, language: String) -> String? {
if let strings = strings[language] {
return strings[key]
}
return nil
}
}
}
| mit |
smahajan28/SwiftInterviewQuestion | LargestNumber/LargestNumber.swift | 1 | 940 | //
// LargestNumber.swift
//
//
// Created by Sahil Mahajan on 31/03/17.
//
//
import Foundation
/// Question : Arrange given numbers to form the biggest number
///
/// Given a list of non negative integers, arrange them in such a manner that they form the largest number possible.
/// The result is going to be very large, hence return the result in the form of a string.
///
/// For example: Given numbers are [64, 646, 648, 70],
/// Output : 7064864664
///
/// Given numbers are [1, 34, 3, 98, 9, 76, 45, 4]
/// Output : 998764543431
///
///
func printLargestNumber(input : [Int]) -> String {
let numberInStringFormat = input.map {
return "\($0)"
}
let result = numberInStringFormat.sorted { (str1, str2) -> Bool in
return str1.appending(str2) > str2.appending(str1)
}
return result.joined()
}
| apache-2.0 |
baquiax/SimpleTwitterClient | SimpleTwitterClient/SimpleTwitterClient/Cells/TwitterPostCell.swift | 1 | 603 | //
// TwitterPostCell.swift
// SimpleTwitterClient
//
// Created by Alexander Baquiax on 4/8/16.
// Copyright © 2016 Alexander Baquiax. All rights reserved.
//
import Foundation
import UIKit
public class TwitterPostCell : UITableViewCell {
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var tweet: UITextView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var username: UILabel!
weak var dataTask: NSURLSessionDataTask?
public override func awakeFromNib() {
super.awakeFromNib()
profileImage.image = UIImage(named: "hashtag")
}
} | mit |
Logicalshift/SwiftRebound | SwiftRebound/Binding/Binding.swift | 1 | 3478 | //
// Binding.swift
// SwiftRebound
//
// Created by Andrew Hunter on 10/07/2016.
//
//
import Foundation
///
/// The binding class provides methods for creating and managing bound objects
///
public class Binding {
fileprivate init() {
// This class has only static methods: you can't create an instance
}
///
/// Creates a simple binding to a value of a particular type
///
public static func create<TBoundType>(_ value: TBoundType) -> MutableBound<TBoundType> {
return BoundValue(value: value);
}
///
/// Creates a simple binding to a value of a particular type
///
public static func create<TBoundType : Equatable>(_ value: TBoundType) -> MutableBound<TBoundType> {
return BoundEquatable(value: value);
}
///
/// Creates a simple binding to a value of a particular type
///
public static func create<TBoundType : AnyObject>(_ value: TBoundType) -> MutableBound<TBoundType> {
return BoundReference(value: value);
}
///
/// Creates a binding for an array value of a particular type
///
public static func create<TBoundType>(_ value: [TBoundType]) -> ArrayBound<TBoundType> {
return ArrayBound(value: value);
}
///
/// Creates a binding that can be used as an attachment point for other bindings
///
public static func attachment<TBoundType>(_ defaultValue: TBoundType) -> AttachmentPoint<TBoundType> {
let defaultBinding = create(defaultValue);
return Binding.attachment(defaultBinding);
}
///
/// Creates a binding that can be used as an attachment point for other bindings
///
/// Attachments are bindings that track the value of a different binding
///
public static func attachment<TBoundType>(_ initialAttachment: Bound<TBoundType>) -> AttachmentPoint<TBoundType> {
return AttachmentPoint(defaultAttachment: initialAttachment);
}
///
/// Creates a binding that can be used as an attachment point for other mutable bindings
///
public static func attachment<TBoundType>(mutable: TBoundType) -> MutableAttachmentPoint<TBoundType> {
let defaultBinding = create(mutable);
return Binding.attachment(mutable: defaultBinding);
}
///
/// Creates a binding that can be used as an attachment point for other mutable bindings
///
public static func attachment<TBoundType>(mutable: MutableBound<TBoundType>) -> MutableAttachmentPoint<TBoundType> {
return MutableAttachmentPoint(defaultAttachment: mutable);
}
///
/// Creates a computed binding
///
/// Computed bindings can access other bindings and will be automatically invalidated when those
/// bindings change.
///
public static func computed<TBoundType>(_ compute: @escaping () -> TBoundType) -> Bound<TBoundType> {
return BoundComputable(compute: compute);
}
///
/// Creates a triggered action
///
/// This is something like a drawing function where it can be triggered to update by calling `setNeedsDisplay()`.
///
public static func trigger(_ action: @escaping () -> (), causeUpdate: @escaping () -> ()) -> (() -> (), Lifetime) {
let trigger = Trigger(action: action);
let lifetime = trigger.whenChanged(causeUpdate).liveAsLongAs(trigger);
return (trigger.performAction, lifetime);
}
};
| apache-2.0 |
silt-lang/silt | Sources/Seismography/PrimOp.swift | 1 | 18356 | /// PrimOp.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Foundation
import Moho
/// A primitive operation that has no CPS definition, yet affects the semantics
/// of a continuation.
/// These are scheduled after GraphIR generation and include operations like
/// application of functions, copying and destroying values, conditional
/// branching, and pattern matching primitives.
public class PrimOp: Value {
/// An enum representing the kind of primitive operation this PrimOp exposes.
public enum Code: String {
/// A no-op operation.
case noop
/// Stack allocation.
case alloca
/// Stack deallocation.
case dealloca
/// An application of a function-type value.
case apply
/// An explicit copy operation of a value.
case copyValue = "copy_value"
/// A explicit destroy operation of a value.
case destroyValue = "destroy_value"
/// When the type of the source value is loadable, loads the source
/// value and stores a copy of it to memory at the given address.
///
/// When the type of the source value is address-only, copies the address
/// from the source value to the address at the destination value.
///
/// Returns the destination's memory.
case copyAddress = "copy_address"
/// Destroys the value pointed to by the given address but does not
/// deallocate the memory at that address. The appropriate memory
/// deallocation instruction should be scheduled instead.
case destroyAddress = "destroy_address"
/// An operation that selects a matching pattern and dispatches to another
/// continuation.
case switchConstr = "switch_constr"
/// An operation that represents a reference to a continuation.
case functionRef = "function_ref"
/// A data constructor call with all parameters provided at +1.
case dataInit = "data_init"
/// Extracts the payload data from a data constructor.
case dataExtract = "data_extract"
/// Heap-allocate a box large enough to hold a given type.
case allocBox = "alloc_box"
/// Deallocate a heap-allocated box.
case deallocBox = "dealloc_box"
/// Retrieve the address of the value inside a box.
case projectBox = "project_box"
/// Load the value stored at an address.
case load = "load"
/// Store a given value to memory allocated by a given box and returns the
/// newly-updated box value.
case store = "store"
/// Creates a tuple value from zero or more multiple field values.
case tuple
/// Projects the address of a tuple element.
case tupleElementAddress = "tuple_element_address"
/// Converts a "thin" function value pointer to a "thick" function by
/// appending a closure context.
case thicken
/// Express a data dependency of a value on multiple other the evaluation of
/// other values.
case forceEffects = "force_effects"
/// An instruction that is considered 'unreachable' that will trap at
/// runtime.
case unreachable
}
/// All the operands of this operation.
public private(set) var operands: [Operand] = []
/// Which specific operation this PrimOp represents.
public let opcode: Code
/// The 'result' of this operation, or 'nil', if this operation is only for
/// side effects.
public var result: Value? {
return nil
}
/// Initializes a PrimOp with the provided OpCode and no operands.
///
/// - Parameter opcode: The opcode this PrimOp represents.
init(opcode: Code, type: GIRType, category: Value.Category) {
self.opcode = opcode
super.init(type: type, category: category)
}
/// Adds the provided operands to this PrimOp's operand list.
///
/// - Parameter ops: The operands to append to the end of the current list of
/// operands.
fileprivate func addOperands(_ ops: [Operand]) {
self.operands.append(contentsOf: ops)
}
}
public class TerminalOp: PrimOp {
public var parent: Continuation
public var successors: [Successor] {
return []
}
init(opcode: Code, parent: Continuation) {
self.parent = parent
super.init(opcode: opcode, type: BottomType.shared, category: .object)
// Tie the knot
self.parent.terminalOp = self
}
func overrideParent(_ parent: Continuation) {
self.parent = parent
}
}
/// A primitive operation that contains no operands and has no effect.
public final class NoOp: PrimOp {
public init() {
super.init(opcode: .noop, type: BottomType.shared, category: .object)
}
}
/// A primitive operation that transfers control out of the current continuation
/// to the provided Graph IR value. The value _must_ represent a function.
public final class ApplyOp: TerminalOp {
/// Creates a new ApplyOp to apply the given arguments to the given value.
/// - parameter fnVal: The value to which arguments are being applied. This
/// must be a value of function type.
/// - parameter args: The values to apply to the callee. These must match the
/// arity of the provided function value.
public init(_ parent: Continuation, _ fnVal: Value, _ args: [Value]) {
super.init(opcode: .apply, parent: parent)
if let succ = fnVal as? FunctionRefOp {
self.successors_.append(Successor(parent, self, succ.function))
}
self.addOperands(([fnVal] + args).map { arg in
return Operand(owner: self, value: arg)
})
}
private var successors_: [Successor] = []
public override var successors: [Successor] {
return successors_
}
/// The value being applied to.
public var callee: Value {
return self.operands[0].value
}
/// The arguments being applied to the callee.
public var arguments: ArraySlice<Operand> {
return self.operands.dropFirst()
}
}
public final class AllocaOp: PrimOp {
public init(_ type: GIRType) {
super.init(opcode: .alloca, type: type, category: .address)
self.addOperands([Operand(owner: self, value: type)])
}
public override var result: Value? {
return self
}
public var addressType: GIRType {
return self.operands[0].value
}
}
public final class DeallocaOp: PrimOp {
public init(_ value: GIRType) {
super.init(opcode: .dealloca, type: BottomType.shared, category: .object)
self.addOperands([Operand(owner: self, value: value)])
}
public var addressValue: Value {
return self.operands[0].value
}
}
public final class CopyValueOp: PrimOp {
public init(_ value: Value) {
super.init(opcode: .copyValue,
type: value.type, category: value.type.category)
self.addOperands([Operand(owner: self, value: value)])
}
public override var result: Value? {
return self
}
public var value: Operand {
return self.operands[0]
}
}
public final class DestroyValueOp: PrimOp {
public init(_ value: Value) {
super.init(opcode: .destroyValue,
type: BottomType.shared, category: .object)
self.addOperands([Operand(owner: self, value: value)])
}
public var value: Operand {
return self.operands[0]
}
}
public final class CopyAddressOp: PrimOp {
public init(_ value: Value, to address: Value) {
super.init(opcode: .copyAddress,
type: address.type, category: value.type.category)
self.addOperands([Operand(owner: self, value: value)])
self.addOperands([Operand(owner: self, value: address)])
}
public override var result: Value? {
return self
}
public var value: Value {
return self.operands[0].value
}
public var address: Value {
return self.operands[1].value
}
}
public final class DestroyAddressOp: PrimOp {
public init(_ value: Value) {
super.init(opcode: .destroyAddress,
type: BottomType.shared, category: .object)
self.addOperands([Operand(owner: self, value: value)])
}
public var value: Value {
return self.operands[0].value
}
}
public final class FunctionRefOp: PrimOp {
public let function: Continuation
public init(continuation: Continuation) {
self.function = continuation
super.init(opcode: .functionRef, type: continuation.type, category: .object)
self.addOperands([Operand(owner: self, value: continuation)])
}
public override var result: Value? {
return self
}
public override var type: Value {
return self.function.type
}
}
public final class SwitchConstrOp: TerminalOp {
/// Initializes a SwitchConstrOp matching the constructor of the provided
/// value with the set of pattern/apply pairs. This will dispatch to a given
/// ApplyOp with the provided value if and only if the value was constructed
/// with the associated constructor.
///
/// - Parameters:
/// - value: The value you're pattern matching.
/// - patterns: A list of pattern/apply pairs.
public init(
_ parent: Continuation,
matching value: Value,
patterns: [(pattern: String, destination: FunctionRefOp)],
default: FunctionRefOp?
) {
self.patterns = patterns
self.`default` = `default`
super.init(opcode: .switchConstr, parent: parent)
self.addOperands([Operand(owner: self, value: value)])
var ops = [Operand]()
for (_, dest) in patterns {
ops.append(Operand(owner: self, value: dest))
successors_.append(Successor(parent, self, dest.function))
}
if let defaultDest = `default` {
ops.append(Operand(owner: self, value: defaultDest))
successors_.append(Successor(parent, self, defaultDest.function))
}
self.addOperands(ops)
}
private var successors_: [Successor] = []
public override var successors: [Successor] {
return successors_
}
public var matchedValue: Value {
return operands[0].value
}
public let patterns: [(pattern: String, destination: FunctionRefOp)]
public let `default`: FunctionRefOp?
}
public final class DataInitOp: PrimOp {
public let constructor: String
public let dataType: Value
public init(constructor: String, type: Value, argument: Value?) {
self.constructor = constructor
self.dataType = type
super.init(opcode: .dataInit, type: type, category: .object)
if let argVal = argument {
self.addOperands([Operand(owner: self, value: argVal)])
}
}
public var argumentTuple: Value? {
guard !self.operands.isEmpty else {
return nil
}
return operands[0].value
}
public override var result: Value? {
return self
}
}
public final class DataExtractOp: PrimOp {
public let constructor: String
public let dataValue: Value
public init(constructor: String, value: Value, payloadType: Value) {
self.constructor = constructor
self.dataValue = value
super.init(opcode: .dataExtract, type: payloadType,
category: payloadType.category)
self.addOperands([
Operand(owner: self, value: value),
])
}
public override var result: Value? {
return self
}
}
public final class TupleOp: PrimOp {
init(arguments: [Value]) {
let ty = TupleType(elements: arguments.map({$0.type}), category: .object)
super.init(opcode: .tuple, type: ty, category: .object)
self.addOperands(arguments.map { Operand(owner: self, value: $0) })
}
public override var result: Value? {
return self
}
}
public final class TupleElementAddressOp: PrimOp {
public let index: Int
init(tuple: Value, index: Int) {
guard let tupleTy = tuple.type as? TupleType else {
fatalError()
}
self.index = index
super.init(opcode: .tupleElementAddress,
type: tupleTy.elements[index], category: .address)
self.addOperands([ Operand(owner: self, value: tuple) ])
}
public var tuple: Value {
return self.operands[0].value
}
public override var result: Value? {
return self
}
}
public final class AllocBoxOp: PrimOp {
public init(_ type: GIRType) {
super.init(opcode: .allocBox, type: BoxType(type), category: .object)
self.addOperands([Operand(owner: self, value: type)])
}
public override var result: Value? {
return self
}
public var boxedType: GIRType {
return self.operands[0].value
}
}
public final class ProjectBoxOp: PrimOp {
public init(_ box: Value, type: GIRType) {
super.init(opcode: .projectBox, type: type, category: .address)
self.addOperands([ Operand(owner: self, value: box) ])
}
public override var result: Value? {
return self
}
public var boxValue: Value {
return operands[0].value
}
}
public final class LoadOp: PrimOp {
public enum Ownership {
case take
case copy
}
public let ownership: Ownership
public init(_ value: Value, _ ownership: Ownership) {
self.ownership = ownership
super.init(opcode: .load, type: value.type, category: .object)
self.addOperands([ Operand(owner: self, value: value) ])
}
public override var result: Value? {
return self
}
public var addressee: Value {
return operands[0].value
}
}
public final class StoreOp: PrimOp {
public init(_ value: Value, to address: Value) {
super.init(opcode: .store, type: value.type, category: .address)
self.addOperands([
Operand(owner: self, value: value),
Operand(owner: self, value: address),
])
}
public override var result: Value? {
return self
}
public var value: Value {
return operands[0].value
}
public var address: Value {
return operands[1].value
}
}
public final class DeallocBoxOp: PrimOp {
public init(_ box: Value) {
super.init(opcode: .deallocBox, type: BottomType.shared, category: .object)
self.addOperands([ Operand(owner: self, value: box) ])
}
public var box: Value {
return operands[0].value
}
}
public final class ThickenOp: PrimOp {
public init(_ funcRef: FunctionRefOp) {
super.init(opcode: .thicken, type: funcRef.type, category: .object)
self.addOperands([ Operand(owner: self, value: funcRef) ])
}
public override var result: Value? {
return self
}
public var function: Value {
return operands[0].value
}
}
public final class ForceEffectsOp: PrimOp {
public init(_ retVal: Value, _ effects: [Value]) {
super.init(opcode: .forceEffects,
type: retVal.type, category: retVal.category)
self.addOperands([ Operand(owner: self, value: retVal) ])
self.addOperands(effects.map { Operand(owner: self, value: $0) })
}
public var subject: Value {
return operands[0].value
}
public override var result: Value? {
return self
}
}
public final class UnreachableOp: TerminalOp {
public init(parent: Continuation) {
super.init(opcode: .unreachable, parent: parent)
}
}
public protocol PrimOpVisitor {
associatedtype Ret
func visitAllocaOp(_ op: AllocaOp) -> Ret
func visitApplyOp(_ op: ApplyOp) -> Ret
func visitDeallocaOp(_ op: DeallocaOp) -> Ret
func visitCopyValueOp(_ op: CopyValueOp) -> Ret
func visitDestroyValueOp(_ op: DestroyValueOp) -> Ret
func visitCopyAddressOp(_ op: CopyAddressOp) -> Ret
func visitDestroyAddressOp(_ op: DestroyAddressOp) -> Ret
func visitFunctionRefOp(_ op: FunctionRefOp) -> Ret
func visitSwitchConstrOp(_ op: SwitchConstrOp) -> Ret
func visitDataInitOp(_ op: DataInitOp) -> Ret
func visitDataExtractOp(_ op: DataExtractOp) -> Ret
func visitTupleOp(_ op: TupleOp) -> Ret
func visitTupleElementAddress(_ op: TupleElementAddressOp) -> Ret
func visitLoadOp(_ op: LoadOp) -> Ret
func visitStoreOp(_ op: StoreOp) -> Ret
func visitAllocBoxOp(_ op: AllocBoxOp) -> Ret
func visitProjectBoxOp(_ op: ProjectBoxOp) -> Ret
func visitDeallocBoxOp(_ op: DeallocBoxOp) -> Ret
func visitThickenOp(_ op: ThickenOp) -> Ret
func visitUnreachableOp(_ op: UnreachableOp) -> Ret
func visitForceEffectsOp(_ op: ForceEffectsOp) -> Ret
}
extension PrimOpVisitor {
public func visitPrimOp(_ code: PrimOp) -> Ret {
switch code.opcode {
case .noop:
fatalError()
// swiftlint:disable force_cast
case .alloca: return self.visitAllocaOp(code as! AllocaOp)
// swiftlint:disable force_cast
case .apply: return self.visitApplyOp(code as! ApplyOp)
// swiftlint:disable force_cast
case .dealloca: return self.visitDeallocaOp(code as! DeallocaOp)
// swiftlint:disable force_cast
case .copyValue: return self.visitCopyValueOp(code as! CopyValueOp)
// swiftlint:disable force_cast
case .destroyValue: return self.visitDestroyValueOp(code as! DestroyValueOp)
// swiftlint:disable force_cast
case .copyAddress: return self.visitCopyAddressOp(code as! CopyAddressOp)
// swiftlint:disable force_cast
case .destroyAddress:
return self.visitDestroyAddressOp(code as! DestroyAddressOp)
// swiftlint:disable force_cast
case .functionRef: return self.visitFunctionRefOp(code as! FunctionRefOp)
// swiftlint:disable force_cast
case .switchConstr: return self.visitSwitchConstrOp(code as! SwitchConstrOp)
// swiftlint:disable force_cast
case .dataInit: return self.visitDataInitOp(code as! DataInitOp)
// swiftlint:disable force_cast
case .dataExtract: return self.visitDataExtractOp(code as! DataExtractOp)
// swiftlint:disable force_cast
case .tuple: return self.visitTupleOp(code as! TupleOp)
// swiftlint:disable force_cast line_length
case .tupleElementAddress: return self.visitTupleElementAddress(code as! TupleElementAddressOp)
// swiftlint:disable force_cast
case .unreachable: return self.visitUnreachableOp(code as! UnreachableOp)
// swiftlint:disable force_cast
case .load: return self.visitLoadOp(code as! LoadOp)
// swiftlint:disable force_cast
case .store: return self.visitStoreOp(code as! StoreOp)
// swiftlint:disable force_cast
case .allocBox: return self.visitAllocBoxOp(code as! AllocBoxOp)
// swiftlint:disable force_cast
case .projectBox: return self.visitProjectBoxOp(code as! ProjectBoxOp)
// swiftlint:disable force_cast
case .deallocBox: return self.visitDeallocBoxOp(code as! DeallocBoxOp)
// swiftlint:disable force_cast
case .thicken: return self.visitThickenOp(code as! ThickenOp)
// swiftlint:disable force_cast
case .forceEffects: return self.visitForceEffectsOp(code as! ForceEffectsOp)
}
}
}
| mit |
fqhuy/minimind | minimindTests/optimisationTests.swift | 1 | 4957 | //
// optimisationTests.swift
// minimind
//
// Created by Phan Quoc Huy on 6/21/17.
// Copyright © 2017 Phan Quoc Huy. All rights reserved.
//
import XCTest
@testable import minimind
class Rosenbrock: ObjectiveFunction {
public typealias ScalarT = Float
public typealias MatrixT = Matrix<ScalarT>
public var dims: Int = 2
func compute(_ x: Matrix<Float>) -> Float {
return 100.0 * powf(x[0, 1] - powf(x[0, 0], 2), 2) + powf(1.0 - x[0, 1], 2)
}
func gradient(_ x: Matrix<Float>) -> Matrix<Float> {
let gX1 = -400.0 * x[0, 0] * (x[0, 1] - powf(x[0, 0], 2)) - 2.0 * (1.0 - x[0, 0])
let gX2 = 200.0 * (x[0, 1] - powf(x[0, 0], 2))
return Matrix<Float>([[gX1, gX2]])
}
func hessian(_ x: Matrix<Float>) -> Matrix<Float> {
let h11 = 1200.0 * powf(x[0, 0], 2) - 400.0 * x[0, 1] + 2.0
let h12 = -400.0 * x[0, 0]
return Matrix<Float>([[ h11, h12], [-400.0 * x[0, 0], 200.0 ] ])
}
}
class Quad: ObjectiveFunction {
typealias ScalarT = Float
typealias MatrixT = Matrix<ScalarT>
public var a: ScalarT
public var b: ScalarT
public var c: ScalarT
public var dims: Int = 1
public init(_ a: ScalarT, _ b: ScalarT, _ c: ScalarT) {
self.a = a
self.b = b
self.c = c
}
public func compute(_ x: MatrixT) -> ScalarT {
return a * x[0, 0] * x[0,0] + b * x[0,0] + c
}
public func gradient(_ x: MatrixT) -> MatrixT {
return MatrixT([[2.0 * a * x[0,0] + b]])
}
public func hessian(_ x: Matrix<Float>) -> Matrix<Float> {
return MatrixT([[2.0 * a]])
}
}
class optimisationTests: 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 testRosenbrock() {
let rb = Rosenbrock()
let x0 = Matrix<Float>([[0.0, 2.0]])
let optimizer = NewtonOptimizer(objective: rb, stepLength: 1.0, initX: x0, maxIters: 200, alphaMax: 1.0)
// let optimizer = SteepestDescentOptimizer(objective: rb, stepLength: 1.0, initX: x0, maxIters: 200)
// let optimizer = SCG(objective: rb, learning_rate: 0.01, init_x: x0, maxiters: 500)
let (x, _, _) = optimizer.optimize(verbose: true)
print(optimizer.Xs)
}
func testSCG() {
let scg = SCG(objective: Quad(2.0, -3.0, 5.0), learningRate: 0.01, initX: Matrix<Float>([[5.0]]), maxIters: 200)
let (x, _, _) = scg.optimize(verbose: true)
print(x)
}
func testNewton() {
let optimizer = NewtonOptimizer(objective: Quad(2.0, -3.0, 5.0), stepLength: 5.0, initX: Matrix<Float>([[10.0]]), maxIters: 100)
let (x, _, _) = optimizer.optimize(verbose: true)
print(x)
}
func testBFGS() {
let rb = Rosenbrock()
let x0 = Matrix<Float>([[-2.2, 1.2]])
let initH: Matrix<Float> = inv(rb.hessian(x0)) // Matrix([[1.0, 0.0],[0.0, 1.0]]) //
let optimizer = QuasiNewtonOptimizer(objective: rb, stepLength: 1.0, initX: x0, initH: nil, gTol: 1e-5, maxIters: 200, fTol: 1e-8, alphaMax: 1.0)
let (x, _, _) = optimizer.optimize(verbose: true)
print(optimizer.Xs)
}
func testInterpolant() {
func cubicInterpolate(_ a: Float, _ b: Float, _ c: Float, _ fa: Float, _ fb: Float, _ fc: Float, _ dfa: Float) -> Float {
let db = b - a
let dc = c - a
let A = Matrix<Float>([[pow(dc, 2), -pow(db, 2)],[-pow(dc, 3), pow(db, 3)]])
let v = Matrix<Float>([[fb - fa - dfa * db, fc - fa - dfa * dc]])
let C = 1.0 / (pow(dc, 2) * pow(db, 2) * (db - dc))
let ab = C * A * v.t
let (alpha, beta) = tuple(ab.grid)
let R = beta * beta - 3 * alpha * dfa
if R < 0 || alpha == 0 {
return Float.nan
}
let nom = -beta + sqrt(R)
return a + nom / (3.0 * alpha)
}
func quadraticInterpolate(_ a: Float, _ b: Float, _ fa: Float, _ fb: Float, _ dfa: Float) -> Float {
let d = b - a
let denom = 2.0 * (fb - fa - dfa * d) / (d * d)
if denom <= 0 || a == b {
return Float.nan
}
return a - dfa / denom
}
print(quadraticInterpolate(5.0, 10, 100.0, 200, -5.0))
print(cubicInterpolate(5.0, 10, 7, 100.0, 200, 120, -5.0))
}
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 |
dmitryrybakov/hubchatsample | hubchatTestapp/Networking/ForumNetwork.swift | 1 | 1513 | //
// ForumNetwork.swift
// hubchatTestapp
//
// Created by Dmitry on 24.03.17.
// Copyright © 2017 hubchat. All rights reserved.
//
import Alamofire
import AlamofireObjectMapper
import AlamofireImage
import ReactiveSwift
class ForumNetwork: ForumNetworking {
func updateForumInfo(completionHandler: @escaping (DataResponse<ForumHeaderModel>) -> ()) {
Alamofire.request(ServerURLAPIConstants.forumURLString).responseObject { (response: DataResponse<ForumHeaderModel>) in
completionHandler(response)
}
}
func updatePostsInfo(completionHandler: @escaping (DataResponse<[PostModel]>) -> ()) {
Alamofire.request(ServerURLAPIConstants.postsURLString).responseArray(keyPath:"posts") { (response: DataResponse<[PostModel]>) in
completionHandler(response)
}
}
func requestImage(imageURL:String, size:CGSize) -> SignalProducer<UIImage?, NetworkError> {
return SignalProducer { observer, disposable in
Alamofire.request(imageURL).responseImage { response in
switch response.result {
case .success(let image):
let filter = AspectScaledToFillSizeCircleFilter(size: size)
observer.send(value: filter.filter(image))
observer.sendCompleted()
case .failure(let error):
observer.send(error: NetworkError(error: error as NSError))
}
}
}
}
}
| mit |
LeeMZC/MZCWB | MZCWB/MZCWB/Classes/Other/Tool/Base/MZCBasePopManager.swift | 1 | 5110 | //
// MZCBasePresentationController.swift
// MZCWB
//
// Created by 马纵驰 on 16/8/10.
// Copyright © 2016年 马纵驰. All rights reserved.
//
import UIKit
import QorumLogs
//MARK:- 数据源代理
protocol MZCBasePresentationControllerDataSource : NSObjectProtocol {
}
//MARK:- 转场控制器
class MZCBasePresentationController: UIPresentationController,UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning{
var isPresent = false
weak var dataSource : MZCBasePresentationControllerDataSource?
/*
1.如果不自定义转场modal出来的控制器会移除原有的控制器
2.如果自定义转场modal出来的控制器不会移除原有的控制器
3.如果不自定义转场modal出来的控制器的尺寸和屏幕一样
4.如果自定义转场modal出来的控制器的尺寸我们可以自己在containerViewWillLayoutSubviews方法中控制
5.containerView 非常重要, 容器视图, 所有modal出来的视图都是添加到containerView上的
6.presentedView() 非常重要, 通过该方法能够拿到弹出的视图
// 用于布局转场动画弹出的控件 即将弹出时调用一次
// override func containerViewWillLayoutSubviews()
// {
// super.containerViewWillLayoutSubviews()
// }
required override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
}
required override init() {
super.init()
}
*/
}
//MARK:- UIViewControllerTransitioningDelegate
extension MZCBasePresentationController {
//MARK:转场代理
func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?{
let pc = MZCBasePresentationController(presentedViewController: presented, presentingViewController: presenting)
pc.dataSource = dataSource
return pc
}
//显示时调用
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
return self
}
//消失时调用
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
return self
}
}
//MARK:- UIViewControllerAnimatedTransitioning
extension MZCBasePresentationController {
//override 显示 和 消失 的动画时间
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval{
return 0.0
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning){
isPresent ? willDismissedController(transitionContext) : willPresentedController(transitionContext)
isPresent = !isPresent
}
/// 执行展现动画 override
func willPresentedController(transitionContext: UIViewControllerContextTransitioning)
{
/**
1.获取需要弹出视图
通过ToViewKey取出的就是toVC对应的view
guard let toView = transitionContext.viewForKey(UITransitionContextToViewKey) else
{
return
}
2.将需要弹出的视图添加到containerView上
transitionContext.containerView()?.addSubview(toView)
3.执行动画
toView.transform = CGAffineTransformMakeScale(1.0, 0.0)
设置锚点
toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0)
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
toView.transform = CGAffineTransformIdentity
}) { (_) -> Void in
注意: 自定转场动画, 在执行完动画之后一定要告诉系统动画执行完毕了
transitionContext.completeTransition(true)
}
*/
}
/// 执行消失动画 override
func willDismissedController(transitionContext: UIViewControllerContextTransitioning)
{
/**
1.拿到需要消失的视图
guard let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) else
{
return
}
2.执行动画让视图消失
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
// 突然消失的原因: CGFloat不准确, 导致无法执行动画, 遇到这样的问题只需要将CGFloat的值设置为一个很小的值即可
fromView.transform = CGAffineTransformMakeScale(1.0, 0.00001)
}, completion: { (_) -> Void in
// 注意: 自定转场动画, 在执行完动画之后一定要告诉系统动画执行完毕了
transitionContext.completeTransition(true)
})
*/
}
} | artistic-2.0 |
brbulic/fastlane | fastlane/swift/GymfileProtocol.swift | 1 | 7374 | // GymfileProtocol.swift
// Copyright (c) 2020 FastlaneTools
public protocol GymfileProtocol: class {
/// Path to the workspace file
var workspace: String? { get }
/// Path to the project file
var project: String? { get }
/// The project's scheme. Make sure it's marked as `Shared`
var scheme: String? { get }
/// Should the project be cleaned before building it?
var clean: Bool { get }
/// The directory in which the ipa file should be stored in
var outputDirectory: String { get }
/// The name of the resulting ipa file
var outputName: String? { get }
/// The configuration to use when building the app. Defaults to 'Release'
var configuration: String? { get }
/// Hide all information that's not necessary while building
var silent: Bool { get }
/// The name of the code signing identity to use. It has to match the name exactly. e.g. 'iPhone Distribution: SunApps GmbH'
var codesigningIdentity: String? { get }
/// Should we skip packaging the ipa?
var skipPackageIpa: Bool { get }
/// Should we skip packaging the pkg?
var skipPackagePkg: Bool { get }
/// Should the ipa file include symbols?
var includeSymbols: Bool? { get }
/// Should the ipa file include bitcode?
var includeBitcode: Bool? { get }
/// Method used to export the archive. Valid values are: app-store, ad-hoc, package, enterprise, development, developer-id
var exportMethod: String? { get }
/// Path to an export options plist or a hash with export options. Use 'xcodebuild -help' to print the full set of available options
var exportOptions: [String: Any]? { get }
/// Pass additional arguments to xcodebuild for the package phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++"
var exportXcargs: String? { get }
/// Export ipa from previously built xcarchive. Uses archive_path as source
var skipBuildArchive: Bool? { get }
/// After building, don't archive, effectively not including -archivePath param
var skipArchive: Bool? { get }
/// Build without codesigning
var skipCodesigning: Bool? { get }
/// Platform to build when using a Catalyst enabled app. Valid values are: ios, macos
var catalystPlatform: String? { get }
/// Full name of 3rd Party Mac Developer Installer or Developer ID Installer certificate. Example: `3rd Party Mac Developer Installer: Your Company (ABC1234XWYZ)`
var installerCertName: String? { get }
/// The directory in which the archive should be stored in
var buildPath: String? { get }
/// The path to the created archive
var archivePath: String? { get }
/// The directory where built products and other derived data will go
var derivedDataPath: String? { get }
/// Should an Xcode result bundle be generated in the output directory
var resultBundle: Bool { get }
/// Path to the result bundle directory to create. Ignored if `result_bundle` if false
var resultBundlePath: String? { get }
/// The directory where to store the build log
var buildlogPath: String { get }
/// The SDK that should be used for building the application
var sdk: String? { get }
/// The toolchain that should be used for building the application (e.g. com.apple.dt.toolchain.Swift_2_3, org.swift.30p620160816a)
var toolchain: String? { get }
/// Use a custom destination for building the app
var destination: String? { get }
/// Optional: Sometimes you need to specify a team id when exporting the ipa file
var exportTeamId: String? { get }
/// Pass additional arguments to xcodebuild for the build phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++"
var xcargs: String? { get }
/// Use an extra XCCONFIG file to build your app
var xcconfig: String? { get }
/// Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path
var suppressXcodeOutput: Bool? { get }
/// Disable xcpretty formatting of build output
var disableXcpretty: Bool? { get }
/// Use the test (RSpec style) format for build output
var xcprettyTestFormat: Bool? { get }
/// A custom xcpretty formatter to use
var xcprettyFormatter: String? { get }
/// Have xcpretty create a JUnit-style XML report at the provided path
var xcprettyReportJunit: String? { get }
/// Have xcpretty create a simple HTML report at the provided path
var xcprettyReportHtml: String? { get }
/// Have xcpretty create a JSON compilation database at the provided path
var xcprettyReportJson: String? { get }
/// Analyze the project build time and store the output in 'culprits.txt' file
var analyzeBuildTime: Bool? { get }
/// Have xcpretty use unicode encoding when reporting builds
var xcprettyUtf: Bool? { get }
/// Do not try to build a profile mapping from the xcodeproj. Match or a manually provided mapping should be used
var skipProfileDetection: Bool { get }
/// Sets a custom path for Swift Package Manager dependencies
var clonedSourcePackagesPath: String? { get }
}
public extension GymfileProtocol {
var workspace: String? { return nil }
var project: String? { return nil }
var scheme: String? { return nil }
var clean: Bool { return false }
var outputDirectory: String { return "." }
var outputName: String? { return nil }
var configuration: String? { return nil }
var silent: Bool { return false }
var codesigningIdentity: String? { return nil }
var skipPackageIpa: Bool { return false }
var skipPackagePkg: Bool { return false }
var includeSymbols: Bool? { return nil }
var includeBitcode: Bool? { return nil }
var exportMethod: String? { return nil }
var exportOptions: [String: Any]? { return nil }
var exportXcargs: String? { return nil }
var skipBuildArchive: Bool? { return nil }
var skipArchive: Bool? { return nil }
var skipCodesigning: Bool? { return nil }
var catalystPlatform: String? { return nil }
var installerCertName: String? { return nil }
var buildPath: String? { return nil }
var archivePath: String? { return nil }
var derivedDataPath: String? { return nil }
var resultBundle: Bool { return false }
var resultBundlePath: String? { return nil }
var buildlogPath: String { return "~/Library/Logs/gym" }
var sdk: String? { return nil }
var toolchain: String? { return nil }
var destination: String? { return nil }
var exportTeamId: String? { return nil }
var xcargs: String? { return nil }
var xcconfig: String? { return nil }
var suppressXcodeOutput: Bool? { return nil }
var disableXcpretty: Bool? { return nil }
var xcprettyTestFormat: Bool? { return nil }
var xcprettyFormatter: String? { return nil }
var xcprettyReportJunit: String? { return nil }
var xcprettyReportHtml: String? { return nil }
var xcprettyReportJson: String? { return nil }
var analyzeBuildTime: Bool? { return nil }
var xcprettyUtf: Bool? { return nil }
var skipProfileDetection: Bool { return false }
var clonedSourcePackagesPath: String? { return nil }
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.46]
| mit |
nickqiao/NKBill | NKBill/Controller/PasscodeVcManager.swift | 1 | 1541 | //
// PasscodeVcManager.swift
// NKBill
//
// Created by nick on 16/6/4.
// Copyright © 2016年 NickChen. All rights reserved.
//
import Foundation
import PasscodeLock
import LocalAuthentication
class PasscodeVcManager {
private init () {}
static let sharedInstance = PasscodeVcManager()
private var configuration = PasscodeLockConfiguration(repository: UserDefaultsPasscodeRepository())
private var passcodeVC : PasscodeLockViewController?
// static func canUseTouchId() -> Bool {
//
// let context: LAContext! = LAContext()
// var errora: NSError?
//
// let os = NSProcessInfo().operatingSystemVersion
// if os.majorVersion < 8 {
// return false
// }
//
// return context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &errora)
//
// }
func showSetcodeVc() {
passcodeVC = PasscodeLockViewController(state: .SetPasscode, configuration: configuration)
UIApplication.topViewController()?.presentViewController(passcodeVC!, animated: true, completion: nil)
}
func showDeleteCodeVc() {
passcodeVC = PasscodeLockViewController(state: .RemovePasscode, configuration: configuration)
passcodeVC!.successCallback = { lock in
lock.repository.deletePasscode()
}
UIApplication.topViewController()?.presentViewController(passcodeVC!, animated: true, completion: nil)
}
} | apache-2.0 |
devios1/Gravity | Plugins/Layout.swift | 1 | 28202 | //
// Layout.swift
// Gravity
//
// Created by Logan Murray on 2016-02-15.
// Copyright © 2016 Logan Murray. All rights reserved.
//
import Foundation
@available(iOS 9.0, *)
extension Gravity {
@objc public class Layout: GravityPlugin {
public var constraints = [String : NSLayoutConstraint]() // store constraints here based on their attribute name (width, minHeight, etc.) -- we should move this to a plugin, but only if we can put all or most of the constraint registering in there as well
private static let keywords = ["fill", "auto"]
private var widthIdentifiers = [String: Set<GravityNode>]() // instead of storing a dictionary of arrays, can we store a dictionary that just points to the first-registered view, and then all subsequent views just add constraints back to that view?
// we should reintroduce this as an *optional* array to represent attributes handled in means *other* than handleAttribute
public override var handledAttributes: [String]? {
get {
return [
"gravity",
"height", "minHeight", "maxHeight",
"margin", "leftMargin", "topMargin", "rightMargin", "bottomMargin",
"padding", "leftPadding", "topPadding", "rightPadding", "bottomPadding",
"shrinks",
"width", "minWidth", "maxWidth",
"zIndex"
]
}
}
static var swizzleToken: dispatch_once_t = 0
public override class func initialize() {
Gravity.swizzle(UIView.self, original: #selector(UIView.alignmentRectInsets), override: #selector(UIView.grav_alignmentRectInsets)) // verify align as func
// Gravity.swizzle(UIView.self, original: #selector(UIView.didMoveToSuperview), override: #selector(UIView.grav_didMoveToSuperview))
// dispatch_once(&swizzleToken) {
// // method swizzling:
// let alignmentRectInsets_orig = class_getInstanceMethod(UIView.self, #selector(UIView.alignmentRectInsets))
// let alignmentRectInsets_swiz = class_getInstanceMethod(UIView.self, Selector("grav_alignmentRectInsets"))
//
// if class_addMethod(UIView.self, #selector(UIView.alignmentRectInsets), method_getImplementation(alignmentRectInsets_swiz), method_getTypeEncoding(alignmentRectInsets_swiz)) {
// class_replaceMethod(UIView.self, Selector("grav_alignmentRectInsets"), method_getImplementation(alignmentRectInsets_orig), method_getTypeEncoding(alignmentRectInsets_orig));
// } else {
// method_exchangeImplementations(alignmentRectInsets_orig, alignmentRectInsets_swiz);
// }
// }
}
public override func instantiateView(node: GravityNode) -> UIView? {
// should this be handled in a stackview plugin?
switch node.nodeName {
case "H":
let stackView = UIStackView()
stackView.axis = .Horizontal
return stackView
case "V":
let stackView = UIStackView()
stackView.axis = .Vertical
return stackView
default:
return nil
}
}
public override func processValue(value: GravityNode) {
guard let node = value.parentNode else {
return
}
guard let stringValue = value.stringValue else {
return
}
// this has to be done here because widthIdentifiers should be referenced relative to the document the value is defined in, not the node they are applied to
if value.attributeName == "width" {
if !Layout.keywords.contains(stringValue) {
let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
if stringValue.rangeOfCharacterFromSet(charset) != nil { // if the value contains any characters other than numeric characters
if widthIdentifiers[stringValue] == nil {
widthIdentifiers[stringValue] = Set<GravityNode>()
}
widthIdentifiers[stringValue]?.unionInPlace([node])
}
}
return
}
return
}
/// Removes *all* constraints with a given identifier (verify that there can in fact be multiple).
private func removeConstraint(identifier: String, fromNode node: GravityNode) {
for constraint in node.view.constraints.filter({ $0.identifier == identifier }) {
// node.view.removeConstraint(constraint)
constraint.active = false // does this also mean we have to set it to true instead of re-adding??
}
}
public override func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult {
// if let width = node["width"]?.stringValue {
// if !Layout.keywords.contains(width) {
// let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
// if width.rangeOfCharacterFromSet(charset) != nil { // if the value contains any characters other than numeric characters
//// if widthIdentifiers[width] == nil {
//// widthIdentifiers[width] = [GravityNode]()
//// }
//// widthIdentifiers[width]?.append(node)
// } else {
// if let width = node.width {
// NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) {
// node.constraints["width"] = node.view.autoSetDimension(ALDimension.Width, toSize: CGFloat(width))
// }
// }
// }
// }
// }
// public override func preprocessAttribute(node: GravityNode, attribute: String, inout value: GravityNode) -> GravityResult {
// NSLog(attribute)
// // TODO: can we do anything with node values here?
// guard let stringValue = value.stringValue else {
// return .NotHandled
// }
// switch attribute {
// TODO: may want to set these with higher priority than default to avoid view/container bindings conflicting
// we should also capture these priorities as constants and put them all in one place for easier tweaking and balancing
// case "width":
// if !Layout.keywords.contains(stringValue) {
// let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
// if stringValue.rangeOfCharacterFromSet(charset) != nil { // if the value contains any characters other than numeric characters
//// if widthIdentifiers[stringValue] == nil {
//// widthIdentifiers[stringValue] = [GravityNode]()
//// }
//// widthIdentifiers[stringValue]?.append(node)
// } else {
// NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) {
// node.constraints[attribute] = node.view.autoSetDimension(ALDimension.Width, toSize: CGFloat((stringValue as NSString).floatValue))
// }
// }
// }
// return .Handled
if attribute == "width" || attribute == nil {
if value != nil && node.width != nil {
// will this properly handle widths of "fill"? right now it'll remove the width constraint but i think that's ok
NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) {
node.constraints[attribute!] = node.view.autoSetDimension(ALDimension.Width, toSize: CGFloat(node.width!)).autoIdentify("width")
}
return .Handled
} else {
removeConstraint("width", fromNode: node)
}
}
if attribute == "minWidth" || attribute == nil {
if let minWidth = node.minWidth {
// TODO: we should consider doing this with raw auto layout by looking up a constraint or creating one and modifying its properties
// let constraint = node.constraints["minWidth"] ?? NSLayoutConstraint()
// NSLayoutConstraint(item: node.view, attribute: .Width, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 0.0, constant: CGFloat(minWidth)
NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) {
node.constraints[attribute!] = node.view.autoSetDimension(.Width, toSize: CGFloat(minWidth), relation: .GreaterThanOrEqual).autoIdentify(attribute!)
}
NSLayoutConstraint.autoSetPriority(50) {//test
node.view.autoSetDimension(.Width, toSize: CGFloat(minWidth))
}
return .Handled
} else {
removeConstraint("minWidth", fromNode: node)
}
}
if attribute == "maxWidth" || attribute == nil {
if let maxWidth = node.maxWidth {
if node.isOtherwiseFilledAlongAxis(.Horizontal) {
// a maxWidth that is filled is equal to an explicit width
NSLayoutConstraint.autoSetPriority(700) {
// FIXME: *HOWEVER* it should have lesser priority than the fill binding because it may still be smaller if the fill size is < maxWidth!
NSLog("filled maxWidth found")
node.constraints["maxWidth"] = node.view.autoSetDimension(.Width, toSize: CGFloat(maxWidth))
}
// NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) {
// // experimental (we need to keep a maxWidth inside a filled view contained to that filled view, at a higher priority than typical view containment)
// // FIXME: we might want to move this to postprocess so it can bind to the parent view properly
// node.view.autoPinEdgeToSuperviewEdge(.Left, withInset: CGFloat(node.leftInset))
// node.view.autoPinEdgeToSuperviewEdge(.Right, withInset: CGFloat(node.rightInset))
// }
} else {
NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { // these have to be higher priority than the normal and fill binding to parent edges
node.constraints["maxWidth"] = node.view.autoSetDimension(.Width, toSize: CGFloat(maxWidth), relation: .LessThanOrEqual)
}
}
return .Handled
} else {
removeConstraint("maxWidth", fromNode: node)
}
}
if attribute == "height" || attribute == nil {
if let height = node.height {
// if !Layout.keywords.contains(stringValue) {
// TODO: add support for height identifiers
NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) {
node.constraints["height"] = node.view.autoSetDimension(.Height, toSize: CGFloat(height)).autoIdentify("height")
}
// }
return .Handled
} else {
removeConstraint("height", fromNode: node)
}
}
if attribute == "minHeight" || attribute == nil {
if let minHeight = node.minHeight {
NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) {
node.constraints["minHeight"] = node.view.autoSetDimension(.Height, toSize: CGFloat(minHeight), relation: .GreaterThanOrEqual).autoIdentify("minHeight")
}
NSLayoutConstraint.autoSetPriority(50) {//test
node.view.autoSetDimension(.Height, toSize: CGFloat(minHeight)).autoIdentify("minHeight") // FIXME: verify that it's safe to use the same identifier for two constraints!! we need to be able to delete them all
}
return .Handled
} else {
removeConstraint("minHeight", fromNode: node)
}
}
if attribute == "maxHeight" || attribute == nil {
if let maxHeight = node.maxHeight {
NSLayoutConstraint.autoSetPriority(GravityPriority.ExplicitSize) { // these have to be higher priority than the normal and fill binding to parent edges
if node.isOtherwiseFilledAlongAxis(.Vertical) {
// a maxWidth that is filled is equal to an explicit width
NSLog("filled maxHeight found")
node.constraints["maxHeight"] = node.view.autoSetDimension(.Height, toSize: CGFloat(maxHeight))
} else {
node.constraints["maxHeight"] = node.view.autoSetDimension(.Height, toSize: CGFloat(maxHeight), relation: .LessThanOrEqual)
}
}
return .Handled
} else {
removeConstraint("maxHeight", fromNode: node)
}
}
return .NotHandled
}
public override func processContents(node: GravityNode) -> GravityResult {
// public override func addChild(node: GravityNode, child: GravityNode) -> GravityResult {
if !node.viewIsInstantiated {
return .NotHandled // no default child handling if we don't have a valid view
}
// TODO: we may be better off actually setting a z-index on the views; this needs to be computed
// we have to do a manual fucking insertion sort here, jesus gawd what the fuck swift?!! no stable sort in version 2.0 of a language??? how is that even remotely acceptable??
// because, you know, i enjoy wasting my time writing sort algorithms!
var sortedChildren = [GravityNode]()
for childNode in node.childNodes {
var handled = false
for i in 0 ..< sortedChildren.count {
if sortedChildren[i].zIndex > childNode.zIndex {
sortedChildren.insert(childNode, atIndex: i)
handled = true
break
}
}
if !handled {
sortedChildren.append(childNode)
}
}
// i'm actually thinking this might make the most sense all in one place in postprocess
for childNode in sortedChildren {
assert(!childNode.unprocessed)
node.view.addSubview(childNode.view) // recurse?
assert(childNode.view.superview != nil)
// let leftInset = CGFloat(node.leftMargin + node.leftPadding)
// let rightInset = CGFloat(node.rightMargin + node.rightPadding)
NSLayoutConstraint.autoSetPriority(GravityPriority.Gravity) {
switch childNode.gravity.horizontal {
case .Left:
childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: CGFloat(childNode.leftInset))
break
case .Center:
let constraint = childNode.view.autoAlignAxisToSuperviewAxis(ALAxis.Vertical)
constraint.constant = CGFloat(childNode.rightInset - childNode.leftInset); // test (not working)
break
case .Right:
childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: CGFloat(childNode.rightInset))
break
default:
break
}
switch childNode.gravity.vertical {
case .Top:
childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: CGFloat(childNode.topInset))
break
case .Middle:
childNode.view.autoAlignAxisToSuperviewAxis(ALAxis.Horizontal)
break
case .Bottom:
childNode.view.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: CGFloat(childNode.bottomInset))
break
default:
break
}
}
}
return .Handled
}
public override func postprocessNode(node: GravityNode) {
// FIXME: put widthIdentifiers back in here somewhere
if let superview = node.view.superview {
if (superview as? UIStackView)?.axis != .Horizontal { // we are not inside a stack view (of the same axis)
// TODO: what priority should these be?
// we need to make a special exception for UIScrollView and potentially others. should we move this back into a default handler/handleChildNodes?
// FIXME: fix
// NSLayoutConstraint.autoSetPriority(200 - Float(node.recursiveDepth)) {
// node.view.autoMatchDimension(.Width, toDimension: .Width, ofView: superview, withOffset: 0, relation: .Equal)
// }
var priority = GravityPriority.ViewContainment + Float(node.recursiveDepth)
if node.isDivergentAlongAxis(.Horizontal) {
priority = 200 + Float(node.recursiveDepth)
}
NSLayoutConstraint.autoSetPriority(priority) {
node.constraints["view-left"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: CGFloat(node.leftInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-left")
node.constraints["view-right"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: CGFloat(node.rightInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-right")
}
}
if (superview as? UIStackView)?.axis != .Vertical { // we are not inside a stack view (of the same axis)
// FIXME: reenable this when we get horizontal working:
// node.view.autoMatchDimension(.Height, toDimension: .Height, ofView: node.parentNode!.view, withOffset: 0, relation: .LessThanOrEqual)
var priority = GravityPriority.ViewContainment + Float(node.recursiveDepth)
if node.isDivergentAlongAxis(.Vertical) {
priority = 200 + Float(node.recursiveDepth)
}
NSLayoutConstraint.autoSetPriority(priority) {
node.constraints["view-top"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: CGFloat(node.topInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-top")
node.constraints["view-bottom"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: CGFloat(node.bottomInset), relation: NSLayoutRelation.Equal).autoIdentify("gravity-view-bottom")
}
}
// minWidth, etc. should probably be higher priority than these so they can override fill size
if node.isFilledAlongAxis(.Horizontal) {
node.view.setContentHuggingPriority(GravityPriority.FillSizeHugging, forAxis: .Horizontal)
if (superview as? UIStackView)?.axis != .Horizontal {
NSLayoutConstraint.autoSetPriority(GravityPriority.FillSize + Float(node.recursiveDepth)) { // i recently changed this from - to +; i didn't think it through but it solved an ambiguous layout problem with InventoryCell
// node.view.autoMatchDimension(ALDimension.Width, toDimension: ALDimension.Width, ofView: superview)
node.constraints["fill-left"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: CGFloat(node.leftInset)).autoIdentify("gravity-fill-left") // leading?
node.constraints["fill-right"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: CGFloat(node.rightInset)).autoIdentify("gravity-fill-right") // trailing?
}
}
}
if node.isFilledAlongAxis(.Vertical) { // should this be otherwise? one of these is wrong
node.view.setContentHuggingPriority(GravityPriority.FillSizeHugging, forAxis: .Vertical)
if (superview as? UIStackView)?.axis != .Vertical {
NSLayoutConstraint.autoSetPriority(GravityPriority.FillSize + Float(node.recursiveDepth)) {
// node.view.autoMatchDimension(ALDimension.Height, toDimension: ALDimension.Height, ofView: superview)
node.constraints["fill-top"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: CGFloat(node.topInset)).autoIdentify("gravity-fill-top")
node.constraints["fill-bottom"] = node.view.autoPinEdgeToSuperviewEdge(ALEdge.Bottom, withInset: CGFloat(node.topInset)).autoIdentify("gravity-fill-bottom")
}
}
}
} else {
NSLog("superview nil")
}
// do we need/want to set content hugging if superview is nil?
}
// public override func postprocessDocument(document: GravityDocument) {
// NSLog("postprocessDocument: \(document.node.nodeName)")
//
// var widthIdentifiers = [String: GravityNode]()
// for node in document.node {
// if let width = node["width"]?.stringValue {
// let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
// if width.rangeOfCharacterFromSet(charset) != nil {
// if let archetype = widthIdentifiers[width] {
// NSLog("Matching dimension of \(unsafeAddressOf(node)) to \(unsafeAddressOf(archetype)).")
// // TODO: add a gravity priority
// node.view.autoMatchDimension(ALDimension.Width, toDimension: ALDimension.Width, ofView: archetype.view)
// } else {
// widthIdentifiers[width] = node
// }
// }
// }
// }
// for (identifier, nodes) in widthIdentifiers {
// let first = nodes[0]
// for var i = 1; i < nodes.count; i++ {
// // priority?? also we need to add a constraint (but what should its identifier be?)
// NSLog("Matching dimension of \(unsafeAddressOf(nodes[i])) to \(unsafeAddressOf(first)).")
// nodes[i].view.autoMatchDimension(ALDimension.Width, toDimension: ALDimension.Width, ofView: first.view)
// }
// }
// }
}
}
public struct GravityDirection {
var horizontal = Horizontal.Inherit
var vertical = Vertical.Inherit
public enum Horizontal: Int {
case Inherit = 0
case Left
case Right
case Center
}
public enum Vertical: Int {
case Inherit = 0
case Top
case Bottom
case Middle
}
// these let you shortcut the Horizontal and Vertical enums and say e.g. GravityDirection.Center
public static let Left = Horizontal.Left
public static let Right = Horizontal.Right
public static let Center = Horizontal.Center
public static let Top = Vertical.Top
public static let Bottom = Vertical.Bottom
public static let Middle = Vertical.Middle
init() {
self.horizontal = .Inherit
self.vertical = .Inherit
}
init(horizontal: Horizontal, vertical: Vertical) {
self.horizontal = horizontal
self.vertical = vertical
}
init?(_ stringValue: String?) {
guard let stringValue = stringValue else {
return nil
}
let valueParts = stringValue.lowercaseString.componentsSeparatedByString(" ")
if valueParts.contains("left") {
horizontal = .Left
} else if valueParts.contains("center") {
horizontal = .Center
} else if valueParts.contains("right") {
horizontal = .Right
}
if valueParts.contains("top") {
vertical = .Top
} else if valueParts.contains("middle") {
vertical = .Middle
} else if valueParts.contains("bottom") {
vertical = .Bottom
}
}
}
@available(iOS 9.0, *)
extension UIView {
public func grav_alignmentRectInsets() -> UIEdgeInsets {
// get {
var insets = self.grav_alignmentRectInsets()
if let node = self.gravityNode {
insets = UIEdgeInsetsMake(insets.top - CGFloat(node.topMargin), insets.left - CGFloat(node.leftMargin), insets.bottom - CGFloat(node.bottomMargin), insets.right - CGFloat(node.rightMargin))
}
return insets
// }
}
public func grav_didMoveToSuperview() {
grav_didMoveToSuperview()
if let gravityNode = gravityNode {
if gravityNode.parentNode != nil {
self.translatesAutoresizingMaskIntoConstraints = false // exp.
}
gravityNode.postprocess()
}
}
}
@available(iOS 9.0, *)
extension GravityNode {
// MARK: Debugging
internal var leftInset: Float {
get { return (parentNode?.leftMargin ?? 0) + (parentNode?.leftPadding ?? 0) }
}
internal var topInset: Float {
get { return (parentNode?.topMargin ?? 0) + (parentNode?.topPadding ?? 0) }
}
internal var rightInset: Float {
get { return (parentNode?.rightMargin ?? 0) + (parentNode?.rightPadding ?? 0) }
}
internal var bottomInset: Float {
get { return (parentNode?.bottomMargin ?? 0) + (parentNode?.bottomPadding ?? 0) }
}
// MARK: Public
public var gravity: GravityDirection {
get {
var gravity = GravityDirection(self["gravity"]?.stringValue) ?? GravityDirection()
if gravity.horizontal == .Inherit {
gravity.horizontal = parentNode?.gravity.horizontal ?? .Center
}
if gravity.vertical == .Inherit {
gravity.vertical = parentNode?.gravity.vertical ?? .Middle
}
return gravity
}
}
public var width: Float? {
get {
return self["width"]?.floatValue // verify this is nil for a string, also test "123test" etc.
}
}
public var height: Float? {
get {
return self["height"]?.floatValue
}
}
public var minWidth: Float? {
get {
return self["minWidth"]?.floatValue
}
}
public var maxWidth: Float? {
get {
return self["maxWidth"]?.floatValue
}
}
public var minHeight: Float? {
get {
return self["minHeight"]?.floatValue
}
}
public var maxHeight: Float? {
get {
return self["maxHeight"]?.floatValue
}
}
public var margin: Float {
get {
return self["margin"]?.floatValue ?? 0
}
}
public var leftMargin: Float {
get {
return self["leftMargin"]?.floatValue ?? self.margin
}
}
public var topMargin: Float {
get {
return self["topMargin"]?.floatValue ?? self.margin
}
}
public var rightMargin: Float {
get {
return self["rightMargin"]?.floatValue ?? self.margin
}
}
public var bottomMargin: Float {
get {
return self["bottomMargin"]?.floatValue ?? self.margin
}
}
public var padding: Float {
get {
return self["padding"]?.floatValue ?? 0
}
}
public var leftPadding: Float {
get {
return self["leftPadding"]?.floatValue ?? self.padding
}
}
public var topPadding: Float {
get {
return self["topPadding"]?.floatValue ?? self.padding
}
}
public var rightPadding: Float {
get {
return self["rightPadding"]?.floatValue ?? self.padding
}
}
public var bottomPadding: Float {
get {
return self["bottomPadding"]?.floatValue ?? self.padding
}
}
public var zIndex: Int {
get {
return Int(self["zIndex"]?.stringValue ?? "0")!
}
}
internal func isExplicitlySizedAlongAxis(axis: UILayoutConstraintAxis) -> Bool {
switch axis {
case .Horizontal:
if let width = self["width"]?.stringValue {
let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
if width.rangeOfCharacterFromSet(charset) == nil {
return true
}
}
return false
case .Vertical:
if let height = self["height"]?.stringValue {
let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
if height.rangeOfCharacterFromSet(charset) == nil {
return true
}
}
return false
}
}
/// A node is divergent from its parent on an axis if it has the potential that at least one edge of that axis is not bound to its corresponding parent edge. For example, an auto-sized node inside a fixed size node has the potential to be smaller than its container, and is therefore considered divergent.
internal func isDivergentAlongAxis(axis: UILayoutConstraintAxis) -> Bool {
// make sure there aren't problems caling this when a view is added to its superview but doesn't have its parent node set
if view.superview != nil {
// assert(parentNode != nil)
if parentNode == nil {
NSLog("Warning: checking isDivergent superview exists but no parentNode")
}
}
// wtf is this??
// if parentNode != nil && parentNode!.parentNode != nil && document.parentNode != nil {
// return true
// }
guard let parentNode = parentNode else {
return false
}
if self.recursiveDepth == 1 { // the root node
return true // leaving in for now
}
if parentNode.isFilledAlongAxis(axis) {
return true
} else if self.isFilledAlongAxis(axis) {
return false
} else if parentNode.isExplicitlySizedAlongAxis(axis) {
return true
}
// should we allow plugins to override this definition? depending on UIStackView here doesn't feel right
switch axis {
case .Horizontal:
if (parentNode.view as? UIStackView)?.axis == .Vertical {
return true
}
if parentNode["minWidth"] != nil {
return true
}
case .Vertical:
if (parentNode.view as? UIStackView)?.axis == .Horizontal {
return true
}
if parentNode["minHeight"] != nil {
return true
}
}
return false
}
internal func isFilledAlongAxis(axis: UILayoutConstraintAxis) -> Bool {
if !isOtherwiseFilledAlongAxis(axis) {
return false
}
switch axis {
case .Horizontal:
return self["maxWidth"] == nil
case .Vertical:
return self["maxHeight"] == nil
}
}
internal func isOtherwiseFilledAlongAxis(axis: UILayoutConstraintAxis) -> Bool {
switch axis {
case .Horizontal:
// if self["maxWidth"] != nil { // we could verify that it is numeric, but i can't think of a concise way to do that
// // even if we have width="fill", if there's a maxWidth, that still just equals width
// return false
// }
if let width = self["width"]?.stringValue {
if width == "fill" {
// are there any other negation cases?
return true
}
let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
if width.rangeOfCharacterFromSet(charset) == nil {
return false
}
}
break
case .Vertical:
// if self["maxHeight"] != nil { // we could verify that it is numeric, but i can't think of a concise way to do that
// // even if we have width="fill", if there's a maxWidth, that still just equals width
// return false
// }
if let height = self["height"]?.stringValue {
if height == "fill" {
// are there any other negation cases?
return true
}
let charset = NSCharacterSet(charactersInString: "-0123456789.").invertedSet
if height.rangeOfCharacterFromSet(charset) == nil {
return false
}
}
break
}
for childNode in childNodes {
if childNode.isFilledAlongAxis(axis) {
return true
}
}
return false
}
} | mit |
swift-lang/swift-k | tests/language-behaviour/strings/761-dirname.swift | 2 | 111 | type file{}
file f<"/etc/fstab">;
string s = @dirname(f);
string t = @tostring(s);
tracef("dirname: %s\n", s);
| apache-2.0 |
keyeMyria/edx-app-ios | Source/CourseOutlineHeaderCell.swift | 4 | 1891 | //
// CourseOutlineHeaderCell.swift
// edX
//
// Created by Akiva Leffert on 4/30/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import UIKit
class CourseOutlineHeaderCell : UITableViewHeaderFooterView {
static let identifier = "CourseOutlineHeaderCellIdentifier"
let headerFontStyle = OEXTextStyle(weight: .SemiBold, size: .XSmall, color : OEXStyles.sharedStyles().neutralBase())
let headerLabel = UILabel()
let horizontalTopLine = UIView()
var block : CourseBlock? {
didSet {
headerLabel.attributedText = headerFontStyle.attributedStringWithText(block?.name)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
addSubviews()
setStyles()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Helper Methods
private func addSubviews(){
addSubview(headerLabel)
addSubview(horizontalTopLine)
}
private func setStyles(){
//Using CGRectZero size because the backgroundView automatically resizes.
backgroundView = UIView(frame: CGRectZero)
backgroundView?.backgroundColor = OEXStyles.sharedStyles().neutralWhiteT()
horizontalTopLine.backgroundColor = OEXStyles.sharedStyles().neutralBase()
}
// Skip autolayout for performance reasons
override func layoutSubviews() {
super.layoutSubviews()
let margin = OEXStyles.sharedStyles().standardHorizontalMargin() - 5
self.headerLabel.frame = UIEdgeInsetsInsetRect(self.bounds, UIEdgeInsetsMake(0, margin, 0, margin))
horizontalTopLine.frame = CGRectMake(0, 0, self.bounds.size.width, OEXStyles.dividerSize())
}
} | apache-2.0 |
johnno1962d/swift | test/expr/cast/as_coerce.swift | 3 | 3849 | // RUN: %target-parse-verify-swift
// Test the use of 'as' for type coercion (which requires no checking).
@objc protocol P1 {
func foo()
}
class A : P1 {
@objc func foo() { }
}
@objc class B : A {
func bar() { }
}
func doFoo() {}
func test_coercion(_ a: A, b: B) {
// Coercion to a protocol type
let x = a as P1
x.foo()
// Coercion to a superclass type
let y = b as A
y.foo()
}
class C : B { }
class D : C { }
func prefer_coercion(_ c: inout C) {
let d = c as! D
c = d
}
// Coerce literals
var i32 = 1 as Int32
var i8 = -1 as Int8
// Coerce to a superclass with generic parameter inference
class C1<T> {
func f(_ x: T) { }
}
class C2<T> : C1<Int> { }
var c2 = C2<()>()
var c1 = c2 as C1
c1.f(5)
@objc protocol P {}
class CC : P {}
let cc: Any = CC()
if cc is P {
doFoo()
}
if let p = cc as? P {
doFoo()
}
// Test that 'as?' coercion fails.
let strImplicitOpt: String! = nil
strImplicitOpt as? String // expected-warning{{conditional cast from 'String!' to 'String' always succeeds}}
class C3 {}
class C4 : C3 {}
class C5 {}
var c: AnyObject = C3()
if let castX = c as! C4? {} // expected-error {{cannot downcast from 'AnyObject' to a more optional type 'C4?'}}
// Only suggest replacing 'as' with 'as!' if it would fix the error.
C3() as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{6-8=as!}}
C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}}
// Diagnostic shouldn't include @lvalue in type of c3.
var c3 = C3()
c3 as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{4-6=as!}}
// <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions
1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}}
1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}}
["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}}
([1, 2, 1.0], 1) as ([String], Int) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
[[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
(1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type 'Double' to type 'Int' in coercion}}
(1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}}
(1, 1.0, "a", [1, 23]) as (Int, Double, String, [String]) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
[1] as! [String] // expected-error{{'[Int]' is not convertible to '[String]'}}
[(1, (1, 1))] as! [(Int, (String, Int))] // expected-error{{'[(Int, (Int, Int))]' is not convertible to '[(Int, (String, Int))]'}}
// <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type
"hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{9-20=}}
// <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its
func f(_ x : String) {}
f("what" as Any as String) // expected-error{{'Any' (aka 'protocol<>') is not convertible to 'String'; did you mean to use 'as!' to force downcast?}} {{17-19=as!}}
f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
// <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests
let s : AnyObject = C3()
s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'; did you mean to use 'as!' to force downcast?}} {{3-5=as!}}
| apache-2.0 |
fmscode/DrawView | Example-Swift/Example-Swift/ViewController.swift | 1 | 3171 | //
// ViewController.swift
// Example-Swift
//
// Created by Frank Michael on 12/24/14.
// Copyright (c) 2014 Frank Michael Sanchez. All rights reserved.
//
import UIKit
import AssetsLibrary
class ViewController: UIViewController {
@IBOutlet weak var mainDrawView: DrawView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.mainDrawView.drawingMode = .Signature
// Need to do a refresh since the view has adapted to the current device size.
self.mainDrawView.refreshCanvas()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
self.mainDrawView.refreshCanvas()
}
// MARK: Class Actions
@IBAction func undo(sender: AnyObject) {
self.mainDrawView.undoLastPath()
}
@IBAction func signatureMode(sender: AnyObject) {
if self.mainDrawView.drawingMode == .Signature {
self.mainDrawView.drawingMode = .Default
}else{
self.mainDrawView.drawingMode = .Signature
}
}
@IBAction func saveCanvas(sender: AnyObject) {
let saveAction = UIAlertController(title: "Draw View Saving", message: "", preferredStyle: .ActionSheet)
saveAction.addAction(UIAlertAction(title: "Save to Camera Roll", style: .Default, handler: { (action: UIAlertAction!) -> Void in
let canvasImage = self.mainDrawView.imageRepresentation()
let cameraRoll = ALAssetsLibrary()
cameraRoll.writeImageToSavedPhotosAlbum(canvasImage.CGImage, orientation: .Up, completionBlock: { (assetURL: NSURL!, error: NSError!) -> Void in
NSLog("\(assetURL)")
NSLog("\(error)")
})
}))
saveAction.addAction(UIAlertAction(title: "Save as UIImage", style: .Default, handler: { (action: UIAlertAction!) -> Void in
let canvasImage = self.mainDrawView.imageRepresentation()
NSLog("\(canvasImage)")
}))
saveAction.addAction(UIAlertAction(title: "Save as UIBezierPath", style: .Default, handler: { (action: UIAlertAction!) -> Void in
let canvasPath = self.mainDrawView.bezierPathRepresentation()
NSLog("\(canvasPath)")
}))
saveAction.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(saveAction, animated: true, completion: nil)
}
@IBAction func animate(sender: AnyObject) {
self.mainDrawView.animateCanvas()
}
// For iOS 7 support
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
self.mainDrawView.refreshCanvas()
}
// For iOS 8 support
override func viewDidLayoutSubviews() {
self.mainDrawView.refreshCanvas()
}
}
| mit |
neoneye/SwiftyFORM | Source/Util/DebugViewController.swift | 1 | 2858 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
import WebKit
public enum WhatToShow {
case json(json: Data)
case text(text: String)
case url(url: URL)
}
/// Present various types of data: json, plain text, webpage
///
/// The data is shown in a webview.
///
/// This is only supposed to be used during development,
/// as a quick way to inspect data.
///
/// Usage:
///
/// DebugViewController.showURL(self, url: URL(string: "http://www.google.com")!)
/// DebugViewController.showText(self, text: "hello world")
///
public class DebugViewController: UIViewController {
public let dismissBlock: () -> Void
public let whatToShow: WhatToShow
public init(dismissBlock: @escaping () -> Void, whatToShow: WhatToShow) {
self.dismissBlock = dismissBlock
self.whatToShow = whatToShow
super.init(nibName: nil, bundle: nil)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public class func showJSON(_ parentViewController: UIViewController, jsonData: Data) {
showModally(parentViewController, whatToShow: WhatToShow.json(json: jsonData))
}
public class func showText(_ parentViewController: UIViewController, text: String) {
showModally(parentViewController, whatToShow: WhatToShow.text(text: text))
}
public class func showURL(_ parentViewController: UIViewController, url: URL) {
showModally(parentViewController, whatToShow: WhatToShow.url(url: url))
}
public class func showModally(_ parentViewController: UIViewController, whatToShow: WhatToShow) {
let dismissBlock: () -> Void = { [weak parentViewController] in
parentViewController?.dismiss(animated: true, completion: nil)
}
let vc = DebugViewController(dismissBlock: dismissBlock, whatToShow: whatToShow)
let nc = UINavigationController(rootViewController: vc)
parentViewController.present(nc, animated: true, completion: nil)
}
public override func loadView() {
let webview = WKWebView()
self.view = webview
let item = UIBarButtonItem(title: "Dismiss", style: .plain, target: self, action: #selector(DebugViewController.dismissAction(_:)))
self.navigationItem.leftBarButtonItem = item
switch whatToShow {
case let .json(json):
let url = URL(string: "http://localhost")!
webview.load(json, mimeType: "application/json", characterEncodingName: "utf-8", baseURL: url)
self.title = "JSON"
case let .text(text):
let url = URL(string: "http://localhost")!
let data = (text as NSString).data(using: String.Encoding.utf8.rawValue)!
webview.load(data, mimeType: "text/plain", characterEncodingName: "utf-8", baseURL: url)
self.title = "Text"
case let .url(url):
let request = URLRequest(url: url)
webview.load(request)
self.title = "URL"
}
}
@objc func dismissAction(_ sender: AnyObject?) {
dismissBlock()
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/00900-swift-functiontype-get.swift | 11 | 619 | // 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
func a<h: T> {
protocol b where B : C> U) -> ("])
class A {
return self.dynamicType.<S {
}
protocol C {
let h: b where S(#object1: c(b.R
func compose("\()
}
func f: I.e: b((T>) {
func a<c: ("a)
}
}
A")
protocol b : a {
func a)
| apache-2.0 |
acastano/swift-bootstrap | foundationkit/Unit Tests/iOS/Test Cases/Device/DeviceTests.swift | 1 | 374 | import XCTest
class DeviceTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testExample() {
}
func testPerformanceExample() {
self.measure {
}
}
}
| apache-2.0 |
fgengine/quickly | Quickly/Collection/QCollectionDecor.swift | 1 | 919 | //
// Quickly
//
open class QCollectionDecor< Type: IQCollectionData > : UICollectionReusableView, IQTypedCollectionDecor {
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
self.configure()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
open func setup() {
}
open override func awakeFromNib() {
super.awakeFromNib()
self.configure()
}
public weak var collectionDelegate: IQCollectionDecorDelegate? = nil
public var data: Type? = nil
open class func size(data: Type, layout: UICollectionViewLayout, section: IQCollectionSection, spec: IQContainerSpec) -> CGSize {
return CGSize.zero
}
open func configure() {
}
open func set(data: Type, spec: IQContainerSpec, animated: Bool) {
self.data = data
}
}
| mit |
wikimedia/wikipedia-ios | Wikipedia/Code/LinkOnlyTextView.swift | 1 | 958 | //https://stackoverflow.com/a/47913329
import Foundation
class LinkOnlyTextView: UITextView {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard !UIAccessibility.isVoiceOverRunning else {
return super.point(inside: point, with: event)
}
let glyphIndex = self.layoutManager.glyphIndex(for: point, in: self.textContainer)
// Ensure the glyphIndex actually matches the point and isn't just the closest glyph to the point
let glyphRect = self.layoutManager.boundingRect(forGlyphRange: NSRange(location: glyphIndex, length: 1), in: self.textContainer)
if glyphIndex < self.textStorage.length,
glyphRect.contains(point),
self.textStorage.attribute(NSAttributedString.Key.link, at: glyphIndex, effectiveRange: nil) != nil {
return true
} else {
return false
}
}
}
| mit |
manumax/TinyRobotWars | TinyRobotWars/Core/AST.swift | 1 | 4311 | //
// AST.swift
// TinyRobotWars
//
// Created by Manuele Mion on 21/02/2017.
// Copyright © 2017 manumax. All rights reserved.
//
import Foundation
/**
Grammar:
<statement> ::= <to>
<to> ::= <expr> ('TO' <register>)+
<expr> ::= <term> ((<plus> | <minus>) <expr>)*
<term> ::= <factor> ((<mul> | <div>) <factor>)*
<factor> ::= (<plus> | <minus>) <factor> | <register> | <number>
<number> ::= ([0-9])+
<plus> ::= '+'
<minus> ::= '-'
<mult> ::= '*'
<div> ::= '/'
<register> ::= [A..Z] | 'AIM' | 'SHOOT' | 'RADAR' | 'DAMAGE' | 'SPEEDX' | 'SPEEDY' | 'RANDOM' | 'INDEX'
*/
enum Node {
case number(Int)
case register(String)
indirect case unaryOp(Operator, Node)
indirect case binaryOp(Operator, Node, Node)
indirect case to(Node, [Node])
}
extension Node: Equatable {
static func ==(lhs: Node, rhs: Node) -> Bool {
switch (lhs, rhs) {
case let (.number(l), .number(r)): return l == r
case let (.register(l), .register(r)): return l == r
case let (.unaryOp(lop, lnode), .unaryOp(rop, rnode)):
return lop == rop && lnode == rnode
case let (.binaryOp(lop, llnode, lrnode), .binaryOp(rop, rlnode, rrnode)):
return lop == rop && llnode == rlnode && lrnode == rrnode
case let (.to(lnode, lnodes), .to(rnode, rnodes)):
return lnode == rnode && lnodes == rnodes
default: return false
}
}
}
protocol Visitor {
func visit(_ node: Node)
}
// MARK: - Parser
enum ParserError: Error {
case invalidSyntaxError
case unexpectedTokenError
}
class Parser {
private let lexer: Lexer
private var currentToken: Token?
init(withLexer lexer: Lexer) {
self.lexer = lexer
self.currentToken = lexer.next()
}
func eat() {
self.currentToken = self.lexer.next()
}
func factor() throws -> Node {
// <factor> ::= (<plus> | <minus>) <factor> | <number>
guard let token = self.currentToken else {
throw ParserError.unexpectedTokenError
}
switch token {
case .op(.plus): fallthrough
case .op(.minus):
if case .op(let op) = token {
self.eat()
return .unaryOp(op, try self.factor())
}
throw ParserError.invalidSyntaxError
case .number(let value):
self.eat()
return .number(value)
case .register(let name):
self.eat()
return .register(name)
default:
throw ParserError.unexpectedTokenError
}
}
func term() throws -> Node {
// <term> ::= <factor> ((<mul> | <div>) <factor>)*
let node = try self.factor()
guard let token = self.currentToken, case let Token.op(op) = token else {
return node
}
switch op {
case .times: fallthrough
case .divide:
self.eat()
return .binaryOp(op, node, try self.factor())
default:
return node
}
}
func expr() throws -> Node {
// <expr> ::= <term> ((<plus> | <minus>) <term>)*
let node = try self.term()
guard let token = self.currentToken, case let Token.op(op) = token else {
return node
}
switch op {
case .plus: fallthrough
case .minus:
self.eat()
return .binaryOp(op, node, try self.expr())
default:
return node
}
}
func statement() throws -> Node {
return try to()
}
func to() throws -> Node {
let expr = try self.expr()
var registers = [Node]()
while let token = self.currentToken, case .to = token {
self.eat()
if let token = self.currentToken, case let .register(name) = token {
self.eat()
registers.append(Node.register(name))
} else {
throw ParserError.unexpectedTokenError
}
}
if registers.count == 0 {
return expr
}
return .to(expr, registers)
}
func parse() throws -> Node {
return try self.statement()
}
}
| mit |
saeta/penguin | Sources/PenguinParallel/Parallel/Array+ParallelSequence.swift | 1 | 3434 | // Copyright 2020 Penguin Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
fileprivate func buffer_psum<T: Numeric>(
_ pool: ComputeThreadPool,
_ buff: UnsafeBufferPointer<T>,
_ level: Int
) -> T {
if level == 0 || buff.count < 1000 { // TODO: tune this constant
return buff.reduce(0, +)
}
let middle = buff.count / 2
let lhs = buff[0..<middle]
let rhs = buff[middle..<buff.count]
var lhsSum = T.zero
var rhsSum = T.zero
pool.join(
{ lhsSum = buffer_psum(pool, UnsafeBufferPointer(rebasing: lhs), level - 1) },
{ rhsSum = buffer_psum(pool, UnsafeBufferPointer(rebasing: rhs), level - 1) })
return lhsSum + rhsSum
}
extension Array where Element: Numeric {
/// Computes the sum of all the elements in parallel.
public func pSum() -> Element {
withUnsafeBufferPointer { buff in
let pool = ComputeThreadPools.global
return buffer_psum(
pool, // TODO: Take defaulted-arg & thread local to allow for composition!
buff,
computeRecursiveDepth(procCount: pool.maxParallelism) + 2) // Sub-divide into quarters-per-processor in case of uneven scheduling.
}
}
}
fileprivate func buffer_pmap<T, U>(
pool: ComputeThreadPool,
source: UnsafeBufferPointer<T>,
dest: UnsafeMutableBufferPointer<U>,
mapFunc: (T) -> U
) {
assert(source.count == dest.count)
var threshold = 1000 // TODO: tune this constant
assert(
{
threshold = 10
return true
}(), "Hacky workaround for no #if OPT.")
if source.count < threshold {
for i in 0..<source.count {
dest[i] = mapFunc(source[i])
}
return
}
let middle = source.count / 2
let srcLower = source[0..<middle]
let dstLower = dest[0..<middle]
let srcUpper = source[middle..<source.count]
let dstUpper = dest[middle..<source.count]
pool.join(
{
buffer_pmap(
pool: pool,
source: UnsafeBufferPointer(rebasing: srcLower),
dest: UnsafeMutableBufferPointer(rebasing: dstLower),
mapFunc: mapFunc)
},
{
buffer_pmap(
pool: pool,
source: UnsafeBufferPointer(rebasing: srcUpper),
dest: UnsafeMutableBufferPointer(rebasing: dstUpper),
mapFunc: mapFunc)
})
}
extension Array {
/// Makes a new array, where every element in the new array is `f(self[i])` for all `i` in `0..<count`.
///
/// Note: this function applies `f` in parallel across all available threads on the local machine.
public func pMap<T>(_ f: (Element) -> T) -> [T] {
// TODO: support throwing.
withUnsafeBufferPointer { selfBuffer in
[T](unsafeUninitializedCapacity: count) { destBuffer, cnt in
cnt = count
buffer_pmap(
pool: ComputeThreadPools.global, // TODO: Take a defaulted-arg / pull from threadlocal for better composition!
source: selfBuffer,
dest: destBuffer,
mapFunc: f
)
}
}
}
}
| apache-2.0 |
dduan/swift | test/SourceKit/CodeComplete/complete_sort_order.swift | 1 | 4364 | func foo(a a: String) {}
func foo(a a: Int) {}
func foo(b b: Int) {}
func test() {
let x = 1
}
// RUN: %sourcekitd-test -req=complete -req-opts=hidelowpriority=0 -pos=7:1 %s -- %s > %t.orig
// RUN: FileCheck -check-prefix=NAME %s < %t.orig
// Make sure the order is as below, foo(Int) should come before foo(String).
// NAME: key.description: "#column"
// NAME: key.description: "AbsoluteValuable"
// NAME: key.description: "foo(a: Int)"
// NAME-NOT: key.description
// NAME: key.description: "foo(a: String)"
// NAME-NOT: key.description
// NAME: key.description: "foo(b: Int)"
// NAME: key.description: "test()"
// NAME: key.description: "x"
// RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=hidelowpriority=0,hideunderscores=0 %s -- %s > %t.default
// RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=0,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.on
// RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=1,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.off
// RUN: FileCheck -check-prefix=CONTEXT %s < %t.default
// RUN: FileCheck -check-prefix=NAME %s < %t.off
// FIXME: rdar://problem/20109989 non-deterministic sort order
// RUN-disabled: diff %t.on %t.default
// RUN: FileCheck -check-prefix=CONTEXT %s < %t.on
// CONTEXT: key.kind: source.lang.swift.decl
// CONTEXT-NEXT: key.name: "x"
// CONTEXT-NOT: key.name:
// CONTEXT: key.name: "foo(a:)"
// CONTEXT-NOT: key.name:
// CONTEXT: key.name: "foo(a:)"
// CONTEXT-NOT: key.name:
// CONTEXT: key.name: "foo(b:)"
// CONTEXT-NOT: key.name:
// CONTEXT: key.name: "test()"
// CONTEXT: key.name: "#column"
// CONTEXT: key.name: "AbsoluteValuable"
// RUN: %complete-test -tok=STMT_0 %s | FileCheck %s -check-prefix=STMT
func test1() {
#^STMT_0^#
}
// STMT: let
// STMT: var
// STMT: if
// STMT: for
// STMT: while
// STMT: func
// STMT: foo(a: Int)
// RUN: %complete-test -tok=STMT_1 %s | FileCheck %s -check-prefix=STMT_1
func test5() {
var retLocal: Int
#^STMT_1,r,ret,retur,return^#
}
// STMT_1-LABEL: Results for filterText: r [
// STMT_1-NEXT: retLocal
// STMT_1-NEXT: repeat
// STMT_1-NEXT: return
// STMT_1-NEXT: required
// STMT_1: ]
// STMT_1-LABEL: Results for filterText: ret [
// STMT_1-NEXT: retLocal
// STMT_1-NEXT: return
// STMT_1-NEXT: repeat
// STMT_1: ]
// STMT_1-LABEL: Results for filterText: retur [
// STMT_1-NEXT: return
// STMT_1: ]
// STMT_1-LABEL: Results for filterText: return [
// STMT_1-NEXT: return
// STMT_1: ]
// RUN: %complete-test -top=0 -tok=EXPR_0 %s | FileCheck %s -check-prefix=EXPR
func test2() {
(#^EXPR_0^#)
}
// EXPR: 0
// EXPR: "abc"
// EXPR: true
// EXPR: false
// EXPR: [#Color(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)#]
// EXPR: [#Image(imageLiteral: String)#]
// EXPR: [values]
// EXPR: [key: value]
// EXPR: (values)
// EXPR: nil
// EXPR: foo(a: Int)
// Top 1
// RUN: %complete-test -top=1 -tok=EXPR_1 %s | FileCheck %s -check-prefix=EXPR_TOP_1
func test3(x: Int) {
let y = x
let z = x
let zzz = x
(#^EXPR_1^#)
}
// EXPR_TOP_1: x
// EXPR_TOP_1: 0
// EXPR_TOP_1: "abc"
// EXPR_TOP_1: true
// EXPR_TOP_1: false
// EXPR_TOP_1: [#Color(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)#]
// EXPR_TOP_1: [#Image(imageLiteral: String)#]
// EXPR_TOP_1: [values]
// EXPR_TOP_1: [key: value]
// EXPR_TOP_1: (values)
// EXPR_TOP_1: nil
// EXPR_TOP_1: y
// EXPR_TOP_1: z
// EXPR_TOP_1: zzz
// Top 3
// RUN: %complete-test -top=3 -tok=EXPR_2 %s | FileCheck %s -check-prefix=EXPR_TOP_3
func test4(x: Int) {
let y = x
let z = x
let zzz = x
(#^EXPR_2^#)
}
// EXPR_TOP_3: x
// EXPR_TOP_3: y
// EXPR_TOP_3: z
// EXPR_TOP_3: 0
// EXPR_TOP_3: "abc"
// EXPR_TOP_3: true
// EXPR_TOP_3: false
// EXPR_TOP_3: [#Color(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)#]
// EXPR_TOP_3: [#Image(imageLiteral: String)#]
// EXPR_TOP_3: [values]
// EXPR_TOP_3: [key: value]
// EXPR_TOP_3: (values)
// EXPR_TOP_3: nil
// EXPR_TOP_3: zzz
// Top 3 with type matching
// RUN: %complete-test -top=3 -tok=EXPR_3 %s | FileCheck %s -check-prefix=EXPR_TOP_3_TYPE_MATCH
func test4(x: Int) {
let y: String = ""
let z: String = y
let zzz = x
let bar: Int = #^EXPR_3^#
}
// EXPR_TOP_3_TYPE_MATCH: x
// EXPR_TOP_3_TYPE_MATCH: zzz
// EXPR_TOP_3_TYPE_MATCH: 0
// EXPR_TOP_3_TYPE_MATCH: y
// EXPR_TOP_3_TYPE_MATCH: z
| apache-2.0 |
nProdanov/FuelCalculator | Fuel economy smart calc./Fuel economy smart calc./FireBaseGasStationData.swift | 1 | 2049 | //
// FireBaseGasStationData.swift
// Fuel economy smart calc.
//
// Created by Nikolay Prodanow on 3/27/17.
// Copyright © 2017 Nikolay Prodanow. All rights reserved.
//
import Foundation
import Firebase
import FirebaseDatabase
class FireBaseGasStationData: BaseRemoteGasStationData
{
private var delegate: RemoteGasStationDataDelegate?
private var dbReference: FIRDatabaseReference!
init(){
if FIRApp.defaultApp() == nil {
FIRApp.configure()
}
dbReference = FIRDatabase.database().reference()
}
func getAll() {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.dbReference
.child(Constants.GasStationDbChild)
.observeSingleEvent(of: .value, with: {(snapshop) in
let gasStationsDict = snapshop.value as! [NSDictionary]
let gasStations = gasStationsDict.map { GasStation.fromDict($0) }
DispatchQueue.main.async {
self?.delegate?.didReceiveRemoteGasStations(gasStations)
}
}) {error in
self?.delegate?.didReceiveRemoteError(error: error)
}
}
}
func getAllCount() {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.dbReference
.child(Constants.GasStationDbChild)
.observeSingleEvent(of: .value, with: {(snapshop) in
DispatchQueue.main.async {
self?.delegate?.didReceiveRemoteGasStationsCount((snapshop.value as! [Any]).count)
}
}) {error in
self?.delegate?.didReceiveRemoteError(error: error)
}
}
}
func setDelegate(_ delegate: RemoteGasStationDataDelegate) {
self.delegate = delegate
}
private struct Constants {
static let GasStationDbChild = "gasStations"
}
}
| mit |
sunlijian/sinaBlog_repository | sinaBlog_sunlijian/sinaBlog_sunlijianTests/sinaBlog_sunlijianTests.swift | 1 | 1017 | //
// sinaBlog_sunlijianTests.swift
// sinaBlog_sunlijianTests
//
// Created by sunlijian on 15/10/9.
// Copyright © 2015年 myCompany. All rights reserved.
//
import XCTest
@testable import sinaBlog_sunlijian
class sinaBlog_sunlijianTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
jtbandes/swift | test/Parse/ConditionalCompilation/can_import.swift | 19 | 2262 | // RUN: %target-typecheck-verify-swift -parse-as-library
// RUN: %target-typecheck-verify-swift -D WITH_PERFORM -primary-file %s %S/Inputs/can_import_nonprimary_file.swift
// REQUIRES: can_import
public struct LibraryDependentBool : ExpressibleByBooleanLiteral {
#if canImport(Swift)
var _description: String
#endif
public let magicConstant: Int = {
#if canImport(Swift)
return 42
#else
return "" // Type error
#endif
}()
#if canImport(AppKit) || (canImport(UIKit) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
#if canImport(Swift)
self._description = "\(value)"
#endif
}
public init(_ value: Bool) {
#if canImport(Swift)
self._description = value ? "YES" : "NO"
#endif
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value: Bool
public init(_ value: Bool) {
#if canImport(Swift)
self._description = value ? "YES" : "NO"
#endif
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if canImport(AppKit) || (canImport(UIKit) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
public init(booleanLiteral value: Bool) {
self.init(value)
}
func withBoolValue(_ f : (Bool) -> ()) {
return f(self.boolValue)
}
}
#if canImport(Swift)
func topLevelFunction() {
LibraryDependentBool(true).withBoolValue { b in
let value: String
#if canImport(Swiftz)
#if canImport(ReactiveCocoa)
#if canImport(Darwin)
value = NSObject() // Type error
#endif
#endif
#else
value = ""
#endif
print(value)
}
}
#else
enum LibraryDependentBool {} // This should not happen
#endif
#if WITH_PERFORM
func performPerOS() -> Int {
let value: Int
#if canImport(Argo)
value = "" // Type error
#else
value = 42
#endif
return performFoo(withX: value, andY: value)
}
#endif
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
| apache-2.0 |
AgaKhanFoundation/WCF-iOS | Steps4Impact/Protocols/PedometerDataProvider.swift | 1 | 2255 | /**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import Foundation
enum PedometerDataProviderError: Error {
case quantityType
case resultsNotPresent
case sharingDenied
case sharingNotAuthorized
case unknown
}
struct PedometerData {
let date: Date
let count: Double
}
extension Array where Element == PedometerData {
var indexOfToday: Int? {
firstIndex { $0.date.endOfDay == Date().endOfDay }
}
}
typealias PedometerDataCompletion = (Result<[PedometerData], PedometerDataProviderError>) -> Void
protocol PedometerDataProvider {
typealias Error = PedometerDataProviderError
func retrieveStepCount(forInterval interval: DateInterval, _ completion: @escaping PedometerDataCompletion)
func retrieveDistance(forInterval interval: DateInterval, _ completion: @escaping PedometerDataCompletion)
}
| bsd-3-clause |
lstn-ltd/lstn-sdk-ios | Example/Tests/Article/MockArticleResolver.swift | 1 | 1208 | //
// MockArticleResolver.swift
// Lstn
//
// Created by Dan Halliday on 10/11/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
@testable import Lstn
class SucceedingArticleResolver: ArticleResolver {
weak var delegate: ArticleResolverDelegate? = nil
var workingPopSoundPath: String {
return Bundle(for: type(of: self)).path(forResource: "Pop", ofType: "m4a")!
}
func resolve(key: ArticleKey) {
let article = Article(
key: key,
source: URL(string: "https://example.com/article.html")!,
audio: URL(fileURLWithPath: self.workingPopSoundPath),
image: URL(string: "https://example.com/image.jpg")!,
title: "Title",
author: "Author",
publisher: "Publisher"
)
self.delegate?.resolutionDidStart(key: key)
self.delegate?.resolutionDidFinish(key: key, article: article)
}
}
class FailingArticleResolver: ArticleResolver {
weak var delegate: ArticleResolverDelegate? = nil
func resolve(key: ArticleKey) {
self.delegate?.resolutionDidStart(key: key)
self.delegate?.resolutionDidFail(key: key)
}
}
| mit |
gaowanli/PinGo | PinGo/PinGo/Other/Tool/DHButton.swift | 1 | 367 | //
// DHButton.swift
// PinGo
//
// Created by GaoWanli on 16/1/31.
// Copyright © 2016年 GWL. All rights reserved.
//
import UIKit
/// 取消高亮的button
class DHButton: UIButton {
override var isHighlighted: Bool {
get {
return super.isHighlighted
}
set {
super.isHighlighted = false
}
}
}
| mit |
Josscii/iOS-Demos | TableViewIssueDemo/TableViewDemo/update/ViewController2.swift | 1 | 3325 | //
// ViewController2.swift
// TableViewDemo
//
// Created by josscii on 2018/2/7.
// Copyright © 2018年 josscii. All rights reserved.
//
import UIKit
/*
测试 beginUpdates / endUpdates 和 tableView reload/delete/insert 的关系
*/
class ViewController2: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
// tableView.rowHeight = 100
tableView.estimatedRowHeight = 44
}
var text = "诚然,有不少人表示 Universal Clipboard 用起来很顺畅、没有遇到问题"
var more = false
var num = 2
@IBAction func change(_ sender: Any) {
more = !more
if more {
text = "诚然,有不少人表示 Universal Clipboard 用起来很顺畅、没有遇到问题,但也有一批人因为这个功能,系统出现了这样那样的问题,甚至影响到了正常的使用。当一个功能到了影响效率的时候,就有必要想解决办法了"
} else {
text = "诚然,有不少人表示 Universal Clipboard 用起来很顺畅、没有遇到问题"
}
// tableView.beginUpdates()
// tableView.reloadRows(at: [IndexPath.init(row: 0, section: 0), IndexPath.init(row: 1, section: 0)], with: .automatic)
// tableView.endUpdates()
// UIView.performWithoutAnimation {
// tableView.reloadRows(at: [IndexPath.init(row: 0, section: 0), IndexPath.init(row: 1, section: 0)], with: .automatic)
// }
// UIView.setAnimationsEnabled(false)
// tableView.reloadRows(at: [IndexPath.init(row: 0, section: 0), IndexPath.init(row: 1, section: 0)], with: .automatic)
// UIView.setAnimationsEnabled(true)
// tableView.reloadData()
/** 对数据进行重新赋值的时候必须 dispatch 到主线程去做,因为这时候可能有其他操作 */
DispatchQueue.main.async {
self.num = 1
self.tableView.reloadData()
}
// tableView.reloadData()
tableView.beginUpdates()
// tableView.insertRows(at: [IndexPath.init(row: 1, section: 0)], with: .automatic)
// tableView.deleteRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
tableView.endUpdates()
/*
beginUpdates 和 endUpdates 和 tableView 的动画无关,只是用于将对 tableView 的批量修改 patch
*/
}
}
extension ViewController2: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return num
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.titleLabel.text = text
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
| mit |
WzhGoSky/ZHPlayer | ZHPlayer/ZHPlayer/ZHPlayer/ZHPlayerOperationView.swift | 1 | 8684 | //
// ZHPlayerOperationView.swift
// ZHPlayer
//
// Created by Hayder on 2017/1/3.
// Copyright © 2017年 Hayder. All rights reserved.
// 视屏播放时操作的View
import UIKit
typealias sliderProgressChangedCallBack = (_ sliderProgress: TimeInterval)->()
enum screenType{
case fullScreen
case smallScreen
}
class ZHPlayerOperationView: UIView {
//滑块是否在拖动
var isSlider: Bool = false
//是否隐藏topBar bottomBar 默认暂时不隐藏
var ishiddenOperationBar: Bool = true
//是否在滑动
var sliderChanged: sliderProgressChangedCallBack?
//目前屏幕状态 是small 还是fullScreen
var screenType: screenType = .smallScreen
//定时器
fileprivate var timer: Timer?
//上面的bar
@IBOutlet weak var topBar: UIView!
//底部的bar
@IBOutlet weak var bottomBar: UIView!
//用来点击的View
@IBOutlet weak var tapView: UIView!
//播放
@IBOutlet weak var play: UIButton!
//缩放(旋转)
@IBOutlet weak var rotation: UIButton!
//当前时间
@IBOutlet weak var currentTime: UILabel!
//总时间
@IBOutlet weak var totalTime: UILabel!
//缓冲进度
@IBOutlet weak var loadedProgress: UIProgressView!
//播放进度
@IBOutlet weak var playProgress: UISlider!
//父控件
fileprivate var superView: ZHPlayerView?{
guard let view = self.superview else {
return nil
}
return view as? ZHPlayerView
}
//MARK:- 创建操作视图
class func operationView() -> ZHPlayerOperationView{
return Bundle.main.loadNibNamed("ZHPlayerOperationView", owner: self, options: nil)?.first as! ZHPlayerOperationView
}
//1.正在拖动
@IBAction func dragging(_ sender: UISlider) {
isSlider = true
if sliderChanged != nil {
sliderChanged!(TimeInterval(sender.value))
}
}
//2.手指按下
@IBAction func touchDown(_ sender: UISlider) {
superView?.Pause()
}
//3.手指抬起
@IBAction func touchUp(_ sender: UISlider) {
superView?.Play()
isSlider = false
}
//暂停或开始
@IBAction func playorPause(_ sender: UIButton) {
play.isSelected = !play.isSelected
if play.isSelected == true {
superView?.Play()
}else
{
superView?.Pause()
}
}
//旋转屏幕
@IBAction func rotateScreen(_ sender: UIButton) {
guard let superView = superView else {
return
}
if screenType == .smallScreen {
let height = UIScreen.main.bounds.width
let width = UIScreen.main.bounds.height
let frame = CGRect(x: (height - width)/2, y: (width - height)/2, width: width, height: height)
//全屏状态
screenType = .fullScreen
UIView.animate(withDuration: 0.3, animations: {
superView.frame = frame
superView.transform = CGAffineTransform(rotationAngle: (CGFloat)(M_PI_2))
})
rotation.isSelected = true
UIApplication.shared.keyWindow?.addSubview(superView)
}else
{
let orientation = UIDevice.current.orientation
if orientation == .portrait
{
//全屏状态
UIView.animate(withDuration: 0.3, animations: {
superView.transform = CGAffineTransform.identity
superView.frame = superView.originalFrame
})
screenType = .smallScreen
superView.originalSuperView?.addSubview(superView)
}
rotation.isSelected = false
}
}
deinit {
removeTimer()
NotificationCenter.default.removeObserver(self)
}
}
//MARK:- operationBar的操作
extension ZHPlayerOperationView{
override func awakeFromNib() {
super.awakeFromNib()
//1.重新设置下slider的thumb图片
self.playProgress.setThumbImage(UIImage(named:"icmpv_thumb_light"), for: .normal)
self.playProgress.setThumbImage(UIImage(named:"icmpv_thumb_light"), for: .highlighted)
//2.给tapview添加一个手势
//添加手势
let tap = UITapGestureRecognizer(target: self, action: #selector(tap(tap:)))
tapView.addGestureRecognizer(tap)
//3.添加通知
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged(noti:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
@objc fileprivate func tap(tap: UITapGestureRecognizer)
{
//保险起见,添加定时器的之前先移除定时器
removeTimer()
//添加定时器
addTimer()
handleBar()
}
//操作handleBar
fileprivate func handleBar(){
if ishiddenOperationBar == true {
UIView.animate(withDuration: 0.25, animations: {
self.topBar.transform = CGAffineTransform(translationX: 0, y: -40)
self.bottomBar.transform = CGAffineTransform(translationX: 0, y: 40)
})
}else
{
UIView.animate(withDuration: 0.25, animations: {
self.topBar.transform = CGAffineTransform.identity
self.bottomBar.transform = CGAffineTransform.identity
})
}
//操作以后改变标志位的状态
ishiddenOperationBar = !ishiddenOperationBar
}
}
//MARK:- 对定时器的操作方法
extension ZHPlayerOperationView{
///创建定时器的方法
func addTimer(){
timer = Timer(timeInterval: 6.0, target: self, selector: #selector(hiddenOperationBar), userInfo: nil, repeats: false)
RunLoop.main.add(timer!, forMode: .commonModes)
}
func removeTimer(){
timer?.invalidate() //从运行循环中移除
timer = nil
}
//隐藏操作的bar
@objc private func hiddenOperationBar(){
handleBar()
//操作完以后移除定时器
removeTimer()
}
}
//MARK:- 屏幕旋转
extension ZHPlayerOperationView{
@objc fileprivate func orientationChanged(noti: NSNotification){
//1.获取屏幕现在的方向
let orientation = UIDevice.current.orientation
switch orientation {
case .portrait:
guard let superView = superView else {
return
}
if screenType == .fullScreen {
screenType = .smallScreen
rotation.isSelected = false
superView.transform = CGAffineTransform.identity
superView.frame = superView.originalFrame
}
case .landscapeLeft:
if screenType == .smallScreen
{
screenType = .fullScreen
rotation.isSelected = true
}
fullScreenWithOrientation(orientation: orientation)
case .landscapeRight:
if screenType == .smallScreen
{
screenType = .fullScreen
rotation.isSelected = true
}
fullScreenWithOrientation(orientation: orientation)
default: break
}
}
private func fullScreenWithOrientation(orientation: UIDeviceOrientation)
{
guard let superView = superView else {
return
}
superView.removeFromSuperview()
superView.transform = CGAffineTransform.identity
let height = UIScreen.main.bounds.height
let width = UIScreen.main.bounds.width
superView.frame = CGRect(x: 0, y: 0, width: width, height: height)
UIApplication.shared.keyWindow?.addSubview(superView)
}
}
| mit |
stevebrambilla/autolayout-expressions | Sources/LayoutExpressions/Extensions/UIKit/tvOS/AVContentProposalViewController+Anchors.swift | 2 | 372 | // Copyright © 2019 Steve Brambilla. All rights reserved.
#if os(tvOS)
import AVKit
@available(tvOS 10.0, *)
extension Anchors where Base: AVContentProposalViewController {
/// A layout area representing the view controller's `playerLayoutGuide`.
public var player: LayoutAreaAnchors {
LayoutAreaAnchors(guide: base.playerLayoutGuide)
}
}
#endif
| mit |
Incipia/Elemental | Elemental/Classes/CustomUI/InsetTextField.swift | 1 | 812 | //
// InsetTextField.swift
// Elemental
//
// Created by Gregory Klein on 2/13/17.
// Copyright © 2017 Incipia. All rights reserved.
//
import UIKit
class InsetTextField: UITextField {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
_commonInit()
}
convenience init() {
self.init(frame: .zero)
_commonInit()
}
private func _commonInit() {
backgroundColor = UIColor.gray.withAlphaComponent(0.1)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 14, dy: 0)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 14, dy: 0)
}
}
| mit |
ministrycentered/onepassword-app-extension | Demos/App Demo for iOS Swift/App Demo for iOS Swift/RegisterViewController.swift | 2 | 3727 | //
// RegisterViewController.swift
// App Demo for iOS Swift
//
// Created by Rad Azzouz on 2015-05-14.
// Copyright (c) 2015 Agilebits. All rights reserved.
//
import Foundation
class RegisterViewController: UIViewController {
@IBOutlet weak var onepasswordButton: UIButton!
@IBOutlet weak var firstnameTextField: UITextField!
@IBOutlet weak var lastnameTextField: UITextField!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
if let patternImage = UIImage(named: "register-background.png") {
self.view.backgroundColor = UIColor(patternImage: patternImage)
}
onepasswordButton.isHidden = (false == OnePasswordExtension.shared().isAppExtensionAvailable())
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.default
}
@IBAction func saveLoginTo1Password(_ sender:AnyObject) {
let newLoginDetails:[String: Any] = [
AppExtensionTitleKey: "ACME",
AppExtensionUsernameKey: usernameTextField.text ?? "",
AppExtensionPasswordKey: passwordTextField.text ?? "",
AppExtensionNotesKey: "Saved with the ACME app",
AppExtensionSectionTitleKey: "ACME Browser",
AppExtensionFieldsKey: [
"firstname" : firstnameTextField.text ?? "",
"lastname" : lastnameTextField.text ?? ""
// Add as many string fields as you please.
]
]
// The password generation options are optional, but are very handy in case you have strict rules about password lengths, symbols and digits.
let passwordGenerationOptions:[String: AnyObject] = [
// The minimum password length can be 4 or more.
AppExtensionGeneratedPasswordMinLengthKey: (8 as NSNumber),
// The maximum password length can be 50 or less.
AppExtensionGeneratedPasswordMaxLengthKey: (30 as NSNumber),
// If YES, the 1Password will guarantee that the generated password will contain at least one digit (number between 0 and 9). Passing NO will not exclude digits from the generated password.
AppExtensionGeneratedPasswordRequireDigitsKey: (true as NSNumber),
// If YES, the 1Password will guarantee that the generated password will contain at least one symbol (See the list below). Passing NO will not exclude symbols from the generated password.
AppExtensionGeneratedPasswordRequireSymbolsKey: (true as NSNumber),
// Here are all the symbols available in the the 1Password Password Generator:
// !@#$%^&*()_-+=|[]{}'\";.,>?/~`
// The string for AppExtensionGeneratedPasswordForbiddenCharactersKey should contain the symbols and characters that you wish 1Password to exclude from the generated password.
AppExtensionGeneratedPasswordForbiddenCharactersKey: "!@#$%/0lIO" as NSString
]
OnePasswordExtension.shared().storeLogin(forURLString: "https://www.acme.com", loginDetails: newLoginDetails, passwordGenerationOptions: passwordGenerationOptions, for: self, sender: sender) { (loginDictionary, error) in
guard let loginDictionary = loginDictionary else {
if let error = error as NSError?, error.code != AppExtensionErrorCode.cancelledByUser.rawValue {
print("Error invoking 1Password App Extension for find login: \(String(describing: error))")
}
return
}
self.usernameTextField.text = loginDictionary[AppExtensionUsernameKey] as? String
self.passwordTextField.text = loginDictionary[AppExtensionPasswordKey] as? String
if let returnedLoginDictionary = loginDictionary[AppExtensionReturnedFieldsKey] as? [String: Any] {
self.firstnameTextField.text = returnedLoginDictionary["firstname"] as? String
self.lastnameTextField.text = returnedLoginDictionary["lastname"] as? String
}
}
}
}
| mit |
Ning-Wang/Come-On | v2exProject/v2exProject/Controller/HotViewController.swift | 1 | 3158 | //
// HotViewController.swift
// v2exProject
//
// Created by 郑建文 on 16/8/4.
// Copyright © 2016年 Zheng. All rights reserved.
//
import UIKit
// 协议名要放在父类名的后面,用 , 隔开
class HotViewController: UIViewController,UITableViewDataSource {
//加标签
// MARK: TEST
//通过闭包创建UI控件
let tableView:UITableView = {
let table:UITableView = UITableView(frame: CGRectMake(0, 0, 200, 600), style: UITableViewStyle.Plain)
// swift 中通过 类型名.self 来返回类型名
table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
table.registerNib(UINib(nibName: "HotCell", bundle: nil), forCellReuseIdentifier:"hotcell")
return table
}()
//计算属性
var frame:CGRect{
get{
return self.view.bounds
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.frame = frame
//设置tableview 的行高是自动计算的
// 使用这个方法的话就不需要再 tableview的返回高度的回调方法了
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
//注册可视化的cell
view.addSubview(tableView)
//发起网络请求
//网络请求管理实例
let manager = NetworkManager.sharedManager
//利用网络请求实例来发起网络请求 //下面方法分两步1.先执行fetch方法 2。解析成功执行success 下面是success的实现(回调)
manager.fetchTopics(success: {
//网络请求成功后就执行这行代码
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NetworkManager.sharedManager.topics.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//查找复用的cell
let cell = tableView.dequeueReusableCellWithIdentifier("hotcell", forIndexPath: indexPath) as? HotCell //为了防止写错关键字所以用?
// as? 强转返回的是一个可选类型
let topic = NetworkManager.sharedManager.topics[indexPath.row]
cell!.topic = topic
return cell! //这个代理方法需要的返回值是UITableViewCell所以需要强转
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
tattn/HackathonStarter | HackathonStarter/Application/Appearance.swift | 1 | 1110 | //
// Appearance.swift
// HackathonStarter
//
// Created by Tatsuya Tanaka on 20170529.
// Copyright © 2017年 tattn. All rights reserved.
//
import Foundation
import UIKit
struct Appearance {
static func setup() {
// Icon color of NavigationBar
UINavigationBar.appearance().tintColor = .main
// Text color of NavigationBar
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.main]
// Text color (UIButton & UIAlertView & ...)
UIView.appearance().tintColor = .main
}
}
extension UIColor {
static var main: UIColor { return .red }
}
extension UIFont {
static func main(ofSize size: CGFloat) -> UIFont {
return .hiraKakuW6(ofSize: size)
}
static func hiraKakuW6(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "HiraKakuProN-W6", size: size) ?? .systemFont(ofSize: size)
}
static func hiraKakuW3(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "HiraKakuProN-W3", size: size) ?? .systemFont(ofSize: size)
}
}
| mit |
philipgreat/b2b-swift-app | B2BSimpleApp/B2BSimpleApp/BillingAddressRemoteManagerImpl.swift | 1 | 2397 | //Domain B2B/BillingAddress/
import SwiftyJSON
import Alamofire
import ObjectMapper
class BillingAddressRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{
override init(){
//lazy load for all the properties
//This is good for UI applications as it might saves RAM which is very expensive in mobile devices
}
override var remoteURLPrefix:String{
//Every manager need to config their own URL
return "https://philipgreat.github.io/naf/billingAddressManager/"
}
func loadBillingAddressDetail(billingAddressId:String,
billingAddressSuccessAction: (BillingAddress)->String,
billingAddressErrorAction: (String)->String){
let methodName = "loadBillingAddressDetail"
let parameters = [billingAddressId]
let url = compositeCallURL(methodName, parameters: parameters)
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
if let billingAddress = self.extractBillingAddressFromJSON(json){
billingAddressSuccessAction(billingAddress)
}
}
case .Failure(let error):
print(error)
billingAddressErrorAction("\(error)")
}
}
}
func extractBillingAddressFromJSON(json:JSON) -> BillingAddress?{
let jsonTool = SwiftyJSONTool()
let billingAddress = jsonTool.extractBillingAddress(json)
return billingAddress
}
//Confirming to the protocol CustomStringConvertible of Foundation
var description: String{
//Need to find out a way to improve this method performance as this method might called to
//debug or log, using + is faster than \(var).
let result = "BillingAddressRemoteManagerImpl, V1"
return result
}
static var CLASS_VERSION = 1
//This value is for serializer like message pack to identify the versions match between
//local and remote object.
}
//Reference http://grokswift.com/simple-rest-with-swift/
//Reference https://github.com/SwiftyJSON/SwiftyJSON
//Reference https://github.com/Alamofire/Alamofire
//Reference https://github.com/Hearst-DD/ObjectMapper
//let remote = RemoteManagerImpl()
//let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"])
//print(result)
| mit |
SakuragiTen/DYTV | DYTV/DYTV/Classes/Main/Models/AnchorModel.swift | 1 | 891 | //
// AnchorModel.swift
// testCocopods
//
// Created by gongsheng on 2017/1/9.
// Copyright © 2017年 com.gongsheng. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
//房间ID
var room_id : Int = 0
//房间图片对应的URLString
var vertical_src : String = ""
//判断是手机直播还是电脑直播
//0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间)
var isVertical : Int = 0
///房间名称
var room_name : String = ""
///主播昵称
var nickname : String = ""
///观看人数
var online : Int = 0
//所在城市
var anchor_city : String = ""
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit |
benlangmuir/swift | test/Generics/sr12531.swift | 4 | 1276 | // RUN: %target-typecheck-verify-swift
// https://github.com/apple/swift/issues/54974
protocol AnyPropertyProtocol {
associatedtype Root = Any
associatedtype Value = Any
associatedtype KP: AnyKeyPath
var key: KP { get }
var value: Value { get }
}
// CHECK-LABEL: .PartialPropertyProtocol@
// CHECK-NEXT: Requirement signature: <Self where Self : AnyPropertyProtocol, Self.[AnyPropertyProtocol]KP : PartialKeyPath<Self.[AnyPropertyProtocol]Root>
protocol PartialPropertyProtocol: AnyPropertyProtocol
where KP: PartialKeyPath<Root> {
}
// CHECK-LABEL: .PropertyProtocol@
// CHECK-NEXT: Requirement signature: <Self where Self : PartialPropertyProtocol, Self.[AnyPropertyProtocol]KP : WritableKeyPath<Self.[AnyPropertyProtocol]Root, Self.[AnyPropertyProtocol]Value>
protocol PropertyProtocol: PartialPropertyProtocol
where KP: WritableKeyPath<Root, Value> {
}
extension Dictionary where Value: AnyPropertyProtocol {
// CHECK-LABEL: .subscript@
// CHECK-NEXT: Generic signature: <R, V, P where P : PropertyProtocol, P.[AnyPropertyProtocol]Root == R, P.[AnyPropertyProtocol]Value == V>
subscript<R, V, P>(key: Key, path: WritableKeyPath<R, V>) -> P? where P: PropertyProtocol, P.Root == R, P.Value == V {
return self[key] as? P
}
}
| apache-2.0 |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/StartUI/StartUI/SearchGroupSelector.swift | 1 | 1985 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
final class SearchGroupSelector: UIView, TabBarDelegate {
var onGroupSelected: ((SearchGroup) -> Void)?
var group: SearchGroup = .people {
didSet {
onGroupSelected?(group)
}
}
// MARK: - Views
private let tabBar: TabBar
private let groups: [SearchGroup]
// MARK: - Initialization
init() {
groups = SearchGroup.all
let groupItems: [UITabBarItem] = groups.enumerated().map { index, group in
UITabBarItem(title: group.name.localizedUppercase, image: nil, tag: index)
}
tabBar = TabBar(items: groupItems, selectedIndex: 0)
super.init(frame: .zero)
configureViews()
configureConstraints()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureViews() {
tabBar.delegate = self
backgroundColor = SemanticColors.View.backgroundDefault
addSubview(tabBar)
}
private func configureConstraints() {
tabBar.fitIn(view: self)
}
// MARK: - Tab Bar Delegate
func tabBar(_ tabBar: TabBar, didSelectItemAt index: Int) {
group = groups[index]
}
}
| gpl-3.0 |
gregomni/swift | test/SILOptimizer/array_contentof_opt.swift | 3 | 2922 | // RUN: %target-swift-frontend -O -sil-verify-all -emit-sil -Xllvm '-sil-inline-never-functions=$sSa6appendyy' -Xllvm -sil-inline-never-function='$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5' %s | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib
// This is an end-to-end test of the Array.append(contentsOf:) ->
// Array.append(Element) optimization.
//
// To check that the optimization produces the expected
// Array.append(Element) calls, the CHECK lines match those call
// sites. The optimizer may subsequently inline Array.append(Element),
// which is good, but to keep the test simple and specific to the
// optimization, the RUN line prevents inlining Array.append(Element).
// Likewise, negative tests check for the existence of
// Array.append(contentsOf:), so don't inline those either.
// CHECK-LABEL: sil @{{.*}}testInt
// CHECK-NOT: apply
// CHECK: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5
// CHECK-NOT: apply
// CHECK: apply [[F]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
public func testInt(_ a: inout [Int]) {
a += [1]
}
// CHECK-LABEL: sil @{{.*}}testThreeInts
// CHECK-DAG: [[FR:%[0-9]+]] = function_ref @${{.*(reserveCapacity|_createNewBuffer)}}
// CHECK-DAG: apply [[FR]]
// CHECK-DAG: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5
// CHECK-DAG: apply [[F]]
// CHECK-DAG: apply [[F]]
// CHECK-DAG: apply [[F]]
// CHECK: } // end sil function '{{.*}}testThreeInts{{.*}}'
public func testThreeInts(_ a: inout [Int]) {
a += [1, 2, 3]
}
// CHECK-LABEL: sil @{{.*}}testTooManyInts
// CHECK-NOT: apply
// CHECK: [[F:%[0-9]+]] = function_ref @${{.*append.*contentsOf.*}}
// CHECK-NOT: apply
// CHECK: apply [[F]]
// CHECK-NOT: apply
// CHECK: return
public func testTooManyInts(_ a: inout [Int]) {
a += [1, 2, 3, 4, 5, 6, 7]
}
// CHECK-LABEL: sil @{{.*}}testString
// CHECK-NOT: apply
// CHECK: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSS_Tg5
// CHECK-NOT: apply
// CHECK: apply [[F]]
// CHECK-NOT: apply
// CHECK: tuple
// CHECK-NEXT: return
public func testString(_ a: inout [String], s: String) {
a += [s]
}
// This is not supported yet. Just check that we don't crash on this.`
public func dontPropagateContiguousArray(_ a: inout ContiguousArray<UInt8>) {
a += [4]
}
// Check if the specialized Array.append<A>(contentsOf:) is reasonably optimized for Array<Int>.
// CHECK-LABEL: sil shared {{.*}}@$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5
// There should only be a single call to _createNewBuffer or reserveCapacityForAppend/reserveCapacityImpl.
// CHECK-NOT: apply
// CHECK: [[F:%[0-9]+]] = function_ref @{{.*(_consumeAndCreateNew|reserveCapacity).*}}
// CHECK-NEXT: apply [[F]]
// CHECK-NOT: apply
// CHECK: } // end sil function '$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5
| apache-2.0 |
firebase/firebase-ios-sdk | FirebaseFunctions/Sources/Internal/FunctionsSerializer.swift | 1 | 6856 | // Copyright 2022 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 Foundation
private enum Constants {
static let longType = "type.googleapis.com/google.protobuf.Int64Value"
static let unsignedLongType = "type.googleapis.com/google.protobuf.UInt64Value"
static let dateType = "type.googleapis.com/google.protobuf.Timestamp"
}
enum SerializerError: Error {
// TODO: Add parameters class name and value
case unsupportedType // (className: String, value: AnyObject)
case unknownNumberType(charValue: String, number: NSNumber)
case invalidValueForType(value: String, requestedType: String)
}
class FUNSerializer: NSObject {
private let dateFormatter: DateFormatter
override init() {
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
}
// MARK: - Internal APIs
internal func encode(_ object: Any) throws -> AnyObject {
if object is NSNull {
return object as AnyObject
} else if object is NSNumber {
return try encodeNumber(object as! NSNumber)
} else if object is NSString {
return object as AnyObject
} else if object is NSDictionary {
let dict = object as! NSDictionary
let encoded: NSMutableDictionary = .init()
dict.enumerateKeysAndObjects { key, obj, _ in
// TODO(wilsonryan): Not exact translation
let anyObj = obj as AnyObject
let stringKey = key as! String
let value = try! encode(anyObj)
encoded[stringKey] = value
}
return encoded
} else if object is NSArray {
let array = object as! NSArray
let encoded = NSMutableArray()
for item in array {
let anyItem = item as AnyObject
let encodedItem = try encode(anyItem)
encoded.add(encodedItem)
}
return encoded
} else {
throw SerializerError.unsupportedType
}
}
internal func decode(_ object: Any) throws -> AnyObject? {
// Return these types as is. PORTING NOTE: Moved from the bottom of the func for readability.
if let dict = object as? NSDictionary {
if let requestedType = dict["@type"] as? String {
guard let value = dict["value"] as? String else {
// Seems like we should throw here - but this maintains compatiblity.
return dict
}
let result = try decodeWrappedType(requestedType, value)
if result != nil { return result }
// Treat unknown types as dictionaries, so we don't crash old clients when we add types.
}
let decoded = NSMutableDictionary()
var decodeError: Error?
dict.enumerateKeysAndObjects { key, obj, stopPointer in
do {
let decodedItem = try self.decode(obj)
decoded[key] = decodedItem
} catch {
decodeError = error
stopPointer.pointee = true
return
}
}
// Throw the internal error that popped up, if it did.
if let decodeError = decodeError {
throw decodeError
}
return decoded
} else if let array = object as? NSArray {
let result = NSMutableArray(capacity: array.count)
for obj in array {
// TODO: Is this data loss? The API is a bit weird.
if let decoded = try decode(obj) {
result.add(decoded)
}
}
return result
} else if object is NSNumber || object is NSString || object is NSNull {
return object as AnyObject
}
throw SerializerError.unsupportedType
}
// MARK: - Private Helpers
private func encodeNumber(_ number: NSNumber) throws -> AnyObject {
// Recover the underlying type of the number, using the method described here:
// http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
let cType = number.objCType
// Type Encoding values taken from
// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
// Articles/ocrtTypeEncodings.html
switch cType[0] {
case CChar("q".utf8.first!):
// "long long" might be larger than JS supports, so make it a string.
return ["@type": Constants.longType, "value": "\(number)"] as AnyObject
case CChar("Q".utf8.first!):
// "unsigned long long" might be larger than JS supports, so make it a string.
return ["@type": Constants.unsignedLongType,
"value": "\(number)"] as AnyObject
case CChar("i".utf8.first!),
CChar("s".utf8.first!),
CChar("l".utf8.first!),
CChar("I".utf8.first!),
CChar("S".utf8.first!):
// If it"s an integer that isn"t too long, so just use the number.
return number
case CChar("f".utf8.first!), CChar("d".utf8.first!):
// It"s a float/double that"s not too large.
return number
case CChar("B".utf8.first!), CChar("c".utf8.first!), CChar("C".utf8.first!):
// Boolean values are weird.
//
// On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
// returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
// legitimate usage of signed chars is impossible, but this should be rare.
//
// Just return Boolean values as-is.
return number
default:
// All documented codes should be handled above, so this shouldn"t happen.
throw SerializerError.unknownNumberType(charValue: String(cType[0]), number: number)
}
}
private func decodeWrappedType(_ type: String, _ value: String) throws -> AnyObject? {
switch type {
case Constants.longType:
let formatter = NumberFormatter()
guard let n = formatter.number(from: value) else {
throw SerializerError.invalidValueForType(value: value, requestedType: type)
}
return n
case Constants.unsignedLongType:
// NSNumber formatter doesn't handle unsigned long long, so we have to parse it.
let str = (value as NSString).utf8String
var endPtr: UnsafeMutablePointer<CChar>?
let returnValue = UInt64(strtoul(str, &endPtr, 10))
guard String(returnValue) == value else {
throw SerializerError.invalidValueForType(value: value, requestedType: type)
}
return NSNumber(value: returnValue)
default:
return nil
}
}
}
| apache-2.0 |
zaxonus/AutoLayScroll | AutoLayScroll/AppDelegate.swift | 1 | 273 | //
// AppDelegate.swift
// AutoLayScroll
//
// Created by Michel Bouchet on 19/08/2016.
// Copyright © 2016 Michel Bouchet. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| gpl-3.0 |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-422/SafeRide/SafeRideUITests/SafeRideUITests.swift | 1 | 3656 | //
// SafeRideUITests.swift
// SafeRideUITests
//
// Created by Caleb Friden on 3/30/16.
// Copyright © 2016 University of Oregon. All rights reserved.
//
import XCTest
class SafeRideUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testStandardTapUse() {
// Goes through a standard procedure of what a user would normally do using tapping for selecting locations
let app = XCUIApplication()
app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).elementBoundByIndex(2).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap()
app.otherElements["PopoverDismissRegion"].tap()
app.navigationBars["Press Next to Continue"].buttons["Next"].tap()
let tablesQuery = app.tables
tablesQuery.cells.containingType(.StaticText, identifier:"Number of Riders").childrenMatchingType(.TextField).element.tap()
app.pickerWheels["1"].tap()
tablesQuery.cells.containingType(.StaticText, identifier:"Ride Time").childrenMatchingType(.TextField).element.tap()
let datePickersQuery = app.datePickers
datePickersQuery.pickerWheels["4 o'clock"].tap()
datePickersQuery.pickerWheels["37 minutes"].tap()
let doneButton = app.toolbars.buttons["Done"]
doneButton.tap()
let phoneNumberCellsQuery = tablesQuery.cells.containingType(.StaticText, identifier:"Phone Number")
phoneNumberCellsQuery.childrenMatchingType(.TextField).element.tap()
phoneNumberCellsQuery.childrenMatchingType(.TextField).element
doneButton.tap()
let uoIdNumberCellsQuery = tablesQuery.cells.containingType(.StaticText, identifier:"UO ID Number")
uoIdNumberCellsQuery.childrenMatchingType(.TextField).element.tap()
uoIdNumberCellsQuery.childrenMatchingType(.TextField).element
doneButton.tap()
app.navigationBars["Confirm Ride Details"].buttons["Send Request"].tap()
}
func testStandardInputUse(){
// Goes through a standard procedure of what a user would normally do using the text fields for selecting locations
}
func testSendingRequest(){
// Takes inputs from the confirmation page and submits them
}
}
| gpl-3.0 |
xmartlabs/Opera | Example/Example/Helpers/Helpers.swift | 1 | 1750 | // Helpers.swift
// Example-iOS ( https://github.com/xmartlabs/Example-iOS )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
func DEBUGLog(_ message: String, file: String = #file, line: Int = #line, function: String = #function) {
#if DEBUG
let fileURL = NSURL(fileURLWithPath: file)
let fileName = fileURL.URLByDeletingPathExtension?.lastPathComponent ?? ""
print("\(NSDate().dblog()) \(fileName)::\(function)[L:\(line)] \(message)")
#endif
}
func DEBUGJson(_ value: AnyObject) {
#if DEBUG
if Constants.Debug.jsonResponse {
print(JSONStringify(value))
}
#endif
}
| mit |
groovelab/SwiftBBS | SwiftBBS/SwiftBBS Server/DatabaseManager.swift | 1 | 870 | //
// DatabaseManager.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/03/05.
// Copyright GrooveLab
//
import MySQL
enum DatabaseError : ErrorType {
case Connect(String)
case Query(String)
case StoreResults
}
class DatabaseManager {
let db: MySQL
init() throws {
db = MySQL()
if db.connect(Config.mysqlHost, user: Config.mysqlUser, password: Config.mysqlPassword, db: Config.mysqlDb) == false {
throw DatabaseError.Connect(db.errorMessage())
}
}
func query(sql: String) throws {
if db.query(sql) == false {
throw DatabaseError.Query(db.errorMessage())
}
}
func storeResults() throws -> MySQL.Results {
guard let results = db.storeResults() else {
throw DatabaseError.StoreResults
}
return results
}
}
| mit |
SwiftKit/Lipstick | Source/UITableView+Init.swift | 1 | 302 | //
// UITableView+Init.swift
// Lipstick
//
// Created by Tadeas Kriz on 31/03/16.
// Copyright © 2016 Brightify. All rights reserved.
//
import UIKit
extension UITableView {
public convenience init(style: UITableViewStyle) {
self.init(frame: CGRect.zero, style: style)
}
}
| mit |
zype/ZypeAppleTVBase | ZypeAppleTVBase/Models/QueryModels/QueryCategoriesModel.swift | 1 | 217 | //
// QueryCategoriesModel.swift
// Zype
//
// Created by Ilya Sorokin on 10/21/15.
// Copyright © 2015 Eugene Lizhnyk. All rights reserved.
//
import UIKit
open class QueryCategoriesModel: QueryBaseModel {
}
| mit |
breadwallet/breadwallet | BreadWallet/BRBitID.swift | 4 | 6892 | //
// BRBitID.swift
// BreadWallet
//
// Created by Samuel Sutch on 6/17/16.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Security
@objc open class BRBitID : NSObject {
static let SCHEME = "bitid"
static let PARAM_NONCE = "x"
static let PARAM_UNSECURE = "u"
static let USER_DEFAULTS_NONCE_KEY = "brbitid_nonces"
static let DEFAULT_INDEX: UInt32 = 42
class open func isBitIDURL(_ url: URL!) -> Bool {
return url.scheme == SCHEME
}
open static let BITCOIN_SIGNED_MESSAGE_HEADER = "Bitcoin Signed Message:\n".data(using: String.Encoding.utf8)!
open class func formatMessageForBitcoinSigning(_ message: String) -> Data {
let data = NSMutableData()
data.append(UInt8(BITCOIN_SIGNED_MESSAGE_HEADER.count))
data.append(BITCOIN_SIGNED_MESSAGE_HEADER)
let msgBytes = message.data(using: String.Encoding.utf8)!
data.appendVarInt(UInt64(msgBytes.count))
data.append(msgBytes)
return data as Data
}
// sign a message with a key and return a base64 representation
open class func signMessage(_ message: String, usingKey key: BRKey) -> String {
let signingData = formatMessageForBitcoinSigning(message)
let signature = key.compactSign((signingData as NSData).sha256_2())!
return String(bytes: signature.base64EncodedData(options: []), encoding: String.Encoding.utf8) ?? ""
}
open let url: URL
open var siteName: String {
return "\(url.host!)\(url.path)"
}
public init(url: URL!) {
self.url = url
}
open func newNonce() -> String {
let defs = UserDefaults.standard
let nonceKey = "\(url.host!)/\(url.path)"
var allNonces = [String: [String]]()
var specificNonces = [String]()
// load previous nonces. we save all nonces generated for each service
// so they are not used twice from the same device
if let existingNonces = defs.object(forKey: BRBitID.USER_DEFAULTS_NONCE_KEY) {
allNonces = existingNonces as! [String: [String]]
}
if let existingSpecificNonces = allNonces[nonceKey] {
specificNonces = existingSpecificNonces
}
// generate a completely new nonce
var nonce: String
repeat {
nonce = "\(Int(Date().timeIntervalSince1970))"
} while (specificNonces.contains(nonce))
// save out the nonce list
specificNonces.append(nonce)
allNonces[nonceKey] = specificNonces
defs.set(allNonces, forKey: BRBitID.USER_DEFAULTS_NONCE_KEY)
return nonce
}
open func runCallback(_ completionHandler: @escaping (Data?, URLResponse?, NSError?) -> Void) {
guard let manager = BRWalletManager.sharedInstance() else {
DispatchQueue.main.async {
completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo:
[NSLocalizedDescriptionKey: NSLocalizedString("No wallet", comment: "")]))
}
return
}
autoreleasepool {
guard let seed = manager.seed(withPrompt: "", forAmount: 0) else {
DispatchQueue.main.async {
completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo:
[NSLocalizedDescriptionKey: NSLocalizedString("Could not unlock", comment: "")]))
}
return
}
let seq = BRBIP32Sequence()
var scheme = "https"
var nonce: String
guard let query = url.query?.parseQueryString() else {
DispatchQueue.main.async {
completionHandler(nil, nil, NSError(domain: "", code: -1001, userInfo:
[NSLocalizedDescriptionKey: NSLocalizedString("Malformed URI", comment: "")]))
}
return
}
if let u = query[BRBitID.PARAM_UNSECURE] , u.count == 1 && u[0] == "1" {
scheme = "http"
}
if let x = query[BRBitID.PARAM_NONCE] , x.count == 1 {
nonce = x[0] // service is providing a nonce
} else {
nonce = newNonce() // we are generating our own nonce
}
let uri = "\(scheme)://\(url.host!)\(url.path)"
// build a payload consisting of the signature, address and signed uri
let priv = BRKey(privateKey: seq.bitIdPrivateKey(BRBitID.DEFAULT_INDEX, forURI: uri, fromSeed: seed)!)!
let uriWithNonce = "bitid://\(url.host!)\(url.path)?x=\(nonce)"
let signature = BRBitID.signMessage(uriWithNonce, usingKey: priv)
let payload: [String: String] = [
"address": priv.address!,
"signature": signature,
"uri": uriWithNonce
]
let json = try! JSONSerialization.data(withJSONObject: payload, options: [])
// send off said payload
var req = URLRequest(url: URL(string: "\(uri)?x=\(nonce)")!)
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpMethod = "POST"
req.httpBody = json
let session = URLSession.shared
session.dataTask(with: req, completionHandler: { (dat: Data?, resp: URLResponse?, err: Error?) in
var rerr: NSError?
if err != nil {
rerr = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: String(describing: err)])
}
completionHandler(dat, resp, rerr)
}).resume()
}
}
}
| mit |
mnin/on_ruby_ios | onruby/EventsViewController.swift | 1 | 3682 | //
// SettingViewController.swift
// onruby
//
// Created by Martin Wilhelmi on 24.09.14.
//
class EventsViewController: UITableViewController {
let notificationCenter = NSNotificationCenter.defaultCenter()
var eventArray = [Event]()
var observer: AnyObject!
override func viewDidLoad() {
super.viewDidLoad()
self.setRefreshControl()
self.loadUserGroup()
startObserver()
}
deinit {
notificationCenter.removeObserver(self.observer)
}
func setRefreshControl() {
self.refreshControl = UIRefreshControl()
self.refreshControlTitle()
self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
}
func refresh(sender: AnyObject) {
self.refreshControl?.attributedTitle = NSAttributedString(string: "Refreshing...")
UserGroup.current().reloadJSONFile()
}
func refreshControlTitle() {
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
let lastModificationDate = UserGroup.current().getModificationDate()
self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh (last updated at \(dateFormatter.stringFromDate(lastModificationDate)))")
}
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return self.eventArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "eventCellIdentifier"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell!
if cell == nil
{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
}
let event = self.eventArray[indexPath.row]
let eventName = cell.viewWithTag(100) as UILabel
let eventDate = cell.viewWithTag(101) as UILabel
eventName.text = event.name
eventDate.text = event.dateString()
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var eventViewController = storyboard?.instantiateViewControllerWithIdentifier("event") as EventViewController
eventViewController.event = self.eventArray[indexPath.row]
navigationController?.pushViewController(eventViewController, animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
func startObserver() {
self.observer = notificationCenter.addObserverForName("reloadUserGroup", object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: {(notification: NSNotification!) -> Void in
let updatedUserGroupKey = notification.object as String?
if updatedUserGroupKey != nil && updatedUserGroupKey == UserGroup.current().key {
self.loadUserGroup()
self.navigationController?.popToRootViewControllerAnimated(false)
self.tableView.reloadData()
self.refreshControlTitle()
}
self.refreshControl?.endRefreshing()
})
}
func loadUserGroup() {
self.navigationItem.title = UserGroup.current().name
self.eventArray = UserGroup.current().allEvents()
}
}
| gpl-3.0 |
dangquochoi2007/cleancodeswift | CleanStore/CleanStore/App/Common/SVMenuOptionManager.swift | 1 | 1097 | //
// SVMenuOptionManager.swift
// CleanStore
//
// Created by hoi on 30/6/17.
// Copyright © 2017 hoi. All rights reserved.
//
import Foundation
import UIKit
enum SVMenuOptions {
case LIVETV
case MOVIES
case TVSHOWS
case WATCHLISTS
case PROFILE
case LOGOUT
var menuTitle: String {
switch self {
case .LIVETV:
return "LIVE TV"
case .MOVIES:
return "MOVIES"
case .TVSHOWS:
return "TV SHOWS"
case .WATCHLISTS:
return "WATCHLIST"
case .PROFILE:
return "PROFILE"
case .LOGOUT:
return "LOGOUT"
}
}
var menuIcon: String {
switch self {
case .LIVETV:
return "airplay_ico"
case .MOVIES:
return "movie_ico"
case .TVSHOWS:
return "tvshow_ico"
case .WATCHLISTS:
return "watchlist_ico"
case .PROFILE:
return "profil_ico"
case .LOGOUT:
return "profil_ico"
}
}
}
| mit |
atuooo/notGIF | notGIF/Views/GIFList/GIFListActionView.swift | 1 | 5830 | //
// LongPressPopShareView.swift
// notGIF
//
// Created by ooatuoo on 2017/6/16.
// Copyright © 2017年 xyz. All rights reserved.
//
import UIKit
class GIFListActionView: UIView {
fileprivate var iconViews: [UIView] = []
fileprivate var iconTriggerRects: [CGRect] = []
fileprivate var actionTypes: [GIFActionType] = []
fileprivate var hasChanged: Bool = false
fileprivate var cellMaskRect: CGRect = .zero
fileprivate var isForIntro: Bool = false
init(popOrigin: CGPoint, cellRect: CGRect, frame: CGRect = UIScreen.main.bounds, isForIntro: Bool = false) {
super.init(frame: frame)
backgroundColor = UIColor.black.withAlphaComponent(0.7)
alpha = 0
self.isForIntro = isForIntro
cellMaskRect = cellRect
if isForIntro {
actionTypes = GIFActionType.defaultActions
} else {
actionTypes = NGUserDefaults.customActions
if !OpenShare.canOpen(.wechat) {
actionTypes.remove(.shareTo(.wechat))
}
}
let iconS: CGFloat = 36
let padding: CGFloat = 16
let spaceV: CGFloat = 12
let count = actionTypes.count
let totalW = CGFloat(count) * iconS + CGFloat(count - 1) * padding
var beignOx: CGFloat
if totalW/2 + popOrigin.x > (kScreenWidth - padding/2) {
beignOx = kScreenWidth - totalW - padding / 2
} else if popOrigin.x - totalW/2 < padding / 2 {
beignOx = padding/2
} else {
beignOx = popOrigin.x - totalW/2
}
let baseOriginY: CGFloat = cellRect.minY - spaceV - iconS
for i in 0..<count {
let iconViewFrame = CGRect(x: beignOx, y: baseOriginY, width: iconS, height: iconS)
let iconView = UIImageView(image: actionTypes[i].icon)
iconView.contentMode = .scaleAspectFit
iconView.tintColor = UIColor.textTint
iconView.frame = iconViewFrame.insetBy(dx: 3, dy: 3)
beignOx += iconS + padding
iconView.alpha = 0
let iconTriggerRect = CGRect(x: iconViewFrame.minX - padding/2, y: baseOriginY, width: iconS+padding, height: cellRect.maxY - iconViewFrame.minY)
iconTriggerRects.append(iconTriggerRect)
iconViews.append(iconView)
addSubview(iconView)
}
restore()
}
override func didMoveToWindow() {
super.didMoveToWindow()
if !isForIntro {
animate()
}
}
public func animate() {
let duration = isForIntro ? 1.2 : 0.6
UIView.animate(withDuration: 0.3) {
self.alpha = 1
}
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [.curveEaseIn], animations: {
self.iconViews.forEach { $0.alpha = 1 ; $0.transform = .identity }
}, completion: nil)
}
public func restore() {
alpha = 0
for i in 0..<iconViews.count {
let iconView = iconViews[i]
iconView.alpha = 0
if i % 2 == 0 {
let transformT = CGAffineTransform(translationX: 0, y: iconView.frame.width)
let transformR = CGAffineTransform(rotationAngle: CGFloat.pi * 0.3)
let transfromS = CGAffineTransform(scaleX: 0.2, y: 0.2)
iconView.transform = transformT.concatenating(transfromS).concatenating(transformR)
} else {
let transformT = CGAffineTransform(translationX: 0, y: -iconView.frame.width)
let transformR = CGAffineTransform(rotationAngle: CGFloat.pi * 0.7)
let transfromS = CGAffineTransform(scaleX: 0.3, y: 0.3)
iconView.transform = transformT.concatenating(transfromS).concatenating(transformR)
}
}
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.clear.cgColor)
context?.setBlendMode(.clear)
context?.fillEllipse(in: cellMaskRect.insetBy(dx: 4, dy: 2))
}
public func update(with offset: CGPoint) {
hasChanged = true
let transfromS = CGAffineTransform(scaleX: 1.2, y: 1.2)
let transformT = CGAffineTransform(translationX: 0, y: -12)
let transform = transformT.concatenating(transfromS)
let index = iconTriggerRects.index(where: { $0.contains(offset) })
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [.curveEaseInOut], animations: {
for i in 0..<self.iconViews.count {
if index == i {
self.iconViews[i].transform = transform
} else {
self.iconViews[i].transform = .identity
}
}
}, completion: nil)
}
public func end(with offset: CGPoint) -> GIFActionType? {
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 0
}) { _ in
self.removeFromSuperview()
}
guard hasChanged else { return nil }
if let index = iconTriggerRects.index(where: { $0.contains(offset) }) {
return actionTypes[index]
} else {
return nil
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
sanjaymhj/SMRippleExample | SMRippleExample/AppDelegate.swift | 1 | 2185 | //
// AppDelegate.swift
// SMRippleExample
//
// Created by Sanjay Maharjan on 5/25/16.
// Copyright © 2016 Sanjay Maharjan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: 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 |
nguyenantinhbk77/practice-swift | Tutorials/Developing_iOS_Apps_With_Swift/lesson8/lesson8/DetailsViewController.swift | 3 | 2828 | import UIKit
import MediaPlayer
import QuartzCore
class DetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, APIControllerProtocol{
@lazy var api: APIController = APIController(delegate: self)
var album: Album?
@IBOutlet var albumTitle : UILabel
@IBOutlet var cover : UIImageView
@IBOutlet var tracksTableView: UITableView
var tracks: Track[] = []
var mediaPlayer = MPMoviePlayerController()
init(coder aDecoder: NSCoder!){
super.init(coder: aDecoder)
}
override func viewDidLoad(){
super.viewDidLoad()
//self.albumTitle.text = album?.title
//var url = NSURL(string:self.album?.largeImageURL)
//var data = NSData(contentsOfURL:url)
//self.cover.image = UIImage(data: data)
if self.album?.collectionId?{
self.api.lookupAlbum(self.album!.collectionId!)
}
}
func didReceiveAPIResults(results: NSDictionary) {
if let allResults = results["results"] as? NSDictionary[] {
for trackInfo in allResults {
// Create the track
if let kind = trackInfo["kind"] as? String {
if kind=="song" {
var track = Track(dict: trackInfo)
tracks.append(track)
}
}
}
}
dispatch_async(dispatch_get_main_queue(), {
self.tracksTableView.reloadData()
})
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return tracks.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("TrackCell") as TrackCell
var track = tracks[indexPath.row]
cell.titleLabel.text = track.title
println(track.title)
cell.playIcon.text = "▶️"
return cell
}
func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1,1,1)
})
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
var track = tracks[indexPath.row]
mediaPlayer.stop()
mediaPlayer.contentURL = NSURL(string: track.previewUrl)
mediaPlayer.play()
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? TrackCell {
cell.playIcon.text = "▪️"
}
}
} | mit |
natecook1000/swift-compiler-crashes | fixed/25351-swift-serialization-serializer-writenormalconformance.swift | 7 | 281 | // 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 c { T
{
}
class b<T :d{} { a { }}
}class a {
class d{
protocol c {
{
}
{} }c {enum{
"
struct c{enum Sg
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/19880-swift-typechecker-typecheckexpression.swift | 10 | 209 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S{init(){struct B{let a=g{},g=Void{ | mit |
mrlegowatch/JSON-to-Swift-Converter | JSON to Swift ConverterUITests/JSONtoSwiftConverterUITests.swift | 1 | 4771 | //
// JSONtoSwiftConverterUITests.swift
// JSON to Swift Converter
//
// Created by Brian Arnold on 2/20/17.
// Copyright © 2018 Brian Arnold. All rights reserved.
//
import XCTest
class JSONtoSwiftConverterUITests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
XCUIApplication().launch()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSettings() {
let window = XCUIApplication().windows["JSON to Swift Converter Settings"]
let letRadioButton = window.radioButtons["let"]
let varRadioButton = window.radioButtons["var"]
let explicitRadioButton = window.radioButtons["Explicit"]
let optionalRadioButton = window.radioButtons["? Optional"]
let requiredRadioButton = window.radioButtons["! Required"]
let supportCodableCheckBox = window.checkBoxes["Support Codable"]
let addDefaultValuesCheckBox = window.checkBoxes["Add default values"]
let outputStaticText = window.staticTexts["outputStaticText"]
// TODO: "reset" the target application's UserDefaults default suite settings in
// a way that actually works. The trick used in the logic unit tests doesn't work
// here. Is it because we are out-of-process, don't have entitlements for the suite,
// or something else? In the meantime, we instead reset the initial state of the controls.
// Reset the initial state of the controls
letRadioButton.click()
requiredRadioButton.click()
if let value = supportCodableCheckBox.value as? Int, value != 1 {
supportCodableCheckBox.click()
}
if let value = addDefaultValuesCheckBox.value as? Int, value != 0 {
addDefaultValuesCheckBox.click()
}
// Validate the initial state of the controls
XCTAssertEqual(letRadioButton.value as? Int, 1, "let should be selected")
XCTAssertEqual(varRadioButton.value as? Int, 0, "var should not be selected")
XCTAssertEqual(explicitRadioButton.value as? Int, 0, "explicit should not be selected")
XCTAssertEqual(optionalRadioButton.value as? Int, 0, "optional should not be selected")
XCTAssertEqual(requiredRadioButton.value as? Int, 1, "required should be selected")
XCTAssertEqual(supportCodableCheckBox.value as? Int, 1, "add key should be selected")
XCTAssertEqual(addDefaultValuesCheckBox.value as? Int, 0, "add default values should be deselected")
// Confirm the initial state of the output static text
do {
let output = outputStaticText.value as? String
let lines = output?.components(separatedBy: "\n")
XCTAssertEqual(lines?.count, 10, "number of lines of output")
}
varRadioButton.click()
XCTAssertEqual(letRadioButton.value as? Int, 0, "let should not be selected")
XCTAssertEqual(varRadioButton.value as? Int, 1, "var should be selected")
optionalRadioButton.click()
XCTAssertEqual(explicitRadioButton.value as? Int, 0, "explicit should not be selected")
XCTAssertEqual(optionalRadioButton.value as? Int, 1, "optional should be selected")
XCTAssertEqual(requiredRadioButton.value as? Int, 0, "required should not be selected")
explicitRadioButton.click()
XCTAssertEqual(explicitRadioButton.value as? Int, 1, "explicit should be selected")
XCTAssertEqual(optionalRadioButton.value as? Int, 0, "optional should not be selected")
XCTAssertEqual(requiredRadioButton.value as? Int, 0, "required should not be selected")
supportCodableCheckBox.click()
XCTAssertEqual(supportCodableCheckBox.value as? Int, 0, "add key should not be selected")
do {
let output = outputStaticText.value as? String
let lines = output?.components(separatedBy: "\n")
XCTAssertEqual(lines?.count, 9, "number of lines of output")
}
addDefaultValuesCheckBox.click()
XCTAssertEqual(addDefaultValuesCheckBox.value as? Int, 1, "add default values should be selected")
// Turn add key back on so we can test add init and add var dictionary
supportCodableCheckBox.click()
do {
let output = outputStaticText.value as? String
let lines = output?.components(separatedBy: "\n")
XCTAssertEqual(lines?.count, 10, "number of lines of output")
}
}
}
| mit |
jwfriese/FrequentFlyer | FrequentFlyerTests/ObjectMapperExtension/StrictBoolTransformSpec.swift | 1 | 1922 | import XCTest
import ObjectMapper
import Quick
import Nimble
@testable import FrequentFlyer
class StrictBoolTransformSpec: QuickSpec {
override func spec() {
describe("\(StrictBoolTransform.self)") {
var subject: StrictBoolTransform!
beforeEach {
subject = StrictBoolTransform()
}
describe("transformFromJSON:") {
it("returns nil when input is nil") {
expect(subject.transformFromJSON(nil)).to(beNil())
}
it("handles normal bool values correctly") {
expect(subject.transformFromJSON("true")).to(beTrue())
expect(subject.transformFromJSON(true)).to(beTrue())
expect(subject.transformFromJSON("false")).to(beFalse())
expect(subject.transformFromJSON(false)).to(beFalse())
}
it("returns nil when input is really numeric") {
expect(subject.transformFromJSON(1.0)).to(beNil())
expect(subject.transformFromJSON(1)).to(beNil())
expect(subject.transformFromJSON(1.0)).to(beNil())
}
it("returns nil when input is some silly string") {
expect(subject.transformFromJSON("something else")).to(beNil())
}
}
describe("transformToJSON:") {
it("returns nil when input is nil") {
expect(subject.transformToJSON(nil)).to(beNil())
}
it("returns 'true' when given 'true'") {
expect(subject.transformToJSON(true)).to(equal("true"))
}
it("returns 'false' when given 'false'") {
expect(subject.transformToJSON(false)).to(equal("false"))
}
}
}
}
}
| apache-2.0 |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/00391-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 1 | 212 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
struct B<T where I.c: d {
func b
| mit |
webelectric/AspirinKit | AspirinKit/Sources/Foundation/String+Extensions.swift | 1 | 11701 | //
// String.swift
// AspirinKit
//
// Copyright © 2014 - 2017 The Web Electric Corp.
//
// 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
let spaceCharacterSet = CharacterSet.whitespaces
public extension String {
var length:Int { return self.characters.count }
var NSStr:NSString { return (self as NSString) }
var float:Float? {
return Float(self)
}
var double:Double? {
return Double(self)
}
var int:Int? {
return Int(self)
}
var fourCharCode:FourCharCode {
assert(self.characters.count == 4, "String length must be 4")
var result : FourCharCode = 0
for char in self.utf16 {
result = (result << 8) + FourCharCode(char)
}
return result
}
static func createUUID() -> String {
return UUID().uuidString
}
public init(base64Value: String) {
let data = Data(base64Encoded: base64Value, options: Data.Base64DecodingOptions(rawValue: 0))
self = String(data: data!, encoding: String.Encoding.utf8)!
}
var base64Value: String {
let data = self.data(using: String.Encoding.utf8)
return data!.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
}
public func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
///a String qualifies as 'blank' if it's either nil or only made up of spaces
public static func isBlank(_ val:String!) -> Bool {
if val == nil {
return true
}
return val.trim().isEmpty
}
mutating public func removed(prefix: String) {
let prefixStartIndex = self.index(self.startIndex, offsetBy: prefix.characters.count)
let range = self.startIndex..<prefixStartIndex
self.removeSubrange(range)
}
public func removing(prefix: String) -> String {
if !self.hasPrefix(prefix) {
return self
}
let prefixStartIndex = self.characters.index(self.startIndex, offsetBy: prefix.characters.count)
return String(self[prefixStartIndex...])
}
public func removing(suffix: String) -> String {
let position = self.position(of: suffix)
if position == -1 {
return self
}
let toIdx = self.index(self.startIndex, offsetBy: position)
return String(self[..<toIdx])
}
public func substring(from startIndex: Int, length: Int) -> String
{
let start = self.characters.index(self.startIndex, offsetBy: startIndex)
let end = self.characters.index(self.startIndex, offsetBy: startIndex + length)
return String(self[start ..< end])
}
public func position(of substring: String) -> Int
{
if let range = self.range(of: substring) {
return self.characters.distance(from: self.startIndex, to: range.lowerBound)
}
else {
return -1
}
}
public func position(of substring: String, from startIndex: Int) -> Int {
let startRange = self.characters.index(self.startIndex, offsetBy: startIndex)
let range = self.range(of: substring, options: NSString.CompareOptions.literal, range: Range<String.Index>(startRange ..< self.endIndex))
if let rangeResult = range {
return self.characters.distance(from: self.startIndex, to: rangeResult.lowerBound)
} else {
return -1
}
}
public func lastPosition(of substring: String) -> Int
{
var index = -1
var stepIndex = self.position(of: substring)
while stepIndex > -1 {
index = stepIndex
if (stepIndex + substring.length) < self.length {
stepIndex = self.position(of: substring, from: (stepIndex + substring.length))
}
else {
stepIndex = -1
}
}
return index
}
public subscript(i: Int) -> Character {
get {
let index = characters.index(startIndex, offsetBy: i)
return self[index]
}
}
public subscript(i: Int) -> String {
return String(self[i] as Character)
}
fileprivate var vowels: [String] {
return ["a", "e", "i", "o", "u"]
}
fileprivate var consonants: [String] {
return ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"]
}
public func pluralized(by count: Int, with locale: Locale = Locale(identifier: "en_US")) -> String
{
let localeLanguage = locale.languageCode ?? "en"
if localeLanguage != "en" {
print("Error plularizing, only languageCode = 'en' is supported at this time, returning unmodified string.")
return self
}
if count == 1 {
return self
}
else {
let len = self.length
let lastChar = self.substring(from: len - 1, length: 1)
let secondToLastChar = self.substring(from: len - 2, length: 1)
var prefix = "", suffix = ""
if lastChar.lowercased() == "y" && vowels.filter({x in x == secondToLastChar}).count == 0 {
let toIdx = self.index(self.startIndex, offsetBy: (len - 1))
prefix = String(self[..<toIdx])// self[0..<(self.length - 1)]
suffix = "ies"
}
else if lastChar.lowercased() == "s" || (lastChar.lowercased() == "o" && consonants.filter({x in x == secondToLastChar}).count > 0) {
let toIdx = self.index(self.startIndex, offsetBy: (len))
prefix = String(self[..<toIdx])// self[0..<(self.length - 1)]
// prefix = self[0..<self.length]
suffix = "es"
}
else {
let toIdx = self.index(self.startIndex, offsetBy: (len))
prefix = String(self[..<toIdx])// self[0..<(self.length - 1)]
// prefix = self[0..<self.length]
suffix = "s"
}
return prefix + (lastChar != lastChar.uppercased() ? suffix : suffix.uppercased())
}
}
}
public extension String {
///removes prefix if present
mutating public func removePrefix(_ prefix: String) {
let prefixStartIndex = self.index(self.startIndex, offsetBy: prefix.characters.count)
let range = self.startIndex..<prefixStartIndex
self.removeSubrange(range)
}
public func stringByRemovingPrefix(_ prefix: String) -> String {
if !self.hasPrefix(prefix) {
return self
}
let prefixStartIndex = self.characters.index(self.startIndex, offsetBy: prefix.characters.count)
return String(self[prefixStartIndex...])
}
public func stringByRemovingSuffix(_ suffix: String) -> String {
let position = self.indexOf(suffix)
if position == -1 {
return self
}
let toIdx = self.index(self.startIndex, offsetBy: position)
return String(self[..<toIdx])
}
public func subString(_ startIndex: Int, length: Int) -> String
{
let start = self.characters.index(self.startIndex, offsetBy: startIndex)
let end = self.characters.index(self.startIndex, offsetBy: startIndex + length)
return String(self[start ..< end])
}
public func indexOf(_ substring: String) -> Int
{
if let range = self.range(of: substring) {
return self.characters.distance(from: self.startIndex, to: range.lowerBound)
}
else {
return -1
}
}
public func indexOf(_ substring: String, startIndex: Int) -> Int {
let startRange = self.characters.index(self.startIndex, offsetBy: startIndex)
let range = self.range(of: substring, options: NSString.CompareOptions.literal, range: Range<String.Index>(startRange ..< self.endIndex))
if let rangeResult = range {
return self.characters.distance(from: self.startIndex, to: rangeResult.lowerBound)
} else {
return -1
}
}
public func lastIndexOf(_ substring: String) -> Int
{
var index = -1
var stepIndex = self.indexOf(substring)
while stepIndex > -1 {
index = stepIndex
if (stepIndex + substring.length) < self.length {
stepIndex = self.indexOf(substring, startIndex: (stepIndex + substring.length))
}
else {
stepIndex = -1
}
}
return index
}
// public func contains(_ substring:String) -> Bool {
// return self.indexOf(substring) != -1
// }
public func pluralize(_ count: Int) -> String
{
if count == 1 {
return self
}
else {
let lastChar = self.subString(self.length - 1, length: 1)
let secondToLastChar = self.subString(self.length - 2, length: 1)
var prefix = "", suffix = ""
if lastChar.lowercased() == "y" && vowels.filter({x in x == secondToLastChar}).count == 0 {
print(prefix)
let toIdx = self.index(self.startIndex, offsetBy: (self.length - 1))
prefix = String(self[..<toIdx])// self[0..<(self.length - 1)]
print(prefix)
suffix = "ies"
}
else if lastChar.lowercased() == "s" || (lastChar.lowercased() == "o" && consonants.filter({x in x == secondToLastChar}).count > 0) {
let toIdx = self.index(self.startIndex, offsetBy: (self.length))
prefix = String(self[..<toIdx])// self[0..<(self.length - 1)]
// prefix = self[0..<self.length]
suffix = "es"
}
else {
let toIdx = self.index(self.startIndex, offsetBy: (self.length))
prefix = String(self[..<toIdx])// self[0..<(self.length - 1)]
// prefix = self[0..<self.length]
suffix = "s"
}
return prefix + (lastChar != lastChar.uppercased() ? suffix : suffix.uppercased())
}
}}
| mit |
delba/SwiftyOAuth | Source/Providers/Basecamp.swift | 1 | 1591 | //
// Basecamp.swift
//
// Copyright (c) 2016-2019 Damien (http://delba.io)
//
// 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.
//
extension Provider {
public static func basecamp(clientID: String, clientSecret: String, redirectURL: String) -> Provider {
return Provider(
clientID: clientID,
clientSecret: clientSecret,
authorizeURL: "https://launchpad.37signals.com/authorization/new",
tokenURL: "https://launchpad.37signals.com/authorization/token",
redirectURL: redirectURL
)
}
}
| mit |
zSher/BulletThief | BulletThief/BulletThief/LinePathBulletEffect.swift | 1 | 1624 | //
// LinePathBulletEffect.swift
// BulletThief
//
// Created by Zachary on 5/4/15.
// Copyright (c) 2015 Zachary. All rights reserved.
//
import Foundation
import SpriteKit
/// This bullet effect...
///
/// * Sets the path of the bullet to be a stright line up or down
class LinePathBulletEffect: NSObject, NSCoding, BulletEffectProtocol {
var path: UIBezierPath!
override init() {
var linePath = UIBezierPath()
linePath.moveToPoint(CGPointZero) //MoveOnPath action is relative to object using it, start 0,0
linePath.addLineToPoint(CGPointMake(0, 550))
self.path = linePath
}
// directional initializer.
init(direction: Directions) {
if direction == Directions.Down {
var linePath = UIBezierPath()
linePath.moveToPoint(CGPointZero) //MoveOnPath action is relative to object using it, start 0,0
linePath.addLineToPoint(CGPointMake(0, -650))
self.path = linePath
} else {
var linePath = UIBezierPath()
linePath.moveToPoint(CGPointZero) //MoveOnPath action is relative to object using it, start 0,0
linePath.addLineToPoint(CGPointMake(0, 550))
self.path = linePath
}
}
required init(coder aDecoder: NSCoder) {
self.path = aDecoder.decodeObjectForKey("path") as UIBezierPath
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(path, forKey: "path")
}
func applyEffect(gun: Gun) {
for bullet in gun.bulletPool {
bullet.path = self.path
}
}
}
| mit |
DianQK/rx-sample-code | PDFExpertContents/ContentItemModel.swift | 1 | 1527 | //
// ContentItemModel.swift
// PDF-Expert-Contents
//
// Created by DianQK on 24/09/2016.
// Copyright © 2016 DianQK. All rights reserved.
//
import Foundation
import RxDataSources
import SwiftyJSON
import RxExtensions
typealias ExpandableContentItemModel = ExpandableItem<ContentItemModel>
struct ContentItemModel: IDHashable, IdentifiableType {
let id: Int64
let title: String
let level: Int
let url: URL?
init(title: String, level: Int, id: Int64, url: URL?) {
self.title = title
self.level = level
self.id = id
self.url = url
}
var hashValue: Int {
return id.hashValue
}
var identity: Int64 {
return id
}
static func createExpandableContentItemModel(json: JSON, withPreLevel preLevel: Int) -> ExpandableContentItemModel {
let title = json["title"].stringValue
let id = json["id"].int64Value
let url = URL(string: json["url"].stringValue)
let level = preLevel + 1
let subItems: [ExpandableContentItemModel]
if let subJSON = json["subdirectory"].array, !subJSON.isEmpty {
subItems = subJSON.map { createExpandableContentItemModel(json: $0, withPreLevel: level) }
} else {
subItems = []
}
let contentItemModel = ContentItemModel(title: title, level: level, id: id, url: url)
let expandableItem = ExpandableItem(model: contentItemModel, isExpanded: false, subItems: subItems)
return expandableItem
}
}
| mit |
DarlingXIe/WeiBoProject | WeiBo/WeiBo/Classes/Model/XDLMatchResult.swift | 1 | 387 | //
// XDLMatchResult.swift
// WeiBo
//
// Created by DalinXie on 16/10/17.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
class XDLMatchResult: NSObject {
var captureString: String
var captureRange: NSRange
init(string: String, range: NSRange){
captureString = string
captureRange = range
}
}
| mit |
MakeSchool/Swift-Playgrounds | More-P1-Properties.playground/Contents.swift | 2 | 3910 | import UIKit
/*:
Let's talk properties! Properties associate values with the class/structure they belong to. There are 2 types of properties: stored properties and computed properties. Stored properties store values for the instance of the class/structure. On the other hand, computed properties have no actual values, but their values are computed on the spot when they are accessed. We will discuss the 2 types of properties in more detail.
*/
/*:
Let's start with stored properties! A class/structure can have both variable or constant stored properties. Each stored property can have a default value, and if the property is a variable, its value can change in the future. Let's look at some examples:
*/
class SomeClass {
let a: Int
var b: String
init(a: Int, b: String) {
self.a = a
self.b = b
}
}
/*:
It is important to understand that properties cannot be left without a value unless they are optionals (where their default value is nil). Try uncommenting the init function and see what kind of error you get. The compiler gives an error because when an object of SomeClass is created, the values of a and b will not be be set to anything. For that reason, you need an initializer that will set their values or you have to give default values to the properties.
*/
/*:
Let's look at a code that uses this class:
*/
var item = SomeClass(a: 10, b: "Swift rocks!")
/*:
In order to access the properties of the object, you use dot notation:
*/
println(item.b)
/*:
Let's now take a look at computed properties. In the class below, num is a stored property becuse it actually stores an integer, but take a look at str property. It does not store any values. It only creates a string whenever it is accessed. Make sure you understand the syntax: for a computed property, you do not say "= 50" for example. You instead, open a block "{ }" and inside there, you add "get { }", and in that block you will return a value for the computed property.
*/
class SomeClass2 {
var num: Int = 50
var str: String {
get {
return "Swift rocks \(num) times!"
}
}
}
/*:
Notice, there are no custom initializers. That is becuase num has a default value, and computed properties do not need to be initialized. As a result, the class is already initialized and ready to go. There is no need to add an init function.
*/
var item2 = SomeClass2()
/*:
What is happening when you write "item2.str"? Since str is a computed property, the program calls its get block, and uses the returned value as the property's value.
*/
println(item2.str)
/*:
Notice how we change only the num property, but the value of str also changes based on that. That is because str's value is computed when it is accessed, based on the value of num.
*/
item2.num = 100
println(item2.str)
/*:
Now let's look at what more you can do with properties. It is possible to observe when a property's value changes, so as a class, you can act accordingly. As you can see below, there are 2 blocks you can add to each property, willSet and didSet. willSet is called just before the new value is stored and didSet is called right after the new value is set.
In willSet, self.num still contains the old value. In order to access the new value, you use newValue variable. In didSet, self.num contains the new value. In order to access the old value, you use oldValue variable.
*/
class SomeClass3 {
var num: Int = 50 {
willSet {
if newValue > self.num {
}
}
didSet {
if self.num == oldValue {
self.num * 2
}
}
}
var str: String {
get {
return "Swift rocks \(num) times!"
}
}
}
/*:
Notice that during initialization, the willSet/diSet blocks are not called.
*/
let item3 = SomeClass3()
item3.num = 60
| mit |
Ferrari-lee/firefox-ios | ClientTests/PrefsTests.swift | 49 | 3420 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCTest
import Shared
class PrefsTests: XCTestCase {
let prefs = NSUserDefaultsPrefs(prefix: "PrefsTests")
override func setUp() {
prefs.clearAll()
}
func testClearPrefs() {
prefs.setObject("foo", forKey: "bar")
XCTAssertEqual(prefs.stringForKey("bar")!, "foo")
// Ensure clearing prefs is branch-specific.
let otherPrefs = NSUserDefaultsPrefs(prefix: "othermockaccount")
otherPrefs.clearAll()
XCTAssertEqual(prefs.stringForKey("bar")!, "foo")
prefs.clearAll()
XCTAssertNil(prefs.stringForKey("bar"))
}
func testStringForKey() {
XCTAssertNil(prefs.stringForKey("key"))
prefs.setObject("value", forKey: "key")
XCTAssertEqual(prefs.stringForKey("key")!, "value")
// Non-String values return nil.
prefs.setObject(1, forKey: "key")
XCTAssertNil(prefs.stringForKey("key"))
}
func testBoolForKey() {
XCTAssertNil(prefs.boolForKey("key"))
prefs.setObject(true, forKey: "key")
XCTAssertEqual(prefs.boolForKey("key")!, true)
prefs.setObject(false, forKey: "key")
XCTAssertEqual(prefs.boolForKey("key")!, false)
// We would like non-Bool values to return nil, but I can't figure out how to differentiate.
// Instead, this documents the undesired behaviour.
prefs.setObject(1, forKey: "key")
XCTAssertEqual(prefs.boolForKey("key")!, true)
prefs.setObject("1", forKey: "key")
XCTAssertNil(prefs.boolForKey("key"))
prefs.setObject("x", forKey: "key")
XCTAssertNil(prefs.boolForKey("key"))
}
func testStringArrayForKey() {
XCTAssertNil(prefs.stringArrayForKey("key"))
prefs.setObject(["value1", "value2"], forKey: "key")
XCTAssertEqual(prefs.stringArrayForKey("key")!, ["value1", "value2"])
// Non-[String] values return nil.
prefs.setObject(1, forKey: "key")
XCTAssertNil(prefs.stringArrayForKey("key"))
// [Non-String] values return nil.
prefs.setObject([1, 2], forKey: "key")
XCTAssertNil(prefs.stringArrayForKey("key"))
}
func testMockProfilePrefsRoundtripsTimestamps() {
let prefs = MockProfilePrefs().branch("baz")
let val: Timestamp = NSDate.now()
prefs.setLong(val, forKey: "foobar")
XCTAssertEqual(val, prefs.unsignedLongForKey("foobar")!)
}
func testMockProfilePrefsKeys() {
let prefs = MockProfilePrefs().branch("baz") as! MockProfilePrefs
let val: Timestamp = NSDate.now()
prefs.setLong(val, forKey: "foobar")
XCTAssertEqual(val, (prefs.things["baz.foobar"] as! NSNumber).unsignedLongLongValue)
}
func testMockProfilePrefsClearAll() {
let prefs1 = MockProfilePrefs().branch("bar") as! MockProfilePrefs
let prefs2 = MockProfilePrefs().branch("baz") as! MockProfilePrefs
// Ensure clearing prefs is branch-specific.
prefs1.setInt(123, forKey: "foo")
prefs2.clearAll()
XCTAssertEqual(123, prefs1.intForKey("foo")!)
prefs1.clearAll()
XCTAssertNil(prefs1.intForKey("foo") as! AnyObject?)
}
}
| mpl-2.0 |
juliobertolacini/ReduxPaperSwift | ReduxPaperScissors/ReduxPaperScissors/AppDelegate.swift | 1 | 2237 | //
// Created by Julio Bertolacini on 02/08/17.
// Copyright © 2017 Julio Bertolacini Organization. All rights reserved.
//
import UIKit
import ReSwift
var store = Store<AppState>(reducer: appReducer, state: nil)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: 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 invalidate graphics rendering callbacks. 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 active 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 |
yonaskolb/SwagGen | Specs/TFL/generated/Swift/Sources/Requests/Road/GetRoad.swift | 1 | 3086 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
extension TFL.Road {
/** Gets the road with the specified id (e.g. A1) */
public enum GetRoad {
public static let service = APIService<Response>(id: "getRoad", tag: "Road", method: "GET", path: "/Road/{ids}", hasBody: false, securityRequirements: [])
public final class Request: APIRequest<Response> {
public struct Options {
/** Comma-separated list of road identifiers e.g. "A406, A2" (a full list of supported road identifiers can be found at the /Road/ endpoint) */
public var ids: [String]
public init(ids: [String]) {
self.ids = ids
}
}
public var options: Options
public init(options: Options) {
self.options = options
super.init(service: GetRoad.service)
}
/// convenience initialiser so an Option doesn't have to be created
public convenience init(ids: [String]) {
let options = Options(ids: ids)
self.init(options: options)
}
public override var path: String {
return super.path.replacingOccurrences(of: "{" + "ids" + "}", with: "\(self.options.ids.joined(separator: ","))")
}
}
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = [RoadCorridor]
/** OK */
case status200([RoadCorridor])
public var success: [RoadCorridor]? {
switch self {
case .status200(let response): return response
}
}
public var response: Any {
switch self {
case .status200(let response): return response
}
}
public var statusCode: Int {
switch self {
case .status200: return 200
}
}
public var successful: Bool {
switch self {
case .status200: return true
}
}
public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws {
switch statusCode {
case 200: self = try .status200(decoder.decode([RoadCorridor].self, from: data))
default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data)
}
}
public var description: String {
return "\(statusCode) \(successful ? "success" : "failure")"
}
public var debugDescription: String {
var string = description
let responseString = "\(response)"
if responseString != "()" {
string += "\n\(responseString)"
}
return string
}
}
}
}
| mit |
chaosarts/ChaosMath.swift | ChaosMath/basis2.swift | 1 | 6222 | //
// basis2.swift
// ChaosMath
//
// Created by Fu Lam Diep on 09/10/2016.
// Copyright © 2016 Fu Lam Diep. All rights reserved.
//
import Foundation
public struct tbasis2<T: ArithmeticScalarType>: Equatable {
/*
+--------------------------------------------------------------------------
| Typealiases
+--------------------------------------------------------------------------
*/
/// Describes the data type of the components
public typealias ElementType = T
/// Describes its own type
public typealias SelfType = tbasis2<ElementType>
/// Decribes the VectorType
public typealias VectorType = tvec2<ElementType>
/// Decribes the MatrixType
public typealias MatrixType = tmat2<ElementType>
/*
+--------------------------------------------------------------------------
| Stored properties
+--------------------------------------------------------------------------
*/
/// Provides the first vector of the basis
public let b1: VectorType
/// Provides the second vector of the basis
public let b2: VectorType
/*
+--------------------------------------------------------------------------
| Derived properties
+--------------------------------------------------------------------------
*/
/// Provides the first basis vector
public var x: VectorType {
return b1
}
/// Provides the first basis vector
public var y: VectorType {
return b2
}
/// Represents the basis as matrix
public var mat: MatrixType {
return MatrixType(b1, b2)
}
/*
+--------------------------------------------------------------------------
| Initialisers
+--------------------------------------------------------------------------
*/
/// Initializes the basis with the standard basis vectors
public init () {
b1 = VectorType.e1
b2 = VectorType.e2
}
/// Initializes the basis with given basis vectors
/// - parameter b1: The first basis vector
/// - parameter b2: The second basis vector
public init?<ForeignType: ArithmeticScalarType> (_ b1: tvec2<ForeignType>, _ b2: tvec2<ForeignType>) {
if determinant(b1, b2) == 0 {
return nil
}
self.b1 = VectorType(b1)
self.b2 = VectorType(b2)
}
/// Initializes the basis with a matrix
/// - parameter mat: The matrix to adopt the
public init?<ForeignType: ArithmeticScalarType> (_ mat: tmat2<ForeignType>) {
let determinant : ForeignType = mat.det
if determinant == 0 {
return nil
}
b1 = VectorType(mat.array[0], mat.array[1])
b2 = VectorType(mat.array[2], mat.array[3])
}
/// Copies a basis
public init<ForeignType: ArithmeticScalarType> (_ basis: tbasis2<ForeignType>) {
b1 = VectorType(basis.b1)
b2 = VectorType(basis.b2)
}
}
public typealias basis2i = tbasis2<Int>
public typealias basis2f = tbasis2<Float>
public typealias basis2d = tbasis2<Double>
public typealias basis2 = basis2f
/*
+------------------------------------------------------------------------------
| Operators
+------------------------------------------------------------------------------
*/
public func ==<ElementType: ArithmeticScalarType> (left: tbasis2<ElementType>, right: tbasis2<ElementType>) -> Bool {
return left.b1 == right.b1 && left.b2 == right.b2
}
/*
+------------------------------------------------------------------------------
| Functions
+------------------------------------------------------------------------------
*/
/// Returns the transformation matrix from one basis to another
/// - parameter from: The basis to transform from
/// - parameter to: The basis to transform to
/// - returns: The transformation matrix
public func transformation<T: ArithmeticIntType> (fromBasis from: tbasis2<T>, toBasis to: tbasis2<T>) -> mat2f {
let invertedMat : mat2f = try! invert(to.mat)
return invertedMat * mat2f(from.mat)
}
/// Returns the transformation matrix from one basis to another
/// - parameter from: The basis to transform from
/// - parameter to: The basis to transform to
/// - returns: The transformation matrix
public func transformation<T: ArithmeticFloatType> (fromBasis from: tbasis2<T>, toBasis to: tbasis2<T>) -> tmat2<T> {
let inverseTo : tmat2<T> = try! invert(to.mat)
return inverseTo * from.mat
}
/// Returns the orthognal version of given basis
/// - parameter basis: The basis to orthogonalize
/// - parameter normalize: Indicates, whether to normalize the basis or not
public func gramschmidt<T: ArithmeticScalarType> (_ basis: tbasis2<T>, _ normalize: Bool = false) -> tbasis2<Float>? {
return gramschmidt(basis.b1, basis.b2)
}
/// Returns a orthogonal basis out of the given two vectors, if not collinear
/// - parameter w1: The first vector
/// - parameter w2: The second vector
/// - parameter normalize: Indicates, whether to normalize the basis or not
public func gramschmidt<T: ArithmeticScalarType> (_ w1: tvec2<T>, _ w2: tvec2<T>, _ normalize: Bool = false) -> tbasis2<Float>? {
if determinant(w1, w2) == 0 {
return nil
}
var v1 : tvec2<Float> = tvec2<Float>(w1)
var v2 : tvec2<Float> = tvec2<Float>(w2)
v2 -= dot(v1, v2) / dot(v1, v1) * v1
if normalize {
v1 = ChaosMath.normalize(v1)
v2 = ChaosMath.normalize(v2)
}
return tbasis2<Float>(v1, v2)
}
/// Returns a orthogonal basis out of the given two vectors, if not collinear
/// - parameter w1: The first vector
/// - parameter w2: The second vector
/// - parameter normalize: Indicates, whether to normalize the basis or not
public func gramschmidt (_ w1: vec2d, _ w2: vec2d, _ normalize: Bool = false) -> basis2d? {
if determinant(w1, w2) == 0 {
return nil
}
var v1 : vec2d = w1
var v2 : vec2d = w2 - dot(v1, w2) / dot(v1, v1) * v1
if normalize {
v1 = ChaosMath.normalize(v1)
v2 = ChaosMath.normalize(v2)
}
return basis2d(v1, v2)
}
| gpl-3.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/00363-swift-scopeinfo-addtoscope.swift | 1 | 924 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
}
class i {
func d((h: (Any, AnyObject)) {
}
}
func d<i>() -> (i, i -> i) -> i {
i j i.f = {
}
protocol d {
}
class i: d{ class func f {}
enum A : String {
}
struct d<f : e, g: e where g.h == f.h> {
}
}
extension d) {
}
func a() {
c a(b: Int = 0) {
}
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
o.m == o> (m: o) {
}
st.C == E> {s func c() { }
}
}
st> {
}
func prefix(with: Strin-> <r>(() -> r) -> h {
n { u o "\(v): \(u()" }
| apache-2.0 |
ben-ng/swift | stdlib/public/core/StringIndexConversions.swift | 1 | 7823 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension String.Index {
/// Creates an index in the given string that corresponds exactly to the
/// specified `UnicodeScalarView` position.
///
/// The following example converts the position of the Unicode scalar `"e"`
/// into its corresponding position in the string's character view. The
/// character at that position is the composed `"é"` character.
///
/// let cafe = "Cafe\u{0301}"
/// print(cafe)
/// // Prints "Café"
///
/// let scalarsIndex = cafe.unicodeScalars.index(of: "e")!
/// let charactersIndex = String.Index(scalarsIndex, within: cafe)!
///
/// print(String(cafe.characters.prefix(through: charactersIndex)))
/// // Prints "Café"
///
/// If the position passed in `unicodeScalarIndex` doesn't have an exact
/// corresponding position in `other.characters`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the combining acute accent (`"\u{0301}"`) fails. Combining Unicode
/// scalars do not have their own position in a character view.
///
/// let nextIndex = String.Index(cafe.unicodeScalars.index(after: scalarsIndex),
/// within: cafe)
/// print(nextIndex)
/// // Prints "nil"
///
/// - Parameters:
/// - unicodeScalarIndex: A position in the `unicodeScalars` view of the
/// `other` parameter.
/// - other: The string referenced by both `unicodeScalarIndex` and the
/// resulting index.
public init?(
_ unicodeScalarIndex: String.UnicodeScalarIndex,
within other: String
) {
if !other.unicodeScalars._isOnGraphemeClusterBoundary(unicodeScalarIndex) {
return nil
}
self.init(_base: unicodeScalarIndex, in: other.characters)
}
/// Creates an index in the given string that corresponds exactly to the
/// specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `characters` view. The value `32` is the UTF-16 encoded value of a space
/// character.
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.index(of: 32)!
/// let charactersIndex = String.Index(utf16Index, within: cafe)!
///
/// print(String(cafe.characters.prefix(upTo: charactersIndex)))
/// // Prints "Café"
///
/// If the position passed in `utf16Index` doesn't have an exact
/// corresponding position in `other.characters`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the trailing surrogate of a UTF-16 surrogate pair fails.
///
/// The next example attempts to convert the indices of the two UTF-16 code
/// points that represent the teacup emoji (`"🍵"`). The index of the lead
/// surrogate is successfully converted to a position in `other.characters`,
/// but the index of the trailing surrogate is not.
///
/// let emojiHigh = cafe.utf16.index(after: utf16Index)
/// print(String.Index(emojiHigh, within: cafe))
/// // Prints "Optional(String.Index(...))"
///
/// let emojiLow = cafe.utf16.index(after: emojiHigh)
/// print(String.Index(emojiLow, within: cafe))
/// // Prints "nil"
///
/// - Parameters:
/// - utf16Index: A position in the `utf16` view of the `other` parameter.
/// - other: The string referenced by both `utf16Index` and the resulting
/// index.
public init?(
_ utf16Index: String.UTF16Index,
within other: String
) {
if let me = utf16Index.samePosition(
in: other.unicodeScalars
)?.samePosition(in: other) {
self = me
}
else {
return nil
}
}
/// Creates an index in the given string that corresponds exactly to the
/// specified `UTF8View` position.
///
/// If the position passed in `utf8Index` doesn't have an exact corresponding
/// position in `other.characters`, the result of the initializer is `nil`.
/// For example, an attempt to convert the position of a UTF-8 continuation
/// byte returns `nil`.
///
/// - Parameters:
/// - utf8Index: A position in the `utf8` view of the `other` parameter.
/// - other: The string referenced by both `utf8Index` and the resulting
/// index.
public init?(
_ utf8Index: String.UTF8Index,
within other: String
) {
if let me = utf8Index.samePosition(
in: other.unicodeScalars
)?.samePosition(in: other) {
self = me
}
else {
return nil
}
}
/// Returns the position in the given UTF-8 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf8).characters`.
///
/// This example first finds the position of the character `"é"` and then uses
/// this method find the same position in the string's `utf8` view.
///
/// let cafe = "Café"
/// if let i = cafe.characters.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf8)
/// print(Array(cafe.utf8.suffix(from: j)))
/// }
/// // Prints "[195, 169]"
///
/// - Parameter utf8: The view to use for the index conversion.
/// - Returns: The position in `utf8` that corresponds exactly to this index.
public func samePosition(
in utf8: String.UTF8View
) -> String.UTF8View.Index {
return String.UTF8View.Index(self, within: utf8)
}
/// Returns the position in the given UTF-16 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf16).characters`.
///
/// This example first finds the position of the character `"é"` and then uses
/// this method find the same position in the string's `utf16` view.
///
/// let cafe = "Café"
/// if let i = cafe.characters.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf16)
/// print(cafe.utf16[j])
/// }
/// // Prints "233"
///
/// - Parameter utf16: The view to use for the index conversion.
/// - Returns: The position in `utf16` that corresponds exactly to this index.
public func samePosition(
in utf16: String.UTF16View
) -> String.UTF16View.Index {
return String.UTF16View.Index(self, within: utf16)
}
/// Returns the position in the given view of Unicode scalars that
/// corresponds exactly to this index.
///
/// The index must be a valid index of `String(unicodeScalars).characters`.
///
/// This example first finds the position of the character `"é"` and then uses
/// this method find the same position in the string's `unicodeScalars`
/// view.
///
/// let cafe = "Café"
/// if let i = cafe.characters.index(of: "é") {
/// let j = i.samePosition(in: cafe.unicodeScalars)
/// print(cafe.unicodeScalars[j])
/// }
/// // Prints "é"
///
/// - Parameter unicodeScalars: The view to use for the index conversion.
/// - Returns: The position in `unicodeScalars` that corresponds exactly to
/// this index.
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarView.Index {
return String.UnicodeScalarView.Index(self, within: unicodeScalars)
}
}
| apache-2.0 |
finngaida/spotify2applemusic | Pods/Sweeft/Sources/Sweeft/Operators/ReducingParametersOperators.swift | 2 | 2008 | //
// ReducingParametersOperators.swift
// Pods
//
// Created by Mathias Quintero on 12/7/16.
//
//
import Foundation
/**
Creates a Reducing Parameter
- Parameters:
- nextPartialResult: nextPartialResult Handler for reduce
- initialResult: initial result for reduce
- Returns: Reducing Parameter
*/
public func **<P: ReducingParameters>(_ nextPartialResult: P.NextPartialResultHandler, _ initialResult: P.Result) -> P {
return P(initialResult: initialResult, nextPartialResult: nextPartialResult)
}
/**
Creates a Reducing Parameter
- Parameter initialResult: initial result for reduce
- Parameter nextPartialResult: nextPartialResult Handler for reduce
- Returns: Reducing Parameter
*/
public func **<P: ReducingParameters>(_ initialResult: P.Result, _ nextPartialResult: P.NextPartialResultHandler) -> P {
return nextPartialResult ** initialResult
}
/**
Reduce
- Parameter items: collection
- Parameter reducingParameters: Reducing Parameters
- Returns: Result of reduce
*/
public func ==><C: Collection, R>(_ items: C, _ reducingParameters: RegularReducingParameters<C.Iterator.Element, R>) -> R {
return items.reduce(reducingParameters.initialResult, reducingParameters.nextPartialResult)
}
/**
Reduce with index
- Parameter items: collection
- Parameter reducingParameters: Reducing Parameters with index
- Returns: Result of reduce
*/
public func ==><I, R>(_ items: [I], _ reducingParameters: ReducingParametersWithIndex<I, R>) -> R {
return items.reduce(reducingParameters.initialResult, reducingParameters.nextPartialResult)
}
prefix operator >
/**
Default Reducing Parameters. Creates them with the default value for the type of the result
- Parameter nextPartialResult: nextPartialResult Handler for reduce
- Returns: Result of reduce
*/
public prefix func ><P: ReducingParameters>(_ nextPartialResult: P.NextPartialResultHandler) -> P where P.Result: Defaultable {
return P.Result.defaultValue ** nextPartialResult
}
| mit |
GongChengKuangShi/DYZB | DouYuTV/DouYuTV/Classes/Home/ViewController/RecommentdViewController.swift | 1 | 6163 | //
// RecommentdViewController.swift
// DouYuTV
//
// Created by xrh on 2017/9/6.
// Copyright © 2017年 xiangronghua. All rights reserved.
//
//抓取数据(抓包):http://study.163.com/course/courseLearn.htm?courseId=1003309014&from=study#/learn/video?lessonId=1004015396&courseId=1003309014
//课件地址: http://study.163.com/course/courseLearn.htm?courseId=1003309014&from=study#/learn/video?lessonId=1004020290&courseId=1003309014
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin) / 2
private let kNormalItemH = kItemW * 3 / 4
private let kPrortyItemH = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kGameViewH : CGFloat = 90
private let kCycleViewH = kScreenW * 3 / 8
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
private let kPrortyCellID = "kPrortyCellID"
class RecommentdViewController: UIViewController {
// -- 懒加载
lazy var recommendVM : RecommendViewModel = RecommendViewModel()
lazy var collectionView : UICollectionView = { [unowned self] in
//1、创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
//2、创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.register(UINib(nibName: "CollectionNormalViewCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrortyViewCell", bundle: nil), forCellWithReuseIdentifier: kPrortyCellID)
collectionView.register(UINib(nibName:"CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
lazy var cycleView : RecommandCycleView = {
let cycleView = RecommandCycleView.recommandCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
lazy var gameView : RecommandGameView = {
let gameView = RecommandGameView.recommandGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
//数据请求
loadData()
}
}
//MARK:-- 设置UI界面内容
extension RecommentdViewController {
func setupUI() {
view.addSubview(collectionView)
//添加cycleView
collectionView.addSubview(cycleView)
//添加gameView进入collectionView
collectionView.addSubview(gameView)
//设置collectView的内边距
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH + kGameViewH, 0, 0, 0)
}
}
//MARK: 遵守UIcollectionView的代理协议
extension RecommentdViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recommendVM.anchorGroup.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recommendVM.anchorGroup[section]
return group.anchers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//取出模型
let group = recommendVM.anchorGroup[indexPath.section]
let ancher = group.anchers[indexPath.item]
var cell : CollectionBaseCell!
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrortyCellID, for: indexPath) as! CollectionPrortyViewCell
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID , for: indexPath) as! CollectionNormalViewCell
}
cell.anchor = ancher
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1、取出section的HeaderView
let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
//2、取出模型
headView.group = recommendVM.anchorGroup[indexPath.section]
return headView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrortyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
//--发送网络请求
extension RecommentdViewController {
func loadData() {
//请求推荐数据
recommendVM.requestData {
self.collectionView.reloadData()
//将数据传到gameView
self.gameView.groups = self.recommendVM.anchorGroup
}
//请求轮播数据
recommendVM.requestCycleData {
self.cycleView.cycleModel = self.recommendVM.cycleModel
}
}
}
| mit |
sydvicious/firefox-ios | Client/Frontend/Browser/SessionData.swift | 2 | 1060 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
class SessionData: NSObject, NSCoding {
let currentPage: Int
let urls: [NSURL]
let lastUsedTime: Timestamp
init(currentPage: Int, urls: [NSURL], lastUsedTime: Timestamp) {
self.currentPage = currentPage
self.urls = urls
self.lastUsedTime = lastUsedTime
}
required init(coder: NSCoder) {
self.currentPage = coder.decodeObjectForKey("currentPage") as? Int ?? 0
self.urls = coder.decodeObjectForKey("urls") as? [NSURL] ?? []
self.lastUsedTime = UInt64(coder.decodeInt64ForKey("lastUsedTime")) ?? NSDate.now()
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(currentPage, forKey: "currentPage")
coder.encodeObject(urls, forKey: "urls")
coder.encodeInt64(Int64(lastUsedTime), forKey: "lastUsedTime")
}
} | mpl-2.0 |
RobinFalko/Ubergang | Ubergang/Core/Engine.swift | 1 | 2075 | //
// Engine.swift
// Ubergang
//
// Created by Robin Frielingsdorf on 09/01/16.
// Copyright © 2016 Robin Falko. All rights reserved.
//
import Foundation
import UIKit
open class Engine: NSObject {
public typealias Closure = () -> Void
fileprivate var displayLink: CADisplayLink?
var closures = [String : Closure]()
var mapTable = NSMapTable<AnyObject, AnyObject>(keyOptions: NSPointerFunctions.Options.strongMemory, valueOptions: NSPointerFunctions.Options.weakMemory)
public static var instance: Engine = {
let engine = Engine()
engine.start()
return engine
}()
func start() {
if displayLink == nil {
displayLink = CADisplayLink(target: self, selector: #selector(Engine.update))
displayLink!.add(to: .current, forMode: .common)
}
}
func stop() {
displayLink?.remove(from: .current, forMode: .common)
displayLink = nil
}
@objc func update() {
let enumerator = mapTable.objectEnumerator()
while let any: AnyObject = enumerator?.nextObject() as AnyObject? {
if let loopable = any as? WeaklyLoopable {
loopable.loopWeakly()
}
}
for (_, closure) in closures {
closure()
}
}
func register(_ closure: @escaping Closure, forKey key: String) {
closures[key] = closure
start()
}
func register(_ loopable: WeaklyLoopable, forKey key: String) {
mapTable.setObject(loopable as AnyObject?, forKey: key as AnyObject?)
start()
}
func unregister(_ key: String) {
mapTable.removeObject(forKey: key as AnyObject?)
closures.removeValue(forKey: key)
if mapTable.count == 0 && closures.isEmpty {
stop()
}
}
func contains(_ key: String) -> Bool {
return mapTable.object(forKey: key as AnyObject?) != nil || closures[key] != nil
}
}
| apache-2.0 |
JustForFunOrg/4-TipCalculator | TipCalculator/MainViewController.swift | 1 | 3254 | //
// ViewController.swift
// TipCalculator
//
// Created by vmalikov on 1/30/16.
// Copyright © 2016 justForFun. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var amountTextField: UITextField!
@IBOutlet weak var tipPercentLabel: UILabel!
@IBOutlet weak var tipResultLabel: UILabel!
@IBOutlet weak var totalResultLabel: UILabel!
@IBOutlet weak var tipPercentSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
amountTextField.delegate = self
amountTextField.resignFirstResponder()
addDoneButtonToKeyboard()
}
// MARK: Keyboard
func addDoneButtonToKeyboard() {
let numberToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
numberToolbar.barStyle = UIBarStyle.Default
numberToolbar.items = [
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "keyboardDoneButtonTapped")]
numberToolbar.sizeToFit()
amountTextField.inputAccessoryView = numberToolbar
}
func keyboardDoneButtonTapped() {
amountTextField.endEditing(true)
textFieldDidEndEditing(amountTextField)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
amountTextField.resignFirstResponder()
}
// MARK: Helpers
func updateTipPersentLabel() {
let percentValue = Int(tipPercentSlider.value)
tipPercentLabel.text = "Tip (\(percentValue)%)"
}
func updateTipResultLabel() {
tipResultLabel.text = "\(getTipAmount().formatWithDefaultValue())"
}
func updateTotalLabel() {
totalResultLabel.text = "\(getCalculatedTotal().formatWithDefaultValue())"
}
@IBAction func percentSliderValueChanged(sender: UISlider) {
updateTipPersentLabel()
updateTipResultLabel()
updateTotalLabel()
}
func getTipAmount() -> Float {
let percent = floor(tipPercentSlider.value)
return getAmount() * (percent / 100)
}
func getAmount() -> Float {
guard var amountString = amountTextField.text where amountString.characters.count > 0 else {
return 0
}
amountString = amountString.stringByReplacingOccurrencesOfString("$", withString: "")
if let amount = Float(amountString) {
return amount
} else {
return 0
}
}
func getCalculatedTotal() -> Float {
return getAmount() + getTipAmount()
}
}
// MARK: - UITextFieldDelegate
extension MainViewController : UITextFieldDelegate {
func textFieldDidEndEditing(textField: UITextField) {
textField.text = "\(getAmount().formatWithDefaultValue())"
updateTipPersentLabel()
updateTipResultLabel()
updateTotalLabel()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.endEditing(true)
return true
}
}
| mit |
lrosa007/ghoul | gool/GPRDataFileWriter.swift | 2 | 997 | //
// GPRDataFileWriter.swift
// gool
//
// Allows writing raw/processed GPR data (without session info) to file.
//
// Copyright © 2016 Dead Squad. All rights reserved.
//
import Foundation
public class GPRDataFileWriter : GPRDataOutput {
public var path: String
init(path: String) {
if(path.isEmpty) {
// rename to a default directory and default name from current time?
}
self.path = path
}
// MARK: GPRDataOutput
func writeGprData(data: [UInt8]) {
//TODO: open file, write short header, then write all data
let outStream = NSOutputStream(toFileAtPath: path, append: false)
if(outStream == nil) {
//handle it
}
outStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outStream!.open()
//TODO: write header
outStream!.write(data, maxLength: data.count)
outStream!.close()
}
} | gpl-2.0 |
delannoyk/SoundcloudSDK | sources/SoundcloudSDK/request/UserRequest.swift | 1 | 17489 | //
// UserRequest.swift
// SoundcloudSDK
//
// Created by Kevin DELANNOY on 25/04/15.
// Copyright (c) 2015 Kevin Delannoy. All rights reserved.
//
import Foundation
extension User {
static let BaseURL = URL(string: "https://api.soundcloud.com/users")!
/**
Loads an user profile
- parameter identifier: The identifier of the user to load
- parameter completion: The closure that will be called when user profile is loaded or upon error
*/
@discardableResult
public static func user(identifier: Int, completion: @escaping (SimpleAPIResponse<User>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(SimpleAPIResponse(error: .credentialsNotSet))
return nil
}
let url = BaseURL.appendingPathComponent("\(identifier).json")
let parameters = ["client_id": clientIdentifier]
let request = Request(url: url, method: .get, parameters: parameters, parse: {
if let user = User(JSON: $0) {
return .success(user)
}
return .failure(.parsing)
}) { result in
completion(SimpleAPIResponse(result: result))
}
request.start()
return request
}
/**
Search users that fit requested name.
- parameter query: The query to run.
- parameter completion: The closure that will be called when users are loaded or upon error.
*/
@discardableResult
public static func search(query: String, completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return nil
}
let parse = { (JSON: JSONObject) -> Result<[User], SoundcloudError> in
guard let users = JSON.flatMap(transform: { User(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(users)
}
let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true", "q": query]
let request = Request(url: BaseURL, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<User>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
/**
Loads tracks the user uploaded to Soundcloud
- parameter completion: The closure that will be called when tracks are loaded or upon error
*/
@discardableResult
public func tracks(completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? {
return User.tracks(from: identifier, completion: completion)
}
/**
Loads tracks the user uploaded to Soundcloud
- parameter userIdentifier: The identifier of the user to load
- parameter completion: The closure that will be called when tracks are loaded or upon error
*/
@discardableResult
public static func tracks(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return nil
}
let url = BaseURL.appendingPathComponent("\(userIdentifier)/tracks.json")
var parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"]
#if !os(tvOS)
if let oauthToken = SoundcloudClient.session?.accessToken {
parameters["oauth_token"] = oauthToken
}
#endif
let parse = { (JSON: JSONObject) -> Result<[Track], SoundcloudError> in
guard let tracks = JSON.flatMap(transform: { Track(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(tracks)
}
let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Track>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
/**
Load all comments from the user
- parameter completion: The closure that will be called when the comments are loaded or upon error
*/
@discardableResult
public func comments(completion: @escaping (PaginatedAPIResponse<Comment>) -> Void) -> CancelableOperation? {
return User.comments(from: identifier, completion: completion)
}
/**
Load all comments from the user
- parameter userIdentifier: The user identifier
- parameter completion: The closure that will be called when the comments are loaded or upon error
*/
@discardableResult
public static func comments(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Comment>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return nil
}
let url = BaseURL.appendingPathComponent("\(userIdentifier)/comments.json")
let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"]
let parse = { (JSON: JSONObject) -> Result<[Comment], SoundcloudError> in
guard let comments = JSON.flatMap(transform: { Comment(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(comments)
}
let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Comment>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
/**
Loads favorited tracks of the user
- parameter completion: The closure that will be called when tracks are loaded or upon error
*/
@discardableResult
public func favorites(completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? {
return User.favorites(from: identifier, completion: completion)
}
/**
Loads favorited tracks of the user
- parameter userIdentifier: The user identifier
- parameter completion: The closure that will be called when tracks are loaded or upon error
*/
@discardableResult
public static func favorites(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Track>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return nil
}
let url = BaseURL.appendingPathComponent("\(userIdentifier)/favorites.json")
let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"]
let parse = { (JSON: JSONObject) -> Result<[Track], SoundcloudError> in
guard let tracks = JSON.flatMap(transform: { Track(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(tracks)
}
let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Track>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
/**
Loads followers of the user
- parameter completion: The closure that will be called when followers are loaded or upon error
*/
@discardableResult
public func followers(completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? {
return User.followers(from: identifier, completion: completion)
}
/**
Loads followers of the user
- parameter userIdentifier: The user identifier
- parameter completion: The closure that will be called when followers are loaded or upon error
*/
@discardableResult
public static func followers(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return nil
}
let url = User.BaseURL.appendingPathComponent("\(userIdentifier)/followers.json")
let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"]
let parse = { (JSON: JSONObject) -> Result<[User], SoundcloudError> in
guard let users = JSON.flatMap(transform: { User(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(users)
}
let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<User>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
/**
Loads followed users of the user
- parameter completion: The closure that will be called when followed users are loaded or upon error
*/
@discardableResult
public func followings(completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? {
return User.followings(from: identifier, completion: completion)
}
/**
Loads followed users of the user
- parameter userIdentifier: The user identifier
- parameter completion: The closure that will be called when followed users are loaded or upon error
*/
@discardableResult
public static func followings(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<User>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return nil
}
let url = User.BaseURL.appendingPathComponent("\(userIdentifier)/followings.json")
let parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"]
let parse = { (JSON: JSONObject) -> Result<[User], SoundcloudError> in
guard let users = JSON.flatMap(transform: { User(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(users)
}
let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<User>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
/**
Follow the given user.
**This method requires a Session.**
- parameter userIdentifier: The identifier of the user to follow
- parameter completion: The closure that will be called when the user has been followed or upon error
*/
@discardableResult
@available(tvOS, unavailable)
public func follow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? {
#if !os(tvOS)
return User.changeFollowStatus(follow: true, userIdentifier: userIdentifier, completion: completion)
#else
return nil
#endif
}
/**
Follow the given user.
**This method requires a Session.**
- parameter userIdentifier: The identifier of the user to follow
- parameter completion: The closure that will be called when the user has been followed or upon error
*/
@discardableResult
@available(tvOS, unavailable)
public static func follow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? {
#if !os(tvOS)
return User.changeFollowStatus(follow: true, userIdentifier: userIdentifier, completion: completion)
#else
return nil
#endif
}
/**
Unfollow the given user.
**This method requires a Session.**
- parameter userIdentifier: The identifier of the user to unfollow
- parameter completion: The closure that will be called when the user has been unfollowed or upon error
*/
@discardableResult
@available(tvOS, unavailable)
public func unfollow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? {
#if !os(tvOS)
return User.changeFollowStatus(follow: false, userIdentifier: userIdentifier, completion: completion)
#else
return nil
#endif
}
/**
Unfollow the given user.
**This method requires a Session.**
- parameter userIdentifier: The identifier of the user to unfollow
- parameter completion: The closure that will be called when the user has been unfollowed or upon error
*/
@discardableResult
@available(tvOS, unavailable)
public static func unfollow(userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? {
#if !os(tvOS)
return User.changeFollowStatus(follow: false, userIdentifier: userIdentifier, completion: completion)
#else
return nil
#endif
}
@available(tvOS, unavailable)
private static func changeFollowStatus(follow: Bool, userIdentifier: Int, completion: @escaping (SimpleAPIResponse<Bool>) -> Void) -> CancelableOperation? {
#if !os(tvOS)
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(SimpleAPIResponse(error: .credentialsNotSet))
return nil
}
guard let oauthToken = SoundcloudClient.session?.accessToken else {
completion(SimpleAPIResponse(error: .needsLogin))
return nil
}
let parameters = ["client_id": clientIdentifier, "oauth_token": oauthToken]
let url = BaseURL
.deletingLastPathComponent()
.appendingPathComponent("me/followings/\(userIdentifier).json")
.appendingQueryString(parameters.queryString)
let request = Request(url: url, method: follow ? .put : .delete, parameters: nil, parse: { _ in
return .success(true)
}) { result in
completion(SimpleAPIResponse(result: result))
}
request.start()
return request
#else
return nil
#endif
}
/**
Loads user's playlists
- parameter completion: The closure that will be called when playlists has been loaded or upon error
*/
@discardableResult
public func playlists(completion: @escaping (PaginatedAPIResponse<Playlist>) -> Void) -> CancelableOperation? {
return User.playlists(from: identifier, completion: completion)
}
/**
Loads user's playlists
- parameter userIdentifier: The identifier of the user to unfollow
- parameter completion: The closure that will be called when playlists has been loaded or upon error
*/
@discardableResult
public static func playlists(from userIdentifier: Int, completion: @escaping (PaginatedAPIResponse<Playlist>) -> Void) -> CancelableOperation? {
guard let clientIdentifier = SoundcloudClient.clientIdentifier else {
completion(PaginatedAPIResponse(error: .credentialsNotSet))
return nil
}
let url = BaseURL.appendingPathComponent("\(userIdentifier)/playlists.json")
var parameters = ["client_id": clientIdentifier, "linked_partitioning": "true"]
#if !os(tvOS)
if let oauthToken = SoundcloudClient.session?.accessToken {
parameters["oauth_token"] = oauthToken
}
#endif
let parse = { (JSON: JSONObject) -> Result<[Playlist], SoundcloudError> in
guard let playlists = JSON.flatMap(transform: { Playlist(JSON: $0) }) else {
return .failure(.parsing)
}
return .success(playlists)
}
let request = Request(url: url, method: .get, parameters: parameters, parse: { JSON -> Result<PaginatedAPIResponse<Playlist>, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
}
| mit |
slightair/SwiftGraphics | SwiftGraphics/Quartz/CGColor.swift | 3 | 3533 | //
// CGColor.swift
// SwiftGraphics
//
// Created by Jonathan Wight on 1/12/15.
// Copyright (c) 2015 schwa.io. All rights reserved.
//
import CoreGraphics
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension CGColor: CustomStringConvertible {
public var description: String {
return CFCopyDescription(self) as String
}
}
public extension CGColor {
public var alpha: CGFloat {
return CGColorGetAlpha(self)
}
}
public extension CGColor {
class func color(colorSpace colorSpace: CGColorSpace, components: [CGFloat]) -> CGColor! {
return components.withUnsafeBufferPointer {
(buffer: UnsafeBufferPointer<CGFloat>) -> CGColor! in
return CGColorCreate(colorSpace, buffer.baseAddress)
}
}
class func color(red red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1.0) -> CGColor! {
#if os(OSX)
return NSColor(deviceRed: red, green: green, blue: blue, alpha: alpha).CGColor
#else
return UIColor(red: red, green: green, blue: blue, alpha: alpha).CGColor
#endif
}
class func color(white white: CGFloat, alpha: CGFloat = 1.0) -> CGColor! {
#if os(OSX)
return NSColor(deviceWhite: white, alpha: alpha).CGColor
#else
return UIColor(white: white, alpha: alpha).CGColor
#endif
}
class func color(hue hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) -> CGColor! {
#if os(OSX)
return NSColor(deviceHue: hue, saturation: saturation, brightness: brightness, alpha: alpha).CGColor
#else
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha).CGColor
#endif
}
}
public extension CGColor {
func withAlpha(alpha: CGFloat) -> CGColor {
return CGColorCreateCopyWithAlpha(self, alpha)!
}
}
public extension CGColorSpace {
#if os(OSX)
var name: String {
return CGColorSpaceCopyName(self) as! String
}
#endif
}
public extension CGColor {
var colorSpace: CGColorSpaceRef {
return CGColorGetColorSpace(self)!
}
// There's a possibility that these colours dont match UIColor's or NSColor's version (although they are taken from the NSColor header file)
class func blackColor() -> CGColor { return CGColor.color(white: 0) }
class func darkGrayColor() -> CGColor { return CGColor.color(white: 0.333) }
class func lightGrayColor() -> CGColor { return CGColor.color(white: 0.667) }
class func whiteColor() -> CGColor { return CGColor.color(white: 1) }
class func grayColor() -> CGColor { return CGColor.color(white: 0.5) }
class func redColor() -> CGColor { return CGColor.color(red: 1, green: 0, blue: 0) }
class func greenColor() -> CGColor { return CGColor.color(red: 0, green: 1, blue: 0) }
class func blueColor() -> CGColor { return CGColor.color(red: 0, green: 0, blue: 1) }
class func cyanColor() -> CGColor { return CGColor.color(red: 0, green: 1, blue: 1) }
class func yellowColor() -> CGColor { return CGColor.color(red: 1, green: 1, blue: 0) }
class func magnetaColor() -> CGColor { return CGColor.color(red: 0, green: 1, blue: 1) }
class func orangeColor() -> CGColor { return CGColor.color(red: 1, green: 0.5, blue: 0) }
class func purpleColor() -> CGColor { return CGColor.color(red: 0.5, green: 0.0, blue: 0.5) }
class func brownColor() -> CGColor { return CGColor.color(red: 0.6, green: 0.4, blue: 0.2) }
class func clearColor() -> CGColor { return CGColor.color(white: 0.0, alpha: 0.0) }
}
| bsd-2-clause |
aidenluo177/Weather-Swift | Weather/WeatherTests/WeatherTests.swift | 1 | 893 | //
// WeatherTests.swift
// WeatherTests
//
// Created by aidenluo on 15/7/22.
// Copyright (c) 2015年 36kr. All rights reserved.
//
import UIKit
import XCTest
class WeatherTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
Allow2CEO/browser-ios | brave/src/frontend/PinController.swift | 1 | 17472 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Foundation
import Shared
import LocalAuthentication
import SwiftKeychainWrapper
import AudioToolbox
public let KeychainKeyPinLockInfo = "pinLockInfo"
struct PinUX {
fileprivate static var ButtonSize: CGSize {
let size = DeviceDetector.iPhone4s ? 60 : 80
return CGSize(width: size, height: size)
}
fileprivate static let DefaultForegroundColor = UIColor(rgb: 0x4a4a4a)
fileprivate static let DefaultBackgroundColor = UIColor(rgb: 0x4a4a4a).withAlphaComponent(0.1)
fileprivate static let SelectedBackgroundColor = BraveUX.BraveOrange
fileprivate static let DefaultBorderWidth: CGFloat = 0.0
fileprivate static let SelectedBorderWidth: CGFloat = 0.0
fileprivate static let DefaultBorderColor = UIColor(rgb: 0x4a4a4a).cgColor
fileprivate static let IndicatorSize: CGSize = CGSize(width: 14, height: 14)
fileprivate static let IndicatorSpacing: CGFloat = 17.0
}
protocol PinViewControllerDelegate {
func pinViewController(_ completed: Bool) -> Void
}
class PinViewController: UIViewController, PinViewControllerDelegate {
var delegate: PinViewControllerDelegate?
var pinView: PinLockView!
static var isBrowserLockEnabled: Bool {
let profile = getApp().profile
return profile?.prefs.boolForKey(kPrefKeySetBrowserLock) == true || profile?.prefs.boolForKey(kPrefKeyPopupForBrowserLock) == true
}
override func loadView() {
super.loadView()
pinView = PinLockView(message: Strings.PinNew)
pinView.codeCallback = { code in
let view = ConfirmPinViewController()
view.delegate = self
view.initialPin = code
self.navigationController?.pushViewController(view, animated: true)
}
view.addSubview(pinView)
let pinViewSize = pinView.frame.size
pinView.snp.makeConstraints { (make) in
make.size.equalTo(pinViewSize)
make.centerX.equalTo(self.view.center).offset(0)
let offset = UIScreen.main.bounds.height < 667 ? 30 : 0
make.centerY.equalTo(self.view.center).offset(offset)
}
title = Strings.PinSet
view.backgroundColor = UIColor(rgb: 0xF8F8F8)
}
func pinViewController(_ completed: Bool) {
delegate?.pinViewController(completed)
}
}
class ConfirmPinViewController: UIViewController {
var delegate: PinViewControllerDelegate?
var pinView: PinLockView!
var initialPin: String = ""
override func loadView() {
super.loadView()
pinView = PinLockView(message: Strings.PinNewRe)
pinView.codeCallback = { code in
if code == self.initialPin {
let pinLockInfo = AuthenticationKeychainInfo(passcode: code)
if LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
pinLockInfo.useTouchID = true
}
KeychainWrapper.setPinLockInfo(pinLockInfo)
self.delegate?.pinViewController(true)
self.navigationController?.popToRootViewController(animated: true)
}
else {
self.pinView.tryAgain()
}
}
view.addSubview(pinView)
let pinViewSize = pinView.frame.size
pinView.snp.makeConstraints { (make) in
make.size.equalTo(pinViewSize)
make.centerX.equalTo(self.view.center).offset(0)
let offset = UIScreen.main.bounds.height < 667 ? 30 : 0
make.centerY.equalTo(self.view.center).offset(offset)
}
title = Strings.PinSet
view.backgroundColor = UIColor(rgb: 0xF8F8F8)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.Cancel, style: .plain, target: self, action: #selector(SEL_cancel))
}
func SEL_cancel() {
navigationController?.popToRootViewController(animated: true)
delegate?.pinViewController(false)
}
}
class PinProtectOverlayViewController: UIViewController {
var blur: UIVisualEffectView!
var pinView: PinLockView!
var touchCanceled: Bool = false
var successCallback: ((_ success: Bool) -> Void)?
var attempts: Int = 0
override func loadView() {
super.loadView()
blur = UIVisualEffectView(effect: UIBlurEffect(style: .light))
view.addSubview(blur)
pinView = PinLockView(message: Strings.PinEnterToUnlock)
pinView.codeCallback = { code in
if let pinLockInfo = KeychainWrapper.pinLockInfo() {
if code == pinLockInfo.passcode {
self.successCallback?(true)
self.pinView.reset()
}
else {
self.successCallback?(false)
self.attempts += 1
self.pinView.tryAgain()
}
}
}
view.addSubview(pinView)
let pinViewSize = pinView.frame.size
pinView.snp.makeConstraints { (make) in
make.size.equalTo(pinViewSize)
make.center.equalTo(self.view.center).offset(0)
}
blur.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
start()
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override var shouldAutorotate : Bool {
return false
}
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
func start() {
getApp().browserViewController.view.endEditing(true)
pinView.isHidden = true
touchCanceled = false
}
func auth() {
if touchCanceled {
return
}
var authError: NSError? = nil
let authenticationContext = LAContext()
if authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
authenticationContext.evaluatePolicy(
.deviceOwnerAuthenticationWithBiometrics,
localizedReason: Strings.PinFingerprintUnlock,
reply: { [unowned self] (success, error) -> Void in
if success {
self.successCallback?(true)
}
else {
self.touchCanceled = true
postAsyncToMain {
self.pinView.isHidden = false
}
}
})
}
else {
self.touchCanceled = true
postAsyncToMain {
self.pinView.isHidden = false
}
}
}
}
class PinLockView: UIView {
var buttons: [PinButton] = []
var codeCallback: ((_ code: String) -> Void)?
var messageLabel: UILabel!
var pinIndicatorView: PinIndicatorView!
var deleteButton: UIButton!
var pin: String = ""
convenience init(message: String) {
self.init()
messageLabel = UILabel()
messageLabel.text = message
messageLabel.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium)
messageLabel.textColor = PinUX.DefaultForegroundColor
messageLabel.sizeToFit()
addSubview(messageLabel)
pinIndicatorView = PinIndicatorView(size: 4)
pinIndicatorView.sizeToFit()
pinIndicatorView.index(0)
addSubview(pinIndicatorView)
for i in 1...10 {
let button = PinButton()
button.tag = i
button.titleLabel.text = i == 10 ? "0" : "\(i)"
button.addTarget(self, action: #selector(SEL_pinButton(_:)), for: .touchUpInside)
addSubview(button)
buttons.append(button)
}
deleteButton = UIButton()
deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium)
deleteButton.setTitle(Strings.Delete, for: .normal)
deleteButton.setTitleColor(PinUX.DefaultForegroundColor, for: .normal)
deleteButton.setTitleColor(BraveUX.GreyJ, for: .highlighted)
deleteButton.addTarget(self, action: #selector(SEL_delete(_:)), for: .touchUpInside)
deleteButton.sizeToFit()
addSubview(deleteButton)
layoutSubviews()
sizeToFit()
}
override func layoutSubviews() {
let spaceX: CGFloat = (min(350, UIScreen.main.bounds.width) - PinUX.ButtonSize.width * 3) / 4
// Special care for iPhone 4s to make all elements fit on screen.
let spaceY: CGFloat = DeviceDetector.iPhone4s ? spaceX - 20 : spaceX
let w: CGFloat = PinUX.ButtonSize.width
let h: CGFloat = PinUX.ButtonSize.height
let frameWidth = spaceX * 2 + w * 3
var messageLabelFrame = messageLabel.frame
messageLabelFrame.origin.x = (frameWidth - messageLabelFrame.width) / 2
messageLabelFrame.origin.y = 0
messageLabel.frame = messageLabelFrame
var indicatorViewFrame = pinIndicatorView.frame
indicatorViewFrame.origin.x = (frameWidth - indicatorViewFrame.width) / 2
indicatorViewFrame.origin.y = messageLabelFrame.maxY + 18
pinIndicatorView.frame = indicatorViewFrame
var x: CGFloat = 0
var y: CGFloat = indicatorViewFrame.maxY + spaceY
for i in 0..<buttons.count {
if i == buttons.count - 1 {
// Center last.
x = (frameWidth - w) / 2
}
let button = buttons[i]
var buttonFrame = button.frame
buttonFrame.origin.x = rint(x)
buttonFrame.origin.y = rint(y)
buttonFrame.size.width = w
buttonFrame.size.height = h
button.frame = buttonFrame
x = x + w + spaceX
if x > frameWidth {
x = 0
y = y + h + spaceY
}
}
let button0 = viewWithTag(10)
let button9 = viewWithTag(9)
var deleteButtonFrame = deleteButton.frame
deleteButtonFrame.center = CGPoint(x: rint((button9?.frame ?? CGRect.zero).midX), y: rint((button0?.frame ?? CGRect.zero).midY))
deleteButton.frame = deleteButtonFrame
}
override func sizeToFit() {
let button0 = buttons[buttons.count - 1]
let button9 = buttons[buttons.count - 2]
let w = button9.frame.maxX
let h = button0.frame.maxY
var f = bounds
f.size.width = w
f.size.height = h
frame = f
bounds = CGRect(x: 0, y: 0, width: w, height: h)
}
func SEL_pinButton(_ sender: UIButton) {
if pin.characters.count < 4 {
let value = sender.tag == 10 ? 0 : sender.tag
pin = pin + "\(value)"
}
pinIndicatorView.index(pin.characters.count)
if pin.characters.count == 4 && codeCallback != nil {
codeCallback!(pin)
}
}
func SEL_delete(_ sender: UIButton) {
if pin.characters.count > 0 {
pin = pin.substring(to: pin.characters.index(pin.endIndex, offsetBy: -1))
pinIndicatorView.index(pin.characters.count)
}
}
func reset() {
pinIndicatorView.index(0)
pin = ""
}
func tryAgain() {
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.06
animation.repeatCount = 3
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: pinIndicatorView.frame.midX - 10, y: pinIndicatorView.frame.midY))
animation.toValue = NSValue(cgPoint: CGPoint(x: pinIndicatorView.frame.midX + 10, y: pinIndicatorView.frame.midY))
pinIndicatorView.layer.add(animation, forKey: "position")
self.perform(#selector(reset), with: self, afterDelay: 0.4)
}
}
class PinIndicatorView: UIView {
var indicators: [UIView] = []
var defaultColor: UIColor!
convenience init(size: Int) {
self.init()
defaultColor = PinUX.DefaultForegroundColor
for i in 0..<size {
let view = UIView()
view.tag = i
view.layer.cornerRadius = PinUX.IndicatorSize.width / 2
view.layer.masksToBounds = true
view.layer.borderWidth = 1
view.layer.borderColor = defaultColor.cgColor
view.backgroundColor = PinUX.DefaultBackgroundColor
addSubview(view)
indicators.append(view)
}
setNeedsDisplay()
layoutIfNeeded()
}
override func layoutSubviews() {
let spaceX: CGFloat = PinUX.IndicatorSpacing
var x: CGFloat = 0
for i in 0..<indicators.count {
let view = indicators[i]
var viewFrame = view.frame
viewFrame.origin.x = x
viewFrame.origin.y = 0
viewFrame.size.width = PinUX.IndicatorSize.width
viewFrame.size.height = PinUX.IndicatorSize.height
view.frame = viewFrame
x = x + PinUX.IndicatorSize.width + spaceX
}
}
override func sizeToFit() {
let view = indicators[indicators.count - 1]
var f = frame
f.size.width = view.frame.maxX
f.size.height = view.frame.maxY
frame = f
}
func index(_ index: Int) -> Void {
if index > indicators.count {
return
}
// Fill
for i in 0..<index {
let view = indicators[i]
view.backgroundColor = PinUX.SelectedBackgroundColor
view.layer.borderColor = PinUX.SelectedBackgroundColor.cgColor
}
// Clear additional
if index < indicators.count {
for i in index..<indicators.count {
let view = indicators[i]
view.layer.borderWidth = PinUX.DefaultBorderWidth
view.layer.borderColor = PinUX.DefaultBorderColor
view.backgroundColor = PinUX.DefaultBackgroundColor
}
}
// Outline next
if index < indicators.count {
let view = indicators[index]
view.layer.borderWidth = 2
}
}
}
class PinButton: UIControl {
var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
layer.masksToBounds = true
layer.borderWidth = PinUX.DefaultBorderWidth
layer.borderColor = PinUX.DefaultBorderColor
backgroundColor = PinUX.DefaultBackgroundColor
titleLabel = UILabel(frame: frame)
titleLabel.isUserInteractionEnabled = false
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 30, weight: UIFontWeightMedium)
titleLabel.textColor = PinUX.DefaultForegroundColor
titleLabel.backgroundColor = UIColor.clear
addSubview(titleLabel)
setNeedsDisplay()
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
override var isHighlighted: Bool {
didSet {
if (isHighlighted) {
backgroundColor = PinUX.SelectedBackgroundColor
titleLabel.textColor = UIColor.white
layer.borderColor = PinUX.SelectedBackgroundColor.cgColor
}
else {
backgroundColor = PinUX.DefaultBackgroundColor
titleLabel.textColor = PinUX.DefaultForegroundColor
layer.borderColor = PinUX.DefaultBorderColor
}
}
}
override func layoutSubviews() {
titleLabel.frame = bounds
layer.cornerRadius = frame.height / 2.0
}
override func sizeToFit() {
super.sizeToFit()
var frame: CGRect = self.frame
frame.size.width = PinUX.ButtonSize.width
frame.size.height = PinUX.ButtonSize.height
self.frame = frame
}
}
extension KeychainWrapper {
class func pinLockInfo() -> AuthenticationKeychainInfo? {
NSKeyedUnarchiver.setClass(AuthenticationKeychainInfo.self, forClassName: "AuthenticationKeychainInfo")
return KeychainWrapper.standard.object(forKey: KeychainKeyPinLockInfo) as? AuthenticationKeychainInfo
}
class func setPinLockInfo(_ info: AuthenticationKeychainInfo?) {
NSKeyedArchiver.setClassName("AuthenticationKeychainInfo", for: AuthenticationKeychainInfo.self)
if let info = info {
KeychainWrapper.standard.set(info, forKey: KeychainKeyPinLockInfo)
} else {
KeychainWrapper.standard.removeObject(forKey: KeychainKeyPinLockInfo)
}
}
}
| mpl-2.0 |
emiledecosterd/Reachability | Reachability/Controllers/ReachabilityController.swift | 1 | 6641 | /*
* Copyright (c) 2016 Emile Décosterd
*
* 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
// MARK: Base class
// MARK: -
///A class that takes care of everything related to the internet reachability
final class ReachabilityController {
// MARK: Properties
//Model
fileprivate var reachabilityManager: ReachabilityManager
fileprivate var banner: ReachabilityBanner! = nil{ // Created at initialisation
didSet{
showBannerForSeconds(3)
}
}
// Views
fileprivate unowned var view: UIView
fileprivate let bannerView: BannerView
public var shouldShowBanner: Bool = true // Set this to false if you do not want the banner to show
// Helpers
fileprivate var bannerWidth: CGFloat {
return UIScreen.main.bounds.size.width
}
fileprivate var bannerHeight = CGFloat(44)
// MARK: Initialisation
/**
* Instanciates a `ReachabilityController`.
*
* - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view.
*/
init(view: UIView){
// Setup views
self.view = view
let bannerViewFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0)
bannerView = BannerView(frame: bannerViewFrame)
// Setup manager
reachabilityManager = ReachabilityManager()
reachabilityManager.delegate = self
reachabilityManager.startMonitoring()
banner = ReachabilityBanner(status: reachabilityManager.status)
if banner.status != .wifi {
showBannerForSeconds(3)
}
// Respond to orientation changes
NotificationCenter.default.addObserver(self, selector: #selector(ReachabilityController.orientationChanged(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
/**
* Instanciates a `ReachabilityController`.
*
* - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view.
* - Parameter wifiOnly: If we want to be informed when we use cellular connection instead of wifi.
*/
convenience init(view: UIView, wifiOnly: Bool){
self.init(view:view)
reachabilityManager.wifiOnly = true
}
/**
* Instanciates a `ReachabilityController`.
*
* - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view.
* - Parameter statusBar: If the view contains the status bar, set `statusBar` to `true`.
*/
convenience init(view: UIView, statusBar: Bool){
self.init(view: view)
if statusBar {
bannerHeight = CGFloat(64)
}
}
/**
* Instanciates a `ReachabilityController`.
*
* - Parameter view: The view in which to show a banner view when reachability changes. The banner will be displayed on the top of this view.
* - Parameter wifiOnly: If we want to be informed when we use cellular connection instead of wifi.
* - Parameter statusBar: If the view contains the status bar, set `statusBar` to `true`.
*/
convenience init(view: UIView, wifiOnly: Bool, statusBar: Bool){
self.init(view: view, wifiOnly: wifiOnly)
if statusBar{
bannerHeight = CGFloat(64)
}
}
deinit{
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
// MARK: Show and hide banner depending on reachability changes
fileprivate func showBannerForSeconds(_ duration: TimeInterval){
// In case you do not want the banner to be shown to the user
if !shouldShowBanner {return}
// Show the view with animation
bannerView.setupView(banner)
view.addSubview(bannerView)
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.9,
initialSpringVelocity: 1,
options: [.allowUserInteraction, .beginFromCurrentState],
animations: {
self.bannerView.changeFrame(CGRect(x: 0, y: 0, width: self.bannerWidth, height: self.bannerHeight))
}, completion: { (done) in
// Hide it after 2 sec
Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(ReachabilityController.timerFinished(_:)), userInfo: true, repeats: false)
})
}
@objc fileprivate func timerFinished(_ timer: Timer){
timer.invalidate()
hideBanner(true)
}
fileprivate func hideBanner(_ animated: Bool){
// If no banner was to be shown, there will be no views to remove
if !shouldShowBanner {return}
if animated {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.bannerView.changeFrame(CGRect(x: 0, y: 0, width: self.bannerWidth, height: 0))
}, completion: { (ok) in
self.bannerView.removeFromSuperview()
})
}else{
bannerView.removeFromSuperview()
}
}
@objc fileprivate func orientationChanged(_ notification: Notification){
self.view.layoutIfNeeded()
}
}
// MARK: - ReachabilityDelegate
// MARK: -
/// An extension of `ReachabilityController` to conform to `ReachabilityManager`'s delegate protocol
extension ReachabilityController: ReachabilityDelegate {
func reachabilityStatusChanged(_ status: NetworkStatus) {
banner = ReachabilityBanner(status: status)
}
}
| mit |
IsaScience/ListerAProductivityAppObj-CandSwift | original-src/ListerAProductivityAppObj-CandSwift/Swift/ListerOSX/ListTableView.swift | 1 | 622 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListTableView` class is an NSTableView subclass that ensures that the text field is always the first responder for an event.
*/
import Cocoa
class ListTableView: NSTableView {
override func validateProposedFirstResponder(responder: NSResponder, forEvent: NSEvent) -> Bool {
if responder is NSTextField {
return true
}
return super.validateProposedFirstResponder(responder, forEvent: forEvent)
}
}
| apache-2.0 |
suifengqjn/swiftDemo | Sina/Sina/Sina/AppDelegate.swift | 1 | 2364 | //
// AppDelegate.swift
// Sina
//
// Created by qianjn on 16/7/27.
// Copyright © 2016年 SF. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main().bounds)
window?.backgroundColor = UIColor.white()
window?.rootViewController = SNRootController()
window?.makeKeyAndVisible()
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 active 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:.
}
}
| apache-2.0 |
Trioser/Calculator | Calculator/AppDelegate.swift | 1 | 2055 | //
// AppDelegate.swift
// Calculator
//
// Created by Richard E Millet on 1/28/15.
// Copyright (c) 2015 remillet. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:.
}
}
| apache-2.0 |
shohei/firefox-ios | Storage/MockLogins.swift | 1 | 3893 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
public class MockLogins: BrowserLogins, SyncableLogins {
private var cache = [Login]()
public init(files: FileAccessor) {
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Result<Cursor<LoginData>>> {
let cursor = ArrayCursor(data: cache.filter({ login in
return login.protectionSpace.host == protectionSpace.host
}).sorted({ (loginA, loginB) -> Bool in
return loginA.timeLastUsed > loginB.timeLastUsed
}).map({ login in
return login as LoginData
}))
return Deferred(value: Result(success: cursor))
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Result<Cursor<LoginData>>> {
let cursor = ArrayCursor(data: cache.filter({ login in
return login.protectionSpace.host == protectionSpace.host &&
login.username == username
}).sorted({ (loginA, loginB) -> Bool in
return loginA.timeLastUsed > loginB.timeLastUsed
}).map({ login in
return login as LoginData
}))
return Deferred(value: Result(success: cursor))
}
// This method is only here for testing
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Result<LoginUsageData>> {
let res = cache.filter({ login in
return login.guid == guid
}).sorted({ (loginA, loginB) -> Bool in
return loginA.timeLastUsed > loginB.timeLastUsed
})[0] as LoginUsageData
return Deferred(value: Result(success: res))
}
public func addLogin(login: LoginData) -> Success {
if let index = find(cache, login as! Login) {
return deferResult(LoginDataError(description: "Already in the cache"))
}
cache.append(login as! Login)
return succeed()
}
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
// TODO
return succeed()
}
public func updateLogin(login: LoginData) -> Success {
if let index = find(cache, login as! Login) {
cache[index].timePasswordChanged = NSDate.nowMicroseconds()
return succeed()
}
return deferResult(LoginDataError(description: "Password wasn't cached yet. Can't update"))
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
if let login = cache.filter({ $0.guid == guid }).first {
login.timeLastUsed = NSDate.nowMicroseconds()
return succeed()
}
return deferResult(LoginDataError(description: "Password wasn't cached yet. Can't update"))
}
public func removeLoginByGUID(guid: GUID) -> Success {
let filtered = cache.filter { $0.guid != guid }
if filtered.count == cache.count {
return deferResult(LoginDataError(description: "Can not remove a password that wasn't stored"))
}
cache = filtered
return succeed()
}
public func removeAll() -> Success {
cache.removeAll(keepCapacity: false)
return succeed()
}
// TODO
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { return succeed() }
public func applyChangedLogin(upstream: Login, timestamp: Timestamp) -> Success { return succeed() }
public func markAsSynchronized([GUID], modified: Timestamp) -> Deferred<Result<Timestamp>> { return deferResult(0) }
public func markAsDeleted(guids: [GUID]) -> Success { return succeed() }
public func onRemovedAccount() -> Success { return succeed() }
} | mpl-2.0 |
inder/ios-ranking-visualization | RankViz/RankViz/MetricsManager.swift | 1 | 3514 | //
// MetricsManager.swift
// Reverse Graph
//
// Created by Inder Sabharwal on 1/6/15.
// Copyright (c) 2015 truquity. All rights reserved.
//
import Foundation
class MetricsMgr {
class var sharedInstance: MetricsMgr {
struct Static {
static let instance: MetricsMgr = MetricsMgr()
}
return Static.instance
}
//metrics group name -> display order
var _metricsGroups: [String] = []
var _stdMetrics: [String:[MetricMetaInformation]] = [:]
var _allMetrics: [String:MetricMetaInformation] = [:]
var numSections: Int {
return _metricsGroups.count
}
var metricsGroups: [String] {
return _metricsGroups
}
func getMetricMetaListForSection(let section: Int) -> [MetricMetaInformation]? {
if (section >= _metricsGroups.count) {
return []
}
return _stdMetrics[_metricsGroups[section]]
}
func getMetricMeta(let section: Int, let row: Int) -> MetricMetaInformation? {
var metrics = getMetricMetaListForSection(section)
return metrics?[row]
}
func getMetricMeta(byName name: String) -> MetricMetaInformation? {
if (_allMetrics[name] == nil) {
println("Metric NOT FOUND \(name)")
}
return _allMetrics[name]
}
//price/earnings
let PE = MetricMetaInformation(name: "PE Ratio", importance: 2, isHigherBetter: false)
//price/book
let PB = MetricMetaInformation(name: "PB Ratio", importance: 2, isHigherBetter: false)
//deb/equity
let DEQ = MetricMetaInformation(name: "Debt/Equity", importance: 2, isHigherBetter: false)
//free cash flow
let FCF = MetricMetaInformation(name: "FCF", importance: 2, isHigherBetter: true)
//PEG Ratio - i am assigning more importance to this metric than others!
let PEG = MetricMetaInformation(name: "PEG", importance: 2, isHigherBetter: false)
let GAIN1M = MetricMetaInformation(name: "Gain 1M", importance: 2, isHigherBetter: true)
let GAIN3M = MetricMetaInformation(name: "Gain 3M", importance: 2, isHigherBetter: true)
let PS = MetricMetaInformation(name: "Price/Rev", importance: 2, isHigherBetter: false)
let VOLUME = MetricMetaInformation(name: "Avg Vol", importance: 2, isHigherBetter: true)
//% change from 50 day moving average.
let PC50 = MetricMetaInformation(name: "%Chg50DMA", importance: 2, isHigherBetter: true)
let PC200 = MetricMetaInformation(name: "%Chg200DMA", importance: 2, isHigherBetter: true)
init() {
_stdMetrics["Popular"] = [PE, GAIN1M, GAIN3M]
_allMetrics[PE.name] = PE
_allMetrics[PEG.name] = PEG
_stdMetrics["Basic"] = [PE, GAIN1M, GAIN3M, PS, VOLUME]
_allMetrics[PS.name] = PS
_allMetrics[VOLUME.name] = VOLUME
_allMetrics[PB.name] = PB
_allMetrics[DEQ.name] = DEQ
_allMetrics[FCF.name] = FCF
_allMetrics[PEG.name] = PEG
_allMetrics[GAIN1M.name] = GAIN1M
_allMetrics[GAIN3M.name] = GAIN3M
_allMetrics[PC50.name] = PC50
_allMetrics[PC200.name] = PC200
_metricsGroups = ["Popular", "Basic"]
}
}
//some code about sorting dictionaries
// func sortMetricsGroups () {
// var arr : [String] = []
// let sortedKeysAndValues = sorted(_metricsGroups) { $0.1 < $1.1 }
// for (k, v) in sortedKeysAndValues {
// arr.append(k)
// }
// _sortedSections = arr
// }
| apache-2.0 |
Acuant/AcuantiOSMobileSDK | Sample-Swift-App/AcuantiOSSDKSwiftSample/ProgressHUD.swift | 2 | 2974 | //
// ProgressHUD.swift
// AcuantiOSSDKSwiftSample
//
// Created by Tapas Behera on 7/28/17.
// Copyright © 2017 Acuant. All rights reserved.
//
import UIKit
class ProgressHUD: UIVisualEffectView {
var text: String? {
didSet {
label.text = text
label.textAlignment = NSTextAlignment.center;
label.numberOfLines = 0;
label.lineBreakMode = .byWordWrapping
label.frame.size.width = 120
label.font = UIFont.systemFont(ofSize: 16.0);
}
}
let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)
let label: UILabel = UILabel()
let blurEffect = UIBlurEffect(style: .light)
let vibrancyView: UIVisualEffectView
init(text: String) {
self.text = text
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
super.init(effect: blurEffect)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
self.text = ""
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
super.init(coder: aDecoder)
self.setup()
}
func setup() {
contentView.addSubview(vibrancyView)
contentView.addSubview(activityIndictor)
contentView.addSubview(label)
activityIndictor.startAnimating()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = self.superview {
let width = superview.frame.size.width / 2.3
let height: CGFloat = 50.0
self.frame = CGRect(x: superview.frame.size.width / 2 - width / 2,
y: superview.frame.height / 2 - height / 2,
width: width,
height: height)
vibrancyView.frame = self.bounds
let activityIndicatorSize: CGFloat = 40
activityIndictor.frame = CGRect(x: 5,
y: height / 2 - activityIndicatorSize / 2,
width: activityIndicatorSize,
height: activityIndicatorSize)
layer.cornerRadius = 8.0
layer.masksToBounds = true
label.text = text
label.textAlignment = NSTextAlignment.center
label.frame = CGRect(x: activityIndicatorSize + 5,
y: 0,
width: width - activityIndicatorSize - 15,
height: height)
label.textColor = UIColor.gray
label.font = UIFont.boldSystemFont(ofSize: 16)
}
}
func show() {
self.isHidden = false
}
func hide() {
self.isHidden = true
}
}
| apache-2.0 |
VigaasVentures/iOSWoocommerceClient | WoocommerceClient/models/FeeLine.swift | 1 | 719 | //
// FeeLine.swift
// WoocommerceClient
//
// Created by Damandeep Singh on 20/02/17.
// Copyright © 2017 Damandeep Singh. All rights reserved.
//
import UIKit
import ObjectMapper
class FeeLine: Mappable {
var id:Int?
var name:String?
var taxClass:String?
var taxStatus:String?
var total:String?
var totalTax:String?
var taxes:[FeeLineTax]?
public required init?(map: Map) {
}
public func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
taxClass <- map["tax_class"]
taxStatus <- map["tax_status"]
total <- map["total"]
totalTax <- map["total_tax"]
taxes <- map["taxes"]
}
}
| mit |
akaralar/siesta | Tests/Functional/TestService.swift | 1 | 278 | //
// TestService.swift
// Siesta
//
// Created by Paul on 2015/8/7.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Siesta
@objc public class TestService: Service
{
public init()
{ super.init(baseURL: "http://example.api") }
}
| mit |
MxABC/oclearning | swiftLearning/Pods/Alamofire/Source/ResponseSerialization.swift | 95 | 13697 | // ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| mit |
franciscocgoncalves/BindViewControllerToView | Example/BindViewControllerToView/ViewController.swift | 1 | 380 | //
// ViewController.swift
// CellViewController
//
// Created by Francisco Gonçalves on 12/19/2015.
// Copyright (c) 2015 Francisco Gonçalves. All rights reserved.
//
import UIKit
import BindViewControllerToView
class ViewController: UIViewController {
@IBOutlet var helloWorld: UILabel!
var model: String? {
didSet {
helloWorld.text = model
}
}
}
| mit |
icemanbsi/BSDropdown | Pod/Classes/BSDropdown.swift | 1 | 33029 | //
// BSDropdown.swift
// V2.0.3
//
// Items selector with a pop up table list view.
// You can use a NSMutableArray of NSDictionary for the data source
//
// Created by Bobby Stenly Irawan ( iceman.bsi@gmail.com - http://bobbystenly.com ) on 11/21/15.
// Copyright © 2015 Bobby Stenly Irawan. All rights reserved.
//
// New in V2.0.3
// - update to swift 3.0.1
//
// New in V2.0.2
// - update to swift 3
//
// New in V1.3
// - change viewController into weak var
//
// New in V1.2
// - added DataSource Protocol for custom tableview cell / layout
// - added fixedDisplayedTitle to make the default title fixed (not change even the selected item has changed)
import Foundation
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
public protocol BSDropdownDelegate {
func onDropdownSelectedItemChange(_ dropdown: BSDropdown, selectedItem: NSDictionary?)
}
extension BSDropdownDelegate {
func onDropdownSelectedItemChange(_ dropdown: BSDropdown, selectedItem: NSDictionary?) {
}
}
public protocol BSDropdownDataSource {
func itemHeightForRowAtIndexPath(_ dropdown: BSDropdown, tableView: UITableView, item: NSDictionary?, indexPath: IndexPath) -> CGFloat
func itemForRowAtIndexPath(_ dropdown: BSDropdown, tableView: UITableView, item: NSDictionary?, indexPath: IndexPath) -> UITableViewCell
}
open class BSDropdown:UIButton, UITableViewDelegate, UITableViewDataSource{
//required attributes
open weak var viewController: UIViewController?
//--end of required attributes
//optional attributes
open var delegate: BSDropdownDelegate!
open var dataSource: BSDropdownDataSource!
open var modalBackgroundColor: UIColor = UIColor(white: 0, alpha: 0.5)
open var selectorBackgroundColor: UIColor = UIColor(white: 1, alpha: 1)
open var headerBackgroundColor: UIColor = UIColor(white: 0, alpha: 1)
open var titleColor: UIColor = UIColor(white: 1, alpha: 1)
open var cancelButtonBackgroundColor: UIColor = UIColor(white: 0, alpha: 0)
open var doneButtonBackgroundColor: UIColor = UIColor(white: 0, alpha: 0)
open var cancelTextColor: UIColor = UIColor(white: 0.8, alpha: 1)
open var doneTextColor: UIColor = UIColor(white: 0.8, alpha: 1)
open var itemTextColor: UIColor = UIColor(white: 0, alpha: 1)
open var itemTintColor: UIColor = UIColor(white: 0, alpha: 0.8)
open var titleFont:UIFont? = UIFont(name: "Helvetica", size: 16)
open var buttonFont:UIFont? = UIFont(name: "Helvetica", size: 13)
open var itemFont:UIFont? = UIFont(name: "Helvetica", size: 13)
open var title: String = "title"
open var cancelButtonTitle: String = "Cancel"
open var doneButtonTitle: String = "Done"
open var defaultTitle: String = "Select Item"
open var titleKey: String = "title"
open var enableSearch: Bool = false
open var searchPlaceholder: String = "Search"
open var fixedDisplayedTitle: Bool = false
open var hideDoneButton: Bool = false
//-- end of optional attributes
fileprivate var selectedIndex: Int = -1
fileprivate var tempSelectedIndex: Int = -1
fileprivate var data: NSMutableArray?
fileprivate var originalData: NSMutableArray?
fileprivate var selectorModalView: UIView!
fileprivate var selectorView: UIView!
fileprivate var selectorHeaderView: UIView!
fileprivate var lblSelectorTitleLabel: UILabel!
fileprivate var btnSelectorCancel: UIButton!
fileprivate var btnSelectorDone: UIButton!
fileprivate var selectorTableView: UITableView!
fileprivate var searchView: UIView!
fileprivate var txtKeyword: UITextField!
open func setup(){
if let vc = self.viewController {
self.selectorModalView = UIView()
self.selectorModalView.backgroundColor = self.modalBackgroundColor
self.selectorModalView.translatesAutoresizingMaskIntoConstraints = false
vc.view.addSubview(self.selectorModalView)
vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: vc.view,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: 0))
vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: vc.view,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 0))
vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: vc.view,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: 0))
vc.view.addConstraint(NSLayoutConstraint(item: self.selectorModalView,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: vc.view,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 0))
self.selectorView = UIView()
self.selectorView.backgroundColor = self.selectorBackgroundColor
self.selectorView.translatesAutoresizingMaskIntoConstraints = false
self.selectorModalView.addSubview(self.selectorView)
self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorModalView,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: 50))
self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorModalView,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: -50))
self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorModalView,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 25))
self.selectorModalView.addConstraint(NSLayoutConstraint(item: self.selectorView,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorModalView,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: -25))
self.selectorHeaderView = UIView()
self.selectorHeaderView.backgroundColor = self.headerBackgroundColor
self.selectorHeaderView.translatesAutoresizingMaskIntoConstraints = false
self.selectorView.addSubview(self.selectorHeaderView)
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorHeaderView,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 56))
self.lblSelectorTitleLabel = UILabel()
self.lblSelectorTitleLabel.text = self.title
self.lblSelectorTitleLabel.textColor = self.titleColor
if let font = self.titleFont {
self.lblSelectorTitleLabel.font = font
}
self.lblSelectorTitleLabel.translatesAutoresizingMaskIntoConstraints = false
self.selectorHeaderView.addSubview(self.lblSelectorTitleLabel)
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.lblSelectorTitleLabel,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.lblSelectorTitleLabel,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0))
self.btnSelectorCancel = UIButton()
self.btnSelectorCancel.setTitle(self.cancelButtonTitle, for: UIControlState())
self.btnSelectorCancel.titleLabel?.textColor = self.cancelTextColor
self.btnSelectorCancel.backgroundColor = self.cancelButtonBackgroundColor
self.btnSelectorCancel.titleLabel?.textAlignment = NSTextAlignment.left
if let font = self.buttonFont {
self.btnSelectorCancel.titleLabel?.font = font
}
self.btnSelectorCancel.translatesAutoresizingMaskIntoConstraints = false
self.selectorHeaderView.addSubview(self.btnSelectorCancel)
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: 8))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: -8))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 8))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 40))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorCancel,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 50))
self.btnSelectorDone = UIButton()
self.btnSelectorDone.setTitle(self.doneButtonTitle, for: UIControlState())
self.btnSelectorDone.titleLabel?.textColor = self.doneTextColor
self.btnSelectorDone.backgroundColor = self.doneButtonBackgroundColor
self.btnSelectorDone.titleLabel?.textAlignment = NSTextAlignment.right
if let font = self.buttonFont {
self.btnSelectorDone.titleLabel?.font = font
}
self.btnSelectorDone.translatesAutoresizingMaskIntoConstraints = false
self.selectorHeaderView.addSubview(self.btnSelectorDone)
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: 8))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: -8))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: -8))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 40))
self.selectorHeaderView.addConstraint(NSLayoutConstraint(item: self.btnSelectorDone,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 50))
if self.enableSearch {
self.searchView = UIView()
self.searchView.translatesAutoresizingMaskIntoConstraints = false
self.selectorView.addSubview(self.searchView)
self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorHeaderView,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.searchView,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 46))
self.txtKeyword = UITextField()
self.txtKeyword.borderStyle = .roundedRect
self.txtKeyword.translatesAutoresizingMaskIntoConstraints = false
self.searchView.addSubview(self.txtKeyword)
self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.searchView,
attribute: NSLayoutAttribute.top,
multiplier: 1,
constant: 8))
self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: self.searchView,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: -8))
self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.searchView,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 8))
self.searchView.addConstraint(NSLayoutConstraint(item: self.txtKeyword,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.searchView,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: -8))
self.txtKeyword.placeholder = self.searchPlaceholder
self.txtKeyword.font = self.itemFont
self.txtKeyword.addTarget(self, action: #selector(BSDropdown.txtKeywordValueChanged(_:)), for: UIControlEvents.editingChanged)
}
self.selectorTableView = UITableView()
self.selectorTableView.translatesAutoresizingMaskIntoConstraints = false
self.selectorTableView.delegate = self
self.selectorTableView.dataSource = self
self.selectorTableView.separatorStyle = .none
self.selectorView.addSubview(self.selectorTableView)
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView,
attribute: NSLayoutAttribute.top,
relatedBy: NSLayoutRelation.equal,
toItem: self.enableSearch ? self.searchView : self.selectorHeaderView,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: 0))
self.selectorView.addConstraint(NSLayoutConstraint(item: self.selectorTableView,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: self.selectorView,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 0))
self.btnSelectorCancel.addTarget(self, action: #selector(BSDropdown.btnSelectorCancelTouched(_:)), for: UIControlEvents.touchUpInside)
self.btnSelectorDone.addTarget(self, action: #selector(BSDropdown.btnSelectorDoneTouched(_:)), for: UIControlEvents.touchUpInside)
self.addTarget(self, action: #selector(BSDropdown.bsdDropdownClicked(_:)), for: UIControlEvents.touchUpInside)
if self.hideDoneButton {
self.btnSelectorDone.isHidden = true
}
self.selectorModalView.isHidden = true
self.setTitle(self.defaultTitle, for: UIControlState())
}
else{
NSLog("BSDropdown Error : Please set the ViewController first")
}
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let values = self.data {
return values.count
}
else{
return 0
}
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cellInfoArray = self.data?.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
if self.dataSource != nil {
return self.dataSource.itemHeightForRowAtIndexPath(self, tableView: tableView, item: cellInfoArray, indexPath: indexPath)
}
else {
let title = cellInfoArray.object(forKey: self.titleKey) as! String
let minHeight:CGFloat = 35.0
var height:CGFloat = 16.0
var maxWidth:CGFloat = tableView.bounds.size.width - 16.0
if (indexPath as NSIndexPath).row == self.tempSelectedIndex {
maxWidth -= 39.0
}
var titleHeight : CGFloat = title.boundingRect(
with: CGSize(width: maxWidth, height: 99999),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: self.itemFont!],
context: nil
).size.height
if titleHeight < 20 {
titleHeight = 20
}
height += titleHeight
return max(minHeight, height)
}
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellInfoArray = self.data?.object(at: (indexPath as NSIndexPath).row) as! NSDictionary
if self.dataSource != nil {
let cell = self.dataSource.itemForRowAtIndexPath(self, tableView: tableView, item: cellInfoArray, indexPath: indexPath)
cell.selectionStyle = .none
cell.tintColor = self.itemTintColor
if (indexPath as NSIndexPath).row == self.tempSelectedIndex {
cell.accessoryType = UITableViewCellAccessoryType.checkmark
}
else{
cell.accessoryType = UITableViewCellAccessoryType.none
}
return cell
}
else {
let reuseId = "BSDropdownTableViewCell"
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: reuseId)
let lblTitle: UILabel!
let borderBottom: UIView!
if let _ = cell {
lblTitle = cell?.viewWithTag(1) as! UILabel
borderBottom = cell?.viewWithTag(2)
}
else{
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: reuseId)
//add label
lblTitle = UILabel()
lblTitle.translatesAutoresizingMaskIntoConstraints = false
cell!.addSubview(lblTitle)
cell!.addConstraint(NSLayoutConstraint(item: lblTitle,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: cell,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0))
cell!.addConstraint(NSLayoutConstraint(item: lblTitle,
attribute: NSLayoutAttribute.leading,
relatedBy: NSLayoutRelation.equal,
toItem: cell,
attribute: NSLayoutAttribute.leading,
multiplier: 1,
constant: 8))
cell!.addConstraint(NSLayoutConstraint(item: lblTitle,
attribute: NSLayoutAttribute.trailing,
relatedBy: NSLayoutRelation.equal,
toItem: cell,
attribute: NSLayoutAttribute.trailing,
multiplier: 1,
constant: 8))
lblTitle.tag = 1
lblTitle.textColor = self.itemTextColor
lblTitle.font = self.itemFont
//add border bottom
borderBottom = UIView()
borderBottom.backgroundColor = UIColor(white: 0.8, alpha: 1)
borderBottom.translatesAutoresizingMaskIntoConstraints = false
cell!.addSubview(borderBottom)
cell!.addConstraint(NSLayoutConstraint(item: borderBottom,
attribute: NSLayoutAttribute.left,
relatedBy: NSLayoutRelation.equal,
toItem: cell,
attribute: NSLayoutAttribute.left,
multiplier: 1,
constant: 0))
cell!.addConstraint(NSLayoutConstraint(item: borderBottom,
attribute: NSLayoutAttribute.right,
relatedBy: NSLayoutRelation.equal,
toItem: cell,
attribute: NSLayoutAttribute.right,
multiplier: 1,
constant: 0))
cell!.addConstraint(NSLayoutConstraint(item: borderBottom,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: cell,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 0))
cell!.addConstraint(NSLayoutConstraint(item: borderBottom,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: 1))
cell?.selectionStyle = .none
cell?.tintColor = self.itemTintColor
}
lblTitle.text = cellInfoArray.object(forKey: self.titleKey) as? String
if (indexPath as NSIndexPath).row == self.tempSelectedIndex {
cell?.accessoryType = UITableViewCellAccessoryType.checkmark
}
else{
cell?.accessoryType = UITableViewCellAccessoryType.none
}
return cell!
}
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let values = self.data {
if (indexPath as NSIndexPath).row > -1 && (indexPath as NSIndexPath).row < values.count {
self.tempSelectedIndex = (indexPath as NSIndexPath).row
self.selectorTableView.reloadData()
if self.hideDoneButton {
self.btnSelectorDoneTouched(self.btnSelectorDone)
}
}
}
else{
NSLog("BSDropdown Error : Please set the data first")
}
}
open func bsdDropdownClicked(_ sender: AnyObject){
if let vc = self.viewController {
self.selectorTableView.reloadData()
self.tempSelectedIndex = self.selectedIndex
self.selectorModalView.isHidden = false
self.selectorModalView.alpha = 0
vc.view.bringSubview(toFront: self.selectorModalView)
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.selectorModalView.alpha = 1
})
}
}
open func btnSelectorCancelTouched(_ sender: AnyObject){
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.selectorModalView.alpha = 0
}, completion: { (Bool) -> Void in
self.selectorModalView.isHidden = true
if self.enableSearch {
self.txtKeyword.text = ""
self.filterData("")
}
})
}
open func btnSelectorDoneTouched(_ sender: AnyObject){
self.selectedIndex = self.tempSelectedIndex
if self.tempSelectedIndex > -1 && self.tempSelectedIndex < self.data?.count {
if let cellInfoArray = self.data?.object(at: self.tempSelectedIndex) as? NSDictionary {
if let idx = cellInfoArray.object(forKey: "bsd_index") as? NSNumber {
self.selectedIndex = idx.intValue
}
}
}
if self.enableSearch {
self.txtKeyword.text = ""
self.filterData("")
}
self.setDisplayedTitle()
self.btnSelectorCancelTouched(sender)
if let d = self.delegate {
d.onDropdownSelectedItemChange(self, selectedItem: self.getSelectedValue())
}
}
fileprivate func setDisplayedTitle(){
//set title
if let value = self.getSelectedValue(){
if !self.fixedDisplayedTitle {
self.setTitle(value.object(forKey: self.titleKey) as? String, for: UIControlState())
}
else {
self.setTitle(self.defaultTitle, for: UIControlState())
}
}
else{
self.setTitle(self.defaultTitle, for: UIControlState())
}
}
open func txtKeywordValueChanged(_ sender: AnyObject) {
self.filterData(self.txtKeyword.text!)
self.selectorTableView.reloadData()
}
fileprivate func filterData(_ keyword: String){
self.data?.removeAllObjects()
self.tempSelectedIndex = -1
var i: Int = 0
if let oriData = self.originalData {
for item in oriData {
if let cellInfoArray = item as? NSMutableDictionary {
if keyword == "" || (cellInfoArray.object(forKey: self.titleKey) as! String).lowercased().range( of: keyword.lowercased() ) != nil {
cellInfoArray.setValue(NSNumber(value: i as Int), forKey: "bsd_index")
self.data?.add(cellInfoArray)
}
}
else if let dict = item as? NSDictionary {
let cellInfoArray = NSMutableDictionary(dictionary: dict)
if keyword == "" || (cellInfoArray.object(forKey: self.titleKey) as! String).lowercased().range( of: keyword.lowercased() ) != nil {
cellInfoArray.setValue(NSNumber(value: i as Int), forKey: "bsd_index")
self.data?.add(cellInfoArray)
}
}
else{
NSLog("cellInfoArray invalid : %i", i)
}
i += 1
}
}
}
//public get set
open func setDataSource(_ dataSource: NSMutableArray){
self.originalData = dataSource
self.data = NSMutableArray()
self.filterData("")
}
open func setSelectedIndex(_ index: Int){
self.selectedIndex = index
self.setDisplayedTitle()
}
open func getSelectedIndex() -> Int {
return self.selectedIndex
}
open func getSelectedValue() -> NSDictionary?{
if let dataSource = self.originalData {
if self.selectedIndex > -1 && self.selectedIndex < dataSource.count{
return dataSource.object(at: self.selectedIndex) as? NSDictionary
}
else{
return nil
}
}
else{
return nil
}
}
}
| mit |
li1024316925/Swift-TimeMovie | Swift-TimeMovie/Swift-TimeMovie/AttentionCell.swift | 1 | 1559 | //
// AttentionCell.swift
// SwiftTimeMovie
//
// Created by DahaiZhang on 16/10/21.
// Copyright © 2016年 LLQ. All rights reserved.
//
import UIKit
class AttentionCell: UICollectionViewCell {
@IBOutlet weak var movieImage: UIImageView!
@IBOutlet weak var time: UILabel!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var count: UILabel!
@IBOutlet weak var director: UILabel!
@IBOutlet weak var actor: UILabel!
@IBOutlet weak var type: UILabel!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button1: UIButton!
var model: WillModel?{
didSet{
time.text = "\((model?.rMonth)!)月\((model?.rDay)!)日上映"
title.text = model?.title
movieImage.sd_setImage(with: URL(string: (model?.image)!))
let aStr = NSMutableAttributedString(string: "\((model?.wantedCount)!)人在期待上映")
aStr.setAttributes([NSForegroundColorAttributeName:UIColor.orange], range: NSRange(location: 0, length: aStr.length-7))
count.attributedText = aStr
director.text = "导演:\((model?.director)!)"
actor.text = "主演:\((model?.actor1)!) \((model?.actor2)!)"
type.text = model?.type
}
}
override func awakeFromNib() {
super.awakeFromNib()
button2.layer.borderWidth = 2
button2.layer.borderColor = UIColor.gray.cgColor
button2.layer.cornerRadius = 15
button2.clipsToBounds = true
}
}
| apache-2.0 |
liuxianghong/GreenBaby | 工程/greenbaby/greenbaby/View/GreenButton.swift | 1 | 564 | //
// GreenButton.swift
// greenbaby
//
// Created by 刘向宏 on 15/12/3.
// Copyright © 2015年 刘向宏. All rights reserved.
//
import UIKit
class GreenButton: CustomButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.mainGreenColor()
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| lgpl-3.0 |
aquarchitect/MyKit | Sources/macOS/Extensions/AppKit/NSWindow.StyleMask+.swift | 1 | 632 | //
// NSWindow.StyleMask+.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2017 Hai Nguyen.
//
import AppKit
#if swift(>=4.0)
public extension NSWindow.StyleMask {
/// The window is displays a close button, a minimize button, and a resize control.
static var standard: NSWindow.StyleMask {
return [.closable, .resizable, .miniaturizable]
}
}
#else
public extension NSWindowStyleMask {
/// The window is displays a close button, a minimize button, and a resize control.
static var standard: NSWindowStyleMask {
return [.closable, .resizable, .miniaturizable]
}
}
#endif
| mit |
narner/AudioKit | AudioKit/Common/Internals/Testing/AKTester.swift | 1 | 1985 | //
// AKTester.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Testing node
open class AKTester: AKNode, AKToggleable, AKComponent, AKInput {
public typealias AKAudioUnitType = AKTesterAudioUnit
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(effect: "tstr")
// MARK: - Properties
fileprivate var internalAU: AKAudioUnitType?
fileprivate var testedNode: AKToggleable?
fileprivate var token: AUParameterObserverToken?
var totalSamples = 0
/// Calculate the MD5
open var MD5: String {
return internalAU?.md5 ?? ""
}
/// Flag on whether or not the test is still in progress
open var isStarted: Bool {
if let samplesIn = internalAU?.samples {
return Int(samplesIn) < totalSamples
} else {
return false
}
}
// MARK: - Initializers
/// Initialize this test node
///
/// - Parameters:
/// - input: AKNode to test
/// - samples: Number of samples to produce
///
@objc public init(_ input: AKNode?, samples: Int) {
testedNode = input as? AKToggleable
totalSamples = samples
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
input?.connect(to: self!)
self?.internalAU?.samples = Int32(samples)
}
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
testedNode?.start()
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit |
sunpaq/BohdiEngineDemoSwift | BEDemo/D3ViewController.swift | 1 | 1468 | //
// 3DViewController.swift
// BEDemo
//
// Created by Sun YuLi on 2017/5/22.
// Copyright © 2017年 SODEC. All rights reserved.
//
import UIKit
class D3ViewController: UIViewController {
@IBOutlet weak var beview: BEView!
override func viewDidLoad() {
super.viewDidLoad()
if let models = BEResource.shared().objModelNames as? [String] {
beview.loadModelNamed(models[AppDelegate.currentIndex])
AppDelegate.currentIndex += 1
if AppDelegate.currentIndex >= models.count {
AppDelegate.currentIndex = 0
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//beview.renderer.setBackgroundColor(UIColor.black)
beview.startDraw3DContent(BECameraRotateAroundModelManual)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
beview.stopDraw3DContent()
}
@IBAction func onFullscreen(_ sender: Any) {
beview.frame = UIScreen.main.bounds
}
@IBAction func onPan(_ sender: Any) {
let trans = (sender as! UIPanGestureRecognizer).translation(in: self.view)
beview.renderer.rotateModel(byPanGesture: trans)
}
@IBAction func onPinch(_ sender: Any) {
let zoom = (sender as! UIPinchGestureRecognizer).scale
beview.renderer.zoomModel(byPinchGesture: zoom)
}
}
| bsd-3-clause |
emadhegab/GenericDataSource | GenericDataSourceTests/ShouldShowMenuForItemTester.swift | 1 | 2114 | //
// ShouldShowMenuForItemTester.swift
// GenericDataSource
//
// Created by Mohamed Ebrahim Mohamed Afifi on 3/14/17.
// Copyright © 2017 mohamede1945. All rights reserved.
//
import Foundation
import GenericDataSource
import XCTest
private class _ReportBasicDataSource<CellType>: ReportBasicDataSource<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
var result: Bool = false
var indexPath: IndexPath?
override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
self.indexPath = indexPath
return result
}
}
class ShouldShowMenuForItemTester<CellType>: DataSourceTester where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
let dataSource: ReportBasicDataSource<CellType> = _ReportBasicDataSource<CellType>()
var result: Bool {
return true
}
required init(id: Int, numberOfReports: Int, collectionView: GeneralCollectionView) {
dataSource.items = Report.generate(numberOfReports: numberOfReports)
dataSource.registerReusableViewsInCollectionView(collectionView)
(dataSource as! _ReportBasicDataSource<CellType>).result = result
}
func test(indexPath: IndexPath, dataSource: AbstractDataSource, tableView: UITableView) -> Bool {
return dataSource.tableView(tableView, shouldShowMenuForRowAt: indexPath)
}
func test(indexPath: IndexPath, dataSource: AbstractDataSource, collectionView: UICollectionView) -> Bool {
return dataSource.collectionView(collectionView, shouldShowMenuForItemAt: indexPath)
}
func assert(result: Bool, indexPath: IndexPath, collectionView: GeneralCollectionView) {
XCTAssertEqual(result, self.result)
XCTAssertEqual((dataSource as! _ReportBasicDataSource<CellType>).indexPath, indexPath)
}
}
class ShouldShowMenuForItemTester2<CellType>: ShouldShowMenuForItemTester<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
override var result: Bool {
return false
}
}
| mit |
adrian-kubala/MyPlaces | MyPlaces/UIImageView+TintColor.swift | 1 | 312 | //
// UIImageView+TintColor.swift
// Places
//
// Created by Adrian on 28.09.2016.
// Copyright © 2016 Adrian Kubała. All rights reserved.
//
import UIKit
extension UIImageView {
func changeTintColor(_ color: UIColor) {
image = image?.withRenderingMode(.alwaysTemplate)
tintColor = color
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.