repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CaiMiao/CGSSGuide | DereGuide/View/Option/StepperOption.swift | 1 | 1963 | //
// StepperOption.swift
// DereGuide
//
// Created by zzk on 2017/8/19.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
class StepperOption: UIControl {
var leftLabel: UILabel!
var stepper: ValueStepper!
override init(frame: CGRect) {
super.init(frame: frame)
stepper = ValueStepper()
stepper.tintColor = Color.parade
stepper.numberFormatter.maximumFractionDigits = 0
stepper.stepValue = 1
addSubview(stepper)
stepper.snp.makeConstraints { (make) in
make.width.equalTo(140)
make.top.equalToSuperview()
make.right.equalToSuperview()
make.bottom.equalToSuperview()
}
stepper.valueLabel.snp.remakeConstraints { (make) in
make.center.equalToSuperview()
}
leftLabel = UILabel()
addSubview(leftLabel)
leftLabel.numberOfLines = 2
leftLabel.adjustsFontSizeToFitWidth = true
leftLabel.baselineAdjustment = .alignCenters
leftLabel.font = UIFont.systemFont(ofSize: 14)
leftLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(stepper)
make.left.equalToSuperview()
make.right.lessThanOrEqualTo(stepper.snp.left)
}
stepper.descriptionLabel.removeFromSuperview()
}
func setup(title: String, minValue: Double, maxValue: Double, currentValue: Double) {
self.leftLabel.text = title
stepper.minimumValue = minValue
stepper.maximumValue = maxValue
stepper.value = currentValue
}
override func addTarget(_ target: Any?, action: Selector, for controllEvents: UIControlEvents) {
stepper.addTarget(target, action: action, for: controllEvents)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 7ea43d802dab9dcf4de024e0fcb4645b | 28.69697 | 100 | 0.622959 | 5 | false | false | false | false |
Fitbit/thrift | lib/swift/Sources/TList.swift | 2 | 3901 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
public struct TList<Element : TSerializable> : RandomAccessCollection, MutableCollection, ExpressibleByArrayLiteral, TSerializable, Hashable {
typealias Storage = Array<Element>
public typealias Indices = Storage.Indices
internal var storage = Storage()
public init() { }
public init(arrayLiteral elements: Element...) {
self.storage = Storage(elements)
}
public init<Source : Sequence>(_ sequence: Source) where Source.Iterator.Element == Element {
storage = Storage(sequence)
}
/// Mark: Hashable
public var hashValue : Int {
let prime = 31
var result = 1
for element in storage {
result = prime &* result &+ element.hashValue
}
return result
}
/// Mark: TSerializable
public static var thriftType : TType { return .list }
public static func read(from proto: TProtocol) throws -> TList {
let (elementType, size) = try proto.readListBegin()
if elementType != Element.thriftType {
throw TProtocolError(error: .invalidData,
extendedError: .unexpectedType(type: elementType))
}
var list = TList()
for _ in 0..<size {
let element = try Element.read(from: proto)
list.storage.append(element)
}
try proto.readListEnd()
return list
}
public func write(to proto: TProtocol) throws {
try proto.writeListBegin(elementType: Element.thriftType, size: Int32(self.count))
for element in self.storage {
try Element.write(element, to: proto)
}
try proto.writeListEnd()
}
/// Mark: MutableCollection
public typealias SubSequence = Storage.SubSequence
public typealias Index = Storage.Index
public subscript(position: Storage.Index) -> Element {
get {
return storage[position]
}
set {
storage[position] = newValue
}
}
public subscript(range: Range<Index>) -> SubSequence {
get {
return storage[range]
}
set {
storage[range] = newValue
}
}
public var startIndex: Index {
return storage.startIndex
}
public var endIndex: Index {
return storage.endIndex
}
public func formIndex(after i: inout Index) {
storage.formIndex(after: &i)
}
public func formIndex(before i: inout Int) {
storage.formIndex(before: &i)
}
public func index(after i: Index) -> Index {
return storage.index(after: i)
}
public func index(before i: Int) -> Int {
return storage.index(before: i)
}
}
extension TList : RangeReplaceableCollection {
public mutating func replaceSubrange<C: Collection>(_ subrange: Range<Index>, with newElements: C)
where C.Iterator.Element == Element {
storage.replaceSubrange(subrange, with: newElements)
}
}
extension TList : CustomStringConvertible, CustomDebugStringConvertible {
public var description : String {
return storage.description
}
public var debugDescription : String {
return storage.debugDescription
}
}
public func ==<Element>(lhs: TList<Element>, rhs: TList<Element>) -> Bool {
return lhs.storage.elementsEqual(rhs.storage) { $0 == $1 }
}
| apache-2.0 | 216fbbad2d454c919136833b6c910828 | 27.268116 | 142 | 0.687516 | 4.402935 | false | false | false | false |
nikita-leonov/DependentType | DependentType.playground/Sources/DependentType.swift | 1 | 3438 | import Foundation
public protocol TypeValue {
typealias DependentType
static func value() -> DependentType
}
public struct False: TypeValue {
public typealias DependentType = Bool
public static func value() -> DependentType {
return false
}
}
public struct True: TypeValue {
public typealias DependentType = Bool
public static func value() -> DependentType {
return true
}
}
public struct DependentType<DependentType: Equatable, Expectation: TypeValue where Expectation.DependentType == DependentType> {
public var unsafeValue: DependentType {
return Expectation.value()
}
public init(value: DependentType = Expectation.value()) {
if value != Expectation.value() {
fatalError("Initialization of \(self) not satisfying to type constraint.")
}
}
}
//: ==
public func ==(left: DependentType<Bool, True>, right: DependentType<Bool, False>) -> DependentType<Bool, False> {
return DependentType()
}
public func ==(left: DependentType<Bool, False>, right: DependentType<Bool, True>) -> DependentType<Bool, False> {
return DependentType()
}
public func ==(left: DependentType<Bool, False>, right: DependentType<Bool, False>) -> DependentType<Bool, True> {
return DependentType()
}
public func ==(left: DependentType<Bool, True>, right: DependentType<Bool, True>) -> DependentType<Bool, True> {
return DependentType()
}
//: !
public prefix func !(value: DependentType<Bool, False>) -> DependentType<Bool, True> {
return DependentType()
}
public prefix func !(value: DependentType<Bool, True>) -> DependentType<Bool, False> {
return DependentType()
}
//: !=
public func !=(left: DependentType<Bool, True>, right: DependentType<Bool, False>) -> DependentType<Bool, True> {
return !(left == right)
}
public func !=(left: DependentType<Bool, False>, right: DependentType<Bool, True>) -> DependentType<Bool, True> {
return !(left == right)
}
public func !=(left: DependentType<Bool, False>, right: DependentType<Bool, False>) -> DependentType<Bool, False> {
return !(left == right)
}
public func !=(left: DependentType<Bool, True>, right: DependentType<Bool, True>) -> DependentType<Bool, False> {
return !(left == right)
}
//: &&
public func &&(left: DependentType<Bool, True>, right: DependentType<Bool, False>) -> DependentType<Bool, False> {
return DependentType()
}
public func &&(left: DependentType<Bool, False>, right: DependentType<Bool, True>) -> DependentType<Bool, False> {
return DependentType()
}
public func &&(left: DependentType<Bool, False>, right: DependentType<Bool, False>) -> DependentType<Bool, False> {
return DependentType()
}
public func &&(left: DependentType<Bool, True>, right: DependentType<Bool, True>) -> DependentType<Bool, True> {
return DependentType()
}
//: ||
public func ||(left: DependentType<Bool, True>, right: DependentType<Bool, False>) -> DependentType<Bool, True> {
return DependentType()
}
public func ||(left: DependentType<Bool, False>, right: DependentType<Bool, True>) -> DependentType<Bool, True> {
return DependentType()
}
public func ||(left: DependentType<Bool, False>, right: DependentType<Bool, False>) -> DependentType<Bool, False> {
return DependentType()
}
public func ||(left: DependentType<Bool, True>, right: DependentType<Bool, True>) -> DependentType<Bool, True> {
return DependentType()
} | mit | fc8523f823068930fb17593f59535dca | 30.550459 | 128 | 0.690227 | 3.88914 | false | false | false | false |
practicalswift/swift | test/SILOptimizer/definite-init-convert-to-escape.swift | 5 | 3593 | // RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name A -verify -emit-sil -import-objc-header %S/Inputs/Closure.h -disable-objc-attr-requires-foundation-module -enable-sil-ownership -Xllvm -sil-disable-convert-escape-to-noescape-switch-peephole %s | %FileCheck %s --check-prefix=NOPEEPHOLE
// REQUIRES: objc_interop
import Foundation
// Make sure that we keep the escaping closures alive accross the ultimate call.
// CHECK-LABEL: sil @$s1A19bridgeNoescapeBlock5optFn0D3Fn2yySSSgcSg_AFtF
// CHECK: bb0
// CHECK: retain_value %0
// CHECK: retain_value %0
// CHECK: bb1
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release
// CHECK: bb5
// CHECK: retain_value %1
// CHECK: retain_value %1
// CHECK: bb6
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release
// CHECK: bb10
// CHECK: [[F:%.*]] = function_ref @noescapeBlock3
// CHECK: apply [[F]]
// CHECK: release_value {{.*}} : $Optional<NSString>
// CHECK: release_value %1 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>) -> ()>
// CHECK: release_value %0 : $Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: release_value {{.*}} : $Optional<@convention(block) @noescape (Optional<NSString>)
public func bridgeNoescapeBlock( optFn: ((String?) -> ())?, optFn2: ((String?) -> ())?) {
noescapeBlock3(optFn, optFn2, "Foobar")
}
@_silgen_name("_returnOptionalEscape")
public func returnOptionalEscape() -> (() ->())?
// Make sure that we keep the escaping closure alive accross the ultimate call.
// CHECK-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[V0:%.*]] = function_ref @_returnOptionalEscape
// CHECK: [[V1:%.*]] = apply [[V0]]
// CHECK: retain_value [[V1]]
// CHECK: switch_enum {{.*}}bb1
// CHECK: bb1([[V2:%.*]]: $@callee_guaranteed () -> ()):
// CHECK: convert_escape_to_noescape %
// CHECK: strong_release [[V2]]
// CHECK: bb5({{.*}} : $Optional<@convention(block) @noescape () -> ()>)
// CHECK: [[F:%.*]] = function_ref @noescapeBlock
// CHECK: apply [[F]]({{.*}})
// CHECK: release_value [[V1]] : $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE-LABEL: sil @$s1A19bridgeNoescapeBlockyyF : $@convention(thin) () -> () {
// NOPEEPHOLE: bb0:
// NOPEEPHOLE: alloc_stack $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE: [[SLOT:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// NOPEEPHOLE: [[NONE:%.*]] = enum $Optional
// NOPEEPHOLE: store [[NONE]] to [[SLOT]]
// NOPEEPHOLE: [[V0:%.*]] = function_ref @_returnOptionalEscape
// NOPEEPHOLE: [[V1:%.*]] = apply [[V0]]
// NOPEEPHOLE: switch_enum {{.*}}bb1
// NOPEEPHOLE: bb1([[V2:%.*]]: $@callee_guaranteed () -> ()):
// NOPEEPHOLE: destroy_addr [[SLOT]]
// NOPEEPHOLE: [[SOME:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[V2]]
// NOPEEPHOLE: store [[SOME]] to [[SLOT]]
// NOPEEPHOLE: convert_escape_to_noescape %
// NOPEEPHOLE-NOT: strong_release
// NOPEEPHOLE: br
// NOPEEPHOLE: bb5({{.*}} : $Optional<@convention(block) @noescape () -> ()>)
// NOPEEPHOLE: [[F:%.*]] = function_ref @noescapeBlock
// NOPEEPHOLE: apply [[F]]({{.*}})
// NOPEEPHOLE: destroy_addr [[SLOT]]
// NOPEEPHOLE: dealloc_stack [[SLOT]]
public func bridgeNoescapeBlock() {
noescapeBlock(returnOptionalEscape())
}
| apache-2.0 | 64a0cc61853802ded00c27d96caca9e8 | 44.481013 | 279 | 0.650431 | 3.185284 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/Jobs/CompileJob.swift | 1 | 19218 | //===--------------- CompileJob.swift - Swift Compilation Job -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftOptions
import struct TSCBasic.RelativePath
extension Driver {
/// Add the appropriate compile mode option to the command line for a compile job.
mutating func addCompileModeOption(outputType: FileType?, commandLine: inout [Job.ArgTemplate]) {
if let compileOption = outputType?.frontendCompileOption {
commandLine.appendFlag(compileOption)
} else {
guard let compileModeOption = parsedOptions.getLast(in: .modes) else {
fatalError("We were told to perform a standard compile, but no mode option was passed to the driver.")
}
commandLine.appendFlag(compileModeOption.option)
}
}
mutating func computeIndexUnitOutput(for input: TypedVirtualPath, outputType: FileType, topLevel: Bool) throws -> TypedVirtualPath? {
if let path = try outputFileMap?.existingOutput(inputFile: input.fileHandle, outputType: .indexUnitOutputPath) {
return TypedVirtualPath(file: path, type: outputType)
}
if topLevel {
if let baseOutput = parsedOptions.getLastArgument(.indexUnitOutputPath)?.asSingle,
let baseOutputPath = try? VirtualPath.intern(path: baseOutput) {
return TypedVirtualPath(file: baseOutputPath, type: outputType)
}
}
return nil
}
mutating func computePrimaryOutput(for input: TypedVirtualPath, outputType: FileType,
isTopLevel: Bool) throws -> TypedVirtualPath {
if let path = try outputFileMap?.existingOutput(inputFile: input.fileHandle, outputType: outputType) {
return TypedVirtualPath(file: path, type: outputType)
}
if isTopLevel {
if let baseOutput = parsedOptions.getLastArgument(.o)?.asSingle,
let baseOutputPath = try? VirtualPath.intern(path: baseOutput) {
return TypedVirtualPath(file: baseOutputPath, type: outputType)
} else if compilerOutputType?.isTextual == true {
return TypedVirtualPath(file: .standardOutput, type: outputType)
} else if outputType == .swiftModule, let moduleOutput = moduleOutputInfo.output {
return TypedVirtualPath(file: moduleOutput.outputPath, type: outputType)
}
}
let baseName: String
if !compilerMode.usesPrimaryFileInputs && numThreads == 0 {
baseName = moduleOutputInfo.name
} else {
baseName = input.file.basenameWithoutExt
}
if !isTopLevel {
return TypedVirtualPath(file: VirtualPath.createUniqueTemporaryFile(.init(baseName.appendingFileTypeExtension(outputType))).intern(),
type: outputType)
}
return TypedVirtualPath(file: try useWorkingDirectory(.init(baseName.appendingFileTypeExtension(outputType))).intern(), type: outputType)
}
/// Is this compile job top-level
func isTopLevelOutput(type: FileType?) -> Bool {
switch type {
case .assembly, .sil, .raw_sil, .llvmIR, .ast, .jsonDependencies, .sib, .raw_sib,
.importedModules, .indexData:
return true
case .object:
return (linkerOutputType == nil)
case .llvmBitcode:
if compilerOutputType != .llvmBitcode {
// The compiler output isn't bitcode, so bitcode isn't top-level (-embed-bitcode).
return false
} else {
// When -lto is set, .bc will be used for linking. Otherwise, .bc is
// top-level output (-emit-bc)
return lto == nil || linkerOutputType == nil
}
case .swiftModule:
return compilerMode.isSingleCompilation && moduleOutputInfo.output?.isTopLevel ?? false
case .swift, .image, .dSYM, .dependencies, .emitModuleDependencies, .autolink,
.swiftDocumentation, .swiftInterface, .privateSwiftInterface, .swiftSourceInfoFile,
.diagnostics, .emitModuleDiagnostics, .objcHeader, .swiftDeps, .remap, .tbd,
.moduleTrace, .yamlOptimizationRecord, .bitstreamOptimizationRecord, .pcm, .pch,
.clangModuleMap, .jsonCompilerFeatures, .jsonTargetInfo, .jsonSwiftArtifacts,
.indexUnitOutputPath, .modDepCache, .jsonAPIBaseline, .jsonABIBaseline,
.swiftConstValues, nil:
return false
}
}
/// Add the compiler inputs for a frontend compilation job, and return the
/// corresponding primary set of outputs and, if not identical, the output
/// paths to record in the index data (empty otherwise).
mutating func addCompileInputs(primaryInputs: [TypedVirtualPath],
indexFilePath: TypedVirtualPath?,
inputs: inout [TypedVirtualPath],
inputOutputMap: inout [TypedVirtualPath: [TypedVirtualPath]],
outputType: FileType?,
commandLine: inout [Job.ArgTemplate])
throws -> ([TypedVirtualPath], [TypedVirtualPath]) {
let useInputFileList: Bool
if let allSourcesFileList = allSourcesFileList {
useInputFileList = true
commandLine.appendFlag(.filelist)
commandLine.appendPath(allSourcesFileList)
} else {
useInputFileList = false
}
let usePrimaryInputFileList = primaryInputs.count > fileListThreshold
if usePrimaryInputFileList {
// primary file list
commandLine.appendFlag(.primaryFilelist)
let fileList = VirtualPath.createUniqueFilelist(RelativePath("primaryInputs"),
.list(primaryInputs.map(\.file)))
commandLine.appendPath(fileList)
}
let isTopLevel = isTopLevelOutput(type: outputType)
// If we will be passing primary files via -primary-file, form a set of primary input files so
// we can check more quickly.
let usesPrimaryFileInputs: Bool
// N.B. We use an array instead of a hashed collection like a set because
// TypedVirtualPaths are quite expensive to hash. To the point where a
// linear scan beats Set.contains by a factor of 4 for heavy workloads.
let primaryInputFiles: [TypedVirtualPath]
if compilerMode.usesPrimaryFileInputs {
assert(!primaryInputs.isEmpty)
usesPrimaryFileInputs = true
primaryInputFiles = primaryInputs
} else if let path = indexFilePath {
// If -index-file is used, we perform a single compile but pass the
// -index-file-path as a primary input file.
usesPrimaryFileInputs = true
primaryInputFiles = [path]
} else {
usesPrimaryFileInputs = false
primaryInputFiles = []
}
let isMultithreaded = numThreads > 0
// Add each of the input files.
var primaryOutputs: [TypedVirtualPath] = []
var primaryIndexUnitOutputs: [TypedVirtualPath] = []
var indexUnitOutputDiffers = false
let firstSwiftInput = inputs.count
for input in self.inputFiles where input.type.isPartOfSwiftCompilation {
inputs.append(input)
let isPrimary = usesPrimaryFileInputs && primaryInputFiles.contains(input)
if isPrimary {
if !usePrimaryInputFileList {
commandLine.appendFlag(.primaryFile)
commandLine.appendPath(input.file)
}
} else {
if !useInputFileList {
commandLine.appendPath(input.file)
}
}
// If there is a primary output or we are doing multithreaded compiles,
// add an output for the input.
if let outputType = outputType,
isPrimary || (!usesPrimaryFileInputs && isMultithreaded && outputType.isAfterLLVM) {
let output = try computePrimaryOutput(for: input,
outputType: outputType,
isTopLevel: isTopLevel)
primaryOutputs.append(output)
inputOutputMap[input] = [output]
if let indexUnitOut = try computeIndexUnitOutput(for: input, outputType: outputType, topLevel: isTopLevel) {
indexUnitOutputDiffers = true
primaryIndexUnitOutputs.append(indexUnitOut)
} else {
primaryIndexUnitOutputs.append(output)
}
}
}
// When not using primary file inputs or multithreading, add a single output.
if let outputType = outputType,
!usesPrimaryFileInputs && !(isMultithreaded && outputType.isAfterLLVM) {
let input = TypedVirtualPath(file: OutputFileMap.singleInputKey, type: inputs[firstSwiftInput].type)
let output = try computePrimaryOutput(for: input,
outputType: outputType,
isTopLevel: isTopLevel)
primaryOutputs.append(output)
inputOutputMap[input] = [output]
if let indexUnitOut = try computeIndexUnitOutput(for: input, outputType: outputType, topLevel: isTopLevel) {
indexUnitOutputDiffers = true
primaryIndexUnitOutputs.append(indexUnitOut)
} else {
primaryIndexUnitOutputs.append(output)
}
}
if !indexUnitOutputDiffers {
primaryIndexUnitOutputs.removeAll()
} else {
assert(primaryOutputs.count == primaryIndexUnitOutputs.count)
}
return (primaryOutputs, primaryIndexUnitOutputs)
}
/// Form a compile job, which executes the Swift frontend to produce various outputs.
mutating func compileJob(primaryInputs: [TypedVirtualPath],
outputType: FileType?,
addJobOutputs: ([TypedVirtualPath]) -> Void,
emitModuleTrace: Bool)
throws -> Job {
var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) }
var inputs: [TypedVirtualPath] = []
var outputs: [TypedVirtualPath] = []
// Used to map primaryInputs to primaryOutputs
var inputOutputMap = [TypedVirtualPath: [TypedVirtualPath]]()
commandLine.appendFlag("-frontend")
addCompileModeOption(outputType: outputType, commandLine: &commandLine)
let indexFilePath: TypedVirtualPath?
if let indexFileArg = parsedOptions.getLastArgument(.indexFilePath)?.asSingle {
let path = try VirtualPath(path: indexFileArg)
indexFilePath = inputFiles.first { $0.file == path }
} else {
indexFilePath = nil
}
let (primaryOutputs, primaryIndexUnitOutputs) =
try addCompileInputs(primaryInputs: primaryInputs,
indexFilePath: indexFilePath,
inputs: &inputs,
inputOutputMap: &inputOutputMap,
outputType: outputType,
commandLine: &commandLine)
outputs += primaryOutputs
// FIXME: optimization record arguments are added before supplementary outputs
// for compatibility with the integrated driver's test suite. We should adjust the tests
// so we can organize this better.
// -save-optimization-record and -save-optimization-record= have different meanings.
// In this case, we specifically want to pass the EQ variant to the frontend
// to control the output type of optimization remarks (YAML or bitstream).
try commandLine.appendLast(.saveOptimizationRecordEQ, from: &parsedOptions)
try commandLine.appendLast(.saveOptimizationRecordPasses, from: &parsedOptions)
let inputsGeneratingCodeCount = primaryInputs.isEmpty
? inputs.count
: primaryInputs.count
outputs += try addFrontendSupplementaryOutputArguments(
commandLine: &commandLine,
primaryInputs: primaryInputs,
inputsGeneratingCodeCount: inputsGeneratingCodeCount,
inputOutputMap: &inputOutputMap,
includeModuleTracePath: emitModuleTrace,
indexFilePath: indexFilePath)
// Forward migrator flags.
try commandLine.appendLast(.apiDiffDataFile, from: &parsedOptions)
try commandLine.appendLast(.apiDiffDataDir, from: &parsedOptions)
try commandLine.appendLast(.dumpUsr, from: &parsedOptions)
if parsedOptions.hasArgument(.parseStdlib) {
commandLine.appendFlag(.disableObjcAttrRequiresFoundationModule)
}
try addCommonFrontendOptions(commandLine: &commandLine, inputs: &inputs)
// FIXME: MSVC runtime flags
if Driver.canDoCrossModuleOptimization(parsedOptions: &parsedOptions) &&
// For historical reasons, -cross-module-optimization turns on "aggressive" CMO
// which is different from "default" CMO.
!parsedOptions.hasArgument(.CrossModuleOptimization) {
assert(!emitModuleSeparately, "Cannot emit module separately with cross-module-optimization")
commandLine.appendFlag("-enable-default-cmo")
}
if parsedOptions.hasArgument(.parseAsLibrary, .emitLibrary) {
commandLine.appendFlag(.parseAsLibrary)
}
try commandLine.appendLast(.parseSil, from: &parsedOptions)
try commandLine.appendLast(.migrateKeepObjcVisibility, from: &parsedOptions)
if numThreads > 0 {
commandLine.appendFlags("-num-threads", numThreads.description)
}
// Add primary outputs.
if primaryOutputs.count > fileListThreshold {
commandLine.appendFlag(.outputFilelist)
let fileList = VirtualPath.createUniqueFilelist(RelativePath("outputs"),
.list(primaryOutputs.map { $0.file }))
commandLine.appendPath(fileList)
} else {
for primaryOutput in primaryOutputs {
commandLine.appendFlag(.o)
commandLine.appendPath(primaryOutput.file)
}
}
// Add index unit output paths if needed.
if !primaryIndexUnitOutputs.isEmpty {
if primaryIndexUnitOutputs.count > fileListThreshold {
commandLine.appendFlag(.indexUnitOutputPathFilelist)
let fileList = VirtualPath.createUniqueFilelist(RelativePath("index-unit-outputs"),
.list(primaryIndexUnitOutputs.map { $0.file }))
commandLine.appendPath(fileList)
} else {
for primaryIndexUnitOutput in primaryIndexUnitOutputs {
commandLine.appendFlag(.indexUnitOutputPath)
commandLine.appendPath(primaryIndexUnitOutput.file)
}
}
}
try commandLine.appendLast(.embedBitcodeMarker, from: &parsedOptions)
// For `-index-file` mode add `-disable-typo-correction`, since the errors
// will be ignored and it can be expensive to do typo-correction.
if compilerOutputType == FileType.indexData {
commandLine.appendFlag(.disableTypoCorrection)
}
if parsedOptions.contains(.indexStorePath) {
try commandLine.appendLast(.indexStorePath, from: &parsedOptions)
if !parsedOptions.contains(.indexIgnoreSystemModules) {
commandLine.appendFlag(.indexSystemModules)
}
try commandLine.appendLast(.indexIgnoreClangModules, from: &parsedOptions)
try commandLine.appendLast(.indexIncludeLocals, from: &parsedOptions)
}
if parsedOptions.contains(.debugInfoStoreInvocation) ||
toolchain.shouldStoreInvocationInDebugInfo {
commandLine.appendFlag(.debugInfoStoreInvocation)
}
if let map = toolchain.globalDebugPathRemapping {
commandLine.appendFlag(.debugPrefixMap)
commandLine.appendFlag(map)
}
try commandLine.appendLast(.trackSystemDependencies, from: &parsedOptions)
try commandLine.appendLast(.CrossModuleOptimization, from: &parsedOptions)
try commandLine.appendLast(.ExperimentalPerformanceAnnotations, from: &parsedOptions)
try commandLine.appendLast(.disableAutolinkingRuntimeCompatibility, from: &parsedOptions)
try commandLine.appendLast(.runtimeCompatibilityVersion, from: &parsedOptions)
try commandLine.appendLast(.disableAutolinkingRuntimeCompatibilityDynamicReplacements, from: &parsedOptions)
try commandLine.appendLast(.disableAutolinkingRuntimeCompatibilityConcurrency, from: &parsedOptions)
try commandLine.appendLast(.checkApiAvailabilityOnly, from: &parsedOptions)
if compilerMode.isSingleCompilation {
try commandLine.appendLast(.emitSymbolGraph, from: &parsedOptions)
try commandLine.appendLast(.emitSymbolGraphDir, from: &parsedOptions)
}
try commandLine.appendLast(.includeSpiSymbols, from: &parsedOptions)
try commandLine.appendLast(.symbolGraphMinimumAccessLevel, from: &parsedOptions)
addJobOutputs(outputs)
// Bridging header is needed for compiling these .swift sources.
if let pchPath = bridgingPrecompiledHeader {
let pchInput = TypedVirtualPath(file: pchPath, type: .pch)
inputs.append(pchInput)
}
let displayInputs : [TypedVirtualPath]
if case .singleCompile = compilerMode {
displayInputs = inputs
} else {
displayInputs = primaryInputs
}
return Job(
moduleName: moduleOutputInfo.name,
kind: .compile,
tool: try toolchain.resolvedTool(.swiftCompiler),
commandLine: commandLine,
displayInputs: displayInputs,
inputs: inputs,
primaryInputs: primaryInputs,
outputs: outputs,
inputOutputMap: inputOutputMap
)
}
}
extension Job {
/// In whole-module-optimization mode (WMO), there are no primary inputs and every input generates
/// code.
public var inputsGeneratingCode: [TypedVirtualPath] {
kind != .compile
? []
: !primaryInputs.isEmpty
? primaryInputs
: inputs.filter {$0.type.isPartOfSwiftCompilation}
}
}
extension FileType {
/// Determine the frontend compile option that corresponds to the given output type.
fileprivate var frontendCompileOption: Option {
switch self {
case .object:
return .c
case .pch:
return .emitPch
case .ast:
return .dumpAst
case .raw_sil:
return .emitSilgen
case .sil:
return .emitSil
case .raw_sib:
return .emitSibgen
case .sib:
return .emitSib
case .llvmIR:
return .emitIr
case .llvmBitcode:
return .emitBc
case .assembly:
return .S
case .swiftModule:
return .emitModule
case .importedModules:
return .emitImportedModules
case .indexData:
return .typecheck
case .remap:
return .updateCode
case .jsonDependencies:
return .scanDependencies
case .jsonTargetInfo:
return .printTargetInfo
case .jsonCompilerFeatures:
return .emitSupportedFeatures
case .swift, .dSYM, .autolink, .dependencies, .emitModuleDependencies,
.swiftDocumentation, .pcm, .diagnostics, .emitModuleDiagnostics,
.objcHeader, .image, .swiftDeps, .moduleTrace, .tbd, .yamlOptimizationRecord,
.bitstreamOptimizationRecord, .swiftInterface, .privateSwiftInterface,
.swiftSourceInfoFile, .clangModuleMap, .jsonSwiftArtifacts,
.indexUnitOutputPath, .modDepCache, .jsonAPIBaseline, .jsonABIBaseline,
.swiftConstValues:
fatalError("Output type can never be a primary output")
}
}
}
| apache-2.0 | 968ff88b761adfcad8be1998f46ac976 | 39.889362 | 141 | 0.682745 | 4.8045 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Parse Dashboard for iOS/ViewControllers/Core/FileViewController.swift | 1 | 13800 | //
// FileViewController.swift
// Parse Dashboard for iOS
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 8/31/17.
//
import UIKit
import Photos
import AlertHUDKit
import PDFReader
final class FileViewController: ViewController {
// MARK: - Properties
private var schema: PFSchema
private var key: String
private var url: URL?
private var filename: String
private var objectId: String
fileprivate var currentFileData: Data? {
didSet {
if let data = currentFileData {
if let image = UIImage(data: data) {
imageView.image = image
imageView.contentMode = .scaleAspectFit
actionButton.setTitle("Export Image", for: .normal)
} else {
if filename.components(separatedBy: ".").last == "pdf" {
imageView.image = UIImage(named: "PDF")
actionButton.setTitle("View File", for: .normal)
} else {
imageView.image = UIImage(named: "File")
actionButton.setTitle("Export File", for: .normal)
}
imageView.contentMode = .center
}
} else {
imageView.image = UIImage(named: "File")
actionButton.setTitle("Download File", for: .normal)
}
}
}
// MARK: - Subviews
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "File")
imageView.contentMode = .center
imageView.clipsToBounds = true
return imageView
}()
private lazy var actionButton: UIButton = { [weak self] in
let button = UIButton()
button.setTitle("Download File", for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 16)
button.setTitleColor(.white, for: .normal)
button.setTitleColor(UIColor.white.withAlphaComponent(0.3), for: .highlighted)
button.backgroundColor = .logoTint
button.layer.cornerRadius = 5
button.addTarget(self, action: #selector(accessFile(_:)), for: .touchUpInside)
return button
}()
// MARK: - Initialization
init(url: URL?, filename: String, schema: PFSchema, key: String, objectId: String) {
self.url = url
self.filename = filename
self.schema = schema
self.key = key
self.objectId = objectId
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupNavigationBar()
}
// MARK: - Setup
private func setupView() {
view.backgroundColor = .darkPurpleAccent
view.addSubview(imageView)
view.addSubview(actionButton)
imageView.fillSuperview()
actionButton.anchorCenterXToSuperview()
actionButton.anchor(bottom: view.layoutMarginsGuide.bottomAnchor, bottomConstant: 32, widthConstant: 120, heightConstant: 44)
}
private func setupNavigationBar() {
title = "File View"
subtitle = objectId
navigationItem.rightBarButtonItems = [
UIBarButtonItem(image: UIImage(named: "Upload"),
style: .plain,
target: self,
action: #selector(uploadNewFile))
]
}
// MARK: - Data Refresh
@objc
func accessFile(_ sender: UIButton) {
sender.isEnabled = false
if currentFileData == nil {
loadDataFromUrl()
} else {
exportFile()
}
sender.isEnabled = true
}
func loadDataFromUrl() {
guard let url = url else {
handleError("File does not exist")
return
}
actionButton.isHidden = true
let progressWheel = DownloadWheel()
print("Download: ", url)
ConsoleView.shared.log(message: "GET: " + url.absoluteString, kind: .info)
progressWheel.downloadFile(from: url) { [weak self] (view, data, error) in
self?.currentFileData = data
guard error == nil else {
ConsoleView.shared.log(message: "RESPONSE: " + error.debugDescription, kind: .error)
self?.handleError(error?.localizedDescription)
return
}
ConsoleView.shared.log(message: "RESPONSE: \(data?.count ?? 0) byes", kind: .success)
view.currentState = .active
self?.actionButton.isHidden = false
}.present(self)
}
func exportFile() {
guard let data = currentFileData else { return }
do {
let directory = FileManager.default.temporaryDirectory
let type = filename.components(separatedBy: ".").last!
let path = directory.appendingPathComponent(filename)
print("Writing to: ", path)
try data.write(to: path, options: .completeFileProtection)
// Try to render the file as a PDF
if type == "pdf", let pdf = PDFDocument(url: path) {
let readerController = PDFViewController.createNew(with: pdf, actionButtonImage: UIImage(named: "Share")?.withRenderingMode(.alwaysTemplate), actionStyle: .activitySheet)
readerController.backgroundColor = .groupTableViewBackground
navigationController?.pushViewController(readerController, animated: true)
} else if let image = UIImage(data: data) {
let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil)
present(activity, animated: true, completion: nil)
} else {
// Fallback on system to recognize file
let activity = UIActivityViewController(activityItems: [path], applicationActivities: nil)
present(activity, animated: true, completion: nil)
}
} catch let error {
handleError(error.localizedDescription)
}
}
// MARK: - User Actions
@objc
func uploadNewFile() {
let actions = [
ActionSheetAction(title: "Photo", image: #imageLiteral(resourceName: "Camera"), style: .default, callback: { [weak self] _ in
self?.presentImagePicker()
}),
ActionSheetAction(title: "Document", image: #imageLiteral(resourceName: "Document"), style: .default, callback: { [weak self] _ in
self?.presentDocumentPicker()
})
]
let actionSheetController = ActionSheetController(title: "Upload File From", message: nil, actions: actions)
present(actionSheetController, animated: true, completion: nil)
}
// MARK: - Helpers
func deleteOldFile() {
if let appId = ParseLite.shared.currentConfiguration?.applicationId,
let urlString = url?.absoluteString.replacingOccurrences(of: "\(appId)/", with: ""),
let url = URL(string: urlString) {
// Delete the old file
ParseLite.shared.delete(url: url, completion: { _, _ in
Toast(text: "Deleted Old File").present(self)
})
}
// Update the current url
ParseLite.shared.get("/classes/\(schema.name)/\(objectId)") { [weak self] result, json in
guard let json = json, let key = self?.key else { return }
let updatedObject = ParseLiteObject(json)
if let urlString = (updatedObject.value(forKey: key) as? [String:String])?["url"] {
self?.url = URL(string: urlString)
}
}
}
func presentDocumentPicker() {
if #available(iOS 11.0, *) {
let documentBrowser = UIDocumentBrowserViewController(forOpeningFilesWithContentTypes: nil)
documentBrowser.delegate = self
documentBrowser.allowsDocumentCreation = false
documentBrowser.allowsPickingMultipleItems = false
documentBrowser.additionalLeadingNavigationBarButtonItems = [
UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelDocumentPicker))
]
present(documentBrowser, animated: false, completion: nil)
} else {
handleError("Sorry, this is only available on iOS 11")
}
}
@objc
func cancelDocumentPicker() {
if #available(iOS 11.0, *) {
// Assume the presented controller is the UIDocumentBrowserViewController
if let documentBrowser = UIApplication.shared.presentedController as? UIDocumentBrowserViewController {
documentBrowser.dismiss(animated: false, completion: nil)
}
}
}
// MARK: - Image Picker
func presentImagePicker() {
let imagePicker = ImagePickerController()
imagePicker.onImageSelection { [weak self] image in
guard let image = image else { return }
guard let imageData = UIImageJPEGRepresentation(image, 1) else {
self?.handleError("Invalid Image Data")
return
}
self?.uploadFile(data: imageData, for: "jpg")
}
present(imagePicker, animated: true, completion: nil)
}
}
extension FileViewController: UIDocumentBrowserViewControllerDelegate {
// MARK: Document Picker Helpers
private func openFile(at url: URL, completion: @escaping (Bool)->Void) {
ConsoleView.shared.log(message: "GET: " + url.absoluteString, kind: .info)
let file = File(fileURL: url)
file.open { [weak self] success in
completion(success)
if success {
guard let data = FileManager.default.contents(atPath: file.fileURL.path) else {
self?.handleError("Sorry, access to that file is unavailable")
return
}
let fileType = url.absoluteString.components(separatedBy: ".").last!.lowercased()
self?.uploadFile(data: data, for: fileType)
} else {
self?.handleError("Failed to open file")
}
}
}
private func uploadFile(data: Data, for fileType: String) {
Toast(text: "Uploading").present(self, animated: true, duration: 1)
ParseLite.shared.post(filename: self.filename , classname: self.schema.name, key: self.key,
objectId: self.objectId, data: data, fileType: fileType, contentType: "application/\(fileType)",
completion: { [weak self] (result, json) in
guard result.success else {
self?.handleError(result.error)
return
}
self?.handleSuccess("application/\(fileType) File Uploaded")
self?.currentFileData = data
self?.deleteOldFile()
})
}
// MARK: UIDocumentBrowserViewControllerDelegate Helpers
@available(iOS 11.0, *)
func documentBrowser(_ controller: UIDocumentBrowserViewController, didPickDocumentURLs documentURLs: [URL]) {
guard let url = documentURLs.first else { return }
openFile(at: url) { success in
if success {
controller.dismiss(animated: false, completion: nil)
}
}
}
@available(iOS 11.0, *)
func documentBrowser(_ controller: UIDocumentBrowserViewController, didImportDocumentAt sourceURL: URL, toDestinationURL destinationURL: URL) {
openFile(at: destinationURL) { success in
if success {
controller.dismiss(animated: false, completion: nil)
}
}
}
@available(iOS 11.0, *)
func documentBrowser(_ controller: UIDocumentBrowserViewController, failedToImportDocumentAt documentURL: URL, error: Error?) {
self.handleError(error?.localizedDescription)
}
@available(iOS 11.0, *)
func documentBrowser(_ controller: UIDocumentBrowserViewController, didRequestDocumentCreationWithHandler importHandler: @escaping (URL?, UIDocumentBrowserViewController.ImportMode) -> Void) {
// Not currently supported, but having this silences warnings
}
}
| mit | cd7c8b57e202c79ef28176d2501a2de4 | 37.544693 | 196 | 0.598812 | 5.116426 | false | false | false | false |
CodeInventorGroup/CIComponentKit | Sources/CIComponentKit/CICHUD+Guide.swift | 1 | 5136 | //
// CICHUD+Guide.swift
// CIComponentKit
//
// Created by ManoBoo on 2017/10/12.
// Copyright © 2017年 club.codeinventor. All rights reserved.
// 页面中弹出一个类似于UIAlertView或者UIAlertController的东西, 建议打开蒙板
import UIKit
extension CICHUD {
public class GuideView: CICUIView {
/// 展示内容内部边距
public var contentInsets = UIEdgeInsets.init(top: 22, left: 20, bottom: 20, right: 20)
/// 展示内容外部边距,top无效
public var contentMargins: UIEdgeInsets {
return UIEdgeInsets.layoutMargins
}
public var title = "提示"
public let titleLabel = UILabel()
public var message: String?
public let messageLabel = CICScrollLabel.init(frame: .zero)
/// 是否需要黑色蒙板
public var isDisplayBlackMask = false {
didSet {
backgroungView.alpha = isDisplayBlackMask ? 0.6 : 0
}
}
/// contentView
public var contentView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffect.Style.extraLight))
/// 黑色遮罩
public var backgroungView = UIView()
public override init(frame: CGRect) {
super.init(frame: frame)
initSubviews()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - CICAppearance
public override func deviceOrientationDidChange() {
super.deviceOrientationDidChange()
guard let superview = self.superview else {
return
}
self.frame(superview.bounds)
}
// MARK: - Layout
public override func layoutSubviews() {
super.layoutSubviews()
render()
}
func initSubviews() {
backgroungView.backgroundColor(UIColor.black)
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(hide))
backgroungView.addGestureRecognizer(tapGesture)
self.addSubview(backgroungView)
contentView.layer.cornerRadius = 10.0
contentView.layer.masksToBounds = true
self.addSubview(contentView)
titleLabel.textColor(CIComponentKitThemeCurrentConfig.tintColor).line(0)
contentView.contentView.addSubview(titleLabel)
messageLabel.label.textColor(CIComponentKitThemeCurrentConfig.alertMessageColor)
contentView.contentView.addSubview(messageLabel)
}
func render() {
backgroungView.frame(self.bounds)
// calculate size of content
contentView.x(contentMargins.left).backgroundColor(CIComponentKitThemeCurrentConfig.mainColor)
.width(self.cic.width - contentMargins.left - contentMargins.right)
titleLabel.text(title)
.font(UIFont.cic.preferred(.headline))
.textColor(CIComponentKitThemeCurrentConfig.tintColor)
.x(contentInsets.left)
.y(contentInsets.top)
.width(contentView.cic.width - contentInsets.left - contentInsets.right)
.sizeTo(layout: .width(titleLabel.cic.width))
// calculate message height
messageLabel.axis = .vertical(maxWidth: titleLabel.cic.width)
messageLabel.label.text(message)
.font(UIFont.cic.preferred(.body))
.textColor(CIComponentKitThemeCurrentConfig.alertMessageColor)
.width(titleLabel.cic.width)
let messageHeight = (message ?? "").cicHeight(titleLabel.cic.width, font: UIFont.cic.preferred(.body))
messageLabel.x(titleLabel.cic.x)
.y(titleLabel.frame.maxY + 15)
.width(titleLabel.cic.width)
.height(.minimum(messageHeight, self.cic.height * 0.7))
.layout()
contentView.height(messageLabel.frame.maxY + contentInsets.bottom)
.y(self.cic.height - contentView.cic.height - contentMargins.bottom)
}
@objc func hide() {
self.removeFromSuperview()
}
}
public class func showGuide(_ title: String = "提示", message: String? = nil, animated: Bool = true) {
let guide = GuideView()
guide.title = title
guide.message = message
if let keyWindow = UIApplication.shared.keyWindow {
guide.frame(keyWindow.bounds)
if !animated {
keyWindow.addSubview(guide)
} else {
keyWindow.addSubview(guide)
guide.backgroungView.alpha = 0
UIView.animate(withDuration: 0.35, animations: {
guide.backgroungView.alpha = 0.6
})
let destinationY = guide.contentView.cic.y
guide.contentView.y(guide.cic.height)
UIView.cic.spring({
guide.contentView.y(destinationY)
})
}
}
}
}
| mit | 07acba7e684b9067594abf31696b30de | 35.136691 | 114 | 0.594266 | 4.820537 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/SchemeHandler/SchemeHandler+ArticleSectionHandler.swift | 3 | 3155 | import Foundation
protocol ArticleSectionHandlerCacheDelegate: class {
func article(for key: String) -> MWKArticle?
func cacheSectionData(for article: MWKArticle)
}
extension SchemeHandler {
final class ArticleSectionHandler: BaseSubHandler {
weak var cacheDelegate: ArticleSectionHandlerCacheDelegate?
required init(cacheDelegate: ArticleSectionHandlerCacheDelegate) {
self.cacheDelegate = cacheDelegate
}
override class var basePath: String? {
return "articleSectionData"
}
static let articleKeyQueryItemName = "articleKey"
static let imageWidthQueryItemName = "imageWidth"
static func appSchemeURL(for articleURL: URL, targetImageWidth: Int) -> URL? {
guard let key = articleURL.wmf_databaseKey,
let basePath = basePath else {
return nil
}
var components = baseURLComponents
components.path = NSString.path(withComponents: ["/", basePath])
let articleKeyQueryItem = URLQueryItem(name: articleKeyQueryItemName, value: key)
let imageWidthString = String(format: "%lli", targetImageWidth)
let imageWidthQueryItem = URLQueryItem(name: imageWidthQueryItemName, value: imageWidthString)
components.queryItems = [articleKeyQueryItem, imageWidthQueryItem]
return components.url
}
func handle(pathComponents: [String], requestURL: URL, completion: @escaping (URLResponse?, Data?, Error?) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
guard let articleKey = (requestURL as NSURL).wmf_value(forQueryKey: ArticleSectionHandler.articleKeyQueryItemName) else {
completion(nil, nil, SchemeHandlerError.invalidParameters)
return
}
guard let article = self.cacheDelegate?.article(for: articleKey) else {
completion(nil, nil, SchemeHandlerError.invalidParameters)
return
}
guard let imageWidthString = (requestURL as NSURL).wmf_value(forQueryKey: ArticleSectionHandler.imageWidthQueryItemName),
(imageWidthString as NSString).integerValue > 0 else {
completion(nil, nil, SchemeHandlerError.invalidParameters)
return
}
let imageWidth = (imageWidthString as NSString).integerValue
guard let json = WMFArticleJSONCompilationHelper.jsonData(for: article, withImageWidth: imageWidth) else {
completion(nil, nil, SchemeHandlerError.invalidParameters)
return
}
let response = HTTPURLResponse(url: requestURL, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "application/json; charset=utf-8"])
completion(response, json, nil)
}
}
}
}
| mit | 7cb7f84eebcc693fe1fa055e7a230706 | 44.071429 | 165 | 0.603803 | 5.831793 | false | false | false | false |
duliodenis/v | V/V/Model/CoreDataStack.swift | 1 | 1498 | //
// CoreDataStack.swift
// V
//
// Created by Dulio Denis on 5/15/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStack {
static let sharedInstance = CoreDataStack()
lazy var storesDirectory: NSURL = {
let fm = NSFileManager.defaultManager()
let urls = fm.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var localStoreURL: NSURL = {
let url = self.storesDirectory.URLByAppendingPathComponent("V.sqlite")
return url
}()
lazy var modelURL: NSURL = {
let bundle = NSBundle.mainBundle()
if let url = bundle.URLForResource("Model", withExtension: "momd") {
return url
}
print("CRITICAL - Managed Object Model file not found")
abort()
}()
lazy var model: NSManagedObjectModel = {
return NSManagedObjectModel(contentsOfURL:self.modelURL)!
}()
lazy var coordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.model)
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: self.localStoreURL, options: nil)
} catch {
print("Could not add the peristent store")
abort()
}
return coordinator
}()
} | mit | e77628a995594c1b3fe529dfb0a3abc9 | 25.75 | 132 | 0.621242 | 5.252632 | false | false | false | false |
Mattmlm/codepathrottentomatoes | Rotten Tomatoes/Rotten Tomatoes/MovieTableViewCell.swift | 1 | 1311 | //
// MovieTableViewCell.swift
// Rotten Tomatoes
//
// Created by admin on 9/15/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class MovieTableViewCell: UITableViewCell {
@IBOutlet weak var movieCoverImageView: UIImageView!
@IBOutlet weak var movieTitleLabel: UILabel!
@IBOutlet weak var movieDescriptionLabel: UILabel!
@IBOutlet weak var movieRatingLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
self.movieCoverImageView.image = nil;
self.movieCoverImageView.alpha = 0.2;
self.movieTitleLabel.text = "";
self.movieDescriptionLabel.text = "";
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func layoutSubviews() {
super.layoutSubviews();
UIView.animateWithDuration(1) { () -> Void in
self.movieCoverImageView.alpha = 1;
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setMovieCover(movieData: NSDictionary) {
RTAPISupport.setMovieCover(self.movieCoverImageView, movieData: movieData);
}
}
| mit | f94d9fc31acd4af7640695f770550dcf | 26.291667 | 83 | 0.654198 | 4.661922 | false | false | false | false |
jtbandes/swift | benchmark/single-source/ObserverUnappliedMethod.swift | 21 | 1291 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
class Observer {
@inline(never)
func receive(_ value: Int) {
}
}
protocol Sink {
func receive(_ value: Int)
}
struct Forwarder<Object>: Sink {
let object: Object
let method: (Object) -> (Int) -> ()
func receive(_ value: Int) {
method(object)(value)
}
}
class Signal {
var observers: [Sink] = []
func subscribe(_ sink: Sink) {
observers.append(sink)
}
func send(_ value: Int) {
for observer in observers {
observer.receive(value)
}
}
}
public func run_ObserverUnappliedMethod(_ iterations: Int) {
let signal = Signal()
let observer = Observer()
for _ in 0 ..< 10_000 * iterations {
let forwarder = Forwarder(object: observer, method: Observer.receive)
signal.subscribe(forwarder)
}
signal.send(1)
}
| apache-2.0 | 04cbf6391cacd5664c38581116621001 | 22.907407 | 80 | 0.584043 | 4.111465 | false | false | false | false |
vmachiel/swift | LearningSwift.playground/Pages/Value vs Reference Types.xcplaygroundpage/Contents.swift | 1 | 3163 | // Also in Classes and Objects
// First, structs and enums are value type and classes are reference type.
// The previous sentence is horrendous. It doesn’t make sense for beginners.
// Okay let me explain. In Classes, when you make a
// copy of a reference type variable, both variables are referring to the same object
// in memory. A change to one of the variables will change the other. In Structs,
// however, you simply copy and paste variables by creating a separate object.
// Again, think of the analogy I used: textbook answer keys (Class) vs whole new
// textbooks (Struct)
struct SomeStruct {
var property = "original"
}
class SomeClass {
var property = "original"
}
// Create instances of both
var valueType = SomeStruct()
var referenceType = SomeClass()
// Make a copy of both that you don't need to change
let valueTypeCopy = valueType
let referenceTypeCopy = referenceType
// Change the original properties:
valueType.property = "new"
referenceType.property = "new"
// And now the copies are:
valueTypeCopy.property
referenceTypeCopy.property
// The original struct didn't change, because you it's a value type: when you made the
// copy, a whole new object was created. A class is a referrence type: when you made the
// the copy, you really just made a second way to refer to the existing object. When you
// changed the orginial object, the second refference "sees" the change as well and thus
// changes from your perspective.
// Enums are like structs: valuetypes:
enum SomeEnum: Int {
case property = 1
case property2
}
var valueType2 = SomeEnum(rawValue: 1)
let valueType2Copy = valueType2
valueType2 = SomeEnum(rawValue: 2)
valueType2Copy
// Extra from the CS193P course.
// value types assigned to constants are IMMUTABLE. In the viewcontroller of calc,
// we assigned the calc brain (struct) to a var. Everytime a mutable function is called,
// it's changed by copying! Copy on write. If it were a let, you couldn't call
// any mutable functions.
// Reference types are stored in the heap, and only a pointer is assigned to a
// var or constant.
// If you assign a reference type to a constant let x = Someclass, you can still
// change properties and called methods that do that. The stuff in the heap gets
// changes, the pointer to it stays the same, which is stored in the constant.
// Using structs as much a possible is like functional programming. With classes,
// you can have multiple locations pointing to one object, all of whom can change that
// object (side effects). When you use structs, if another var or constant is set to
// that data, it copies it. So when one of them calls a method, it's like func.
// programming: data goes in, predictable data comes out.
// This is new to macOS and iOS, which were designed with ref. types only in mind
// Swift has powerful structs, protocols and generics, making proper func. programming
// possible.
// Always keep immutability in mind when designing with swift. If you can do!, it's way
// easier to test math function instead of mutable classes with many pointers to them
// and having to set up a lot of stuff.
| mit | 25bb20712d599ef5cd9d9972543f23fb | 32.273684 | 88 | 0.745334 | 4.089263 | false | false | false | false |
esheppard/travel-lingo | xcode/Travel Lingo/Source/Repositories/Preferences.swift | 1 | 1673 | //
// Preferences.swift
// Travel Lingo
//
// Created by Elijah Sheppard on 20/04/2016.
// Copyright © 2016 Elijah Sheppard. All rights reserved.
//
import Foundation
private let HomeLanguageKey = "homeLanguage"
private let LastLanguageKey = "lastLanguage"
private let defaults = NSUserDefaults.standardUserDefaults()
private let _PreferencesInstance = Preferences()
class Preferences
{
class var sharedPrefs: Preferences
{
return _PreferencesInstance
}
private init()
{
registerDefaults()
}
// MARK: - Values
var homeLanguage: String?
{
set
{
defaults.setObject(newValue!, forKey: HomeLanguageKey)
defaults.synchronize()
}
get
{
return defaults.stringForKey(HomeLanguageKey)
}
}
var lastLanguage: String?
{
set
{
defaults.setObject(newValue!, forKey: LastLanguageKey)
defaults.synchronize()
}
get
{
return defaults.stringForKey(LastLanguageKey)
}
}
// MARK: - Setup
private func registerDefaults()
{
var defaultValues: [String: AnyObject] = [
HomeLanguageKey: "english",
LastLanguageKey: "arabic"
]
// find the users preferred language
if let languageCode = preferredLanguageCodeIso639()
{
if let mapping = iso639MappingForLanguageCode(languageCode) {
defaultValues[HomeLanguageKey] = mapping.language
}
}
defaults.registerDefaults(defaultValues)
}
}
| gpl-3.0 | 9553c9ccfebd5cf1b25bd6c69ed85c78 | 19.9 | 73 | 0.583134 | 4.860465 | false | false | false | false |
LQJJ/demo | 125-iOSTips-master/Demo/40.给UICollectionView的Cell添加左滑删除/EditingCollectionView/UIView+Extensions.swift | 1 | 654 | //
// UIView+Extensions.swift
// EditingCollectionView
//
// Created by Dariel on 2019/1/8.
// Copyright © 2019年 Dariel. All rights reserved.
//
import UIKit
extension UIView {
func pinEdgesToSuperView() {
guard let superView = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
topAnchor.constraint(equalTo: superView.topAnchor).isActive = true
leftAnchor.constraint(equalTo: superView.leftAnchor).isActive = true
bottomAnchor.constraint(equalTo: superView.bottomAnchor).isActive = true
rightAnchor.constraint(equalTo: superView.rightAnchor).isActive = true
}
}
| apache-2.0 | f9955e64344f925187156f314c3ac769 | 30 | 80 | 0.72043 | 4.822222 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Controllers/ZSShelfViewController.swift | 1 | 16395 | //
// ZSShelfViewController.swift
// zhuishushenqi
//
// Created by yung on 2018/7/31.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
import RxSwift
import SafariServices
import MJRefresh
class ZSShelfViewController: BaseViewController,Refreshable,UITableViewDataSource,UITableViewDelegate {
lazy var shelfMsg:UIButton = {
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 44)
btn.backgroundColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.7 )
btn.setTitleColor(UIColor.gray, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
return btn
}()
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .grouped)
tableView.qs_registerCellClass(SwipableCell.self)
tableView.rowHeight = ZSShelfViewController.kCellHeight
tableView.estimatedRowHeight = ZSShelfViewController.kCellHeight
tableView.dataSource = self
tableView.delegate = self
tableView.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
return tableView
}()
fileprivate let kHeaderBigHeight:CGFloat = 44
static let kCellHeight:CGFloat = 60
fileprivate let disposeBag = DisposeBag()
var headerRefresh:MJRefreshHeader?
let viewModel = ZSShelfViewModel()
override func viewDidLoad() {
super.viewDidLoad()
setupSubviews()
NotificationCenter.qs_addObserver(observer: self, selector: #selector(loginSuccessAction), name: LoginSuccess, object: nil)
NotificationCenter.qs_addObserver(observer: self, selector: #selector(addBookToShelf(noti:)), name: BOOKSHELF_ADD, object: nil)
NotificationCenter.qs_addObserver(observer: self, selector: #selector(deleteFromShelf(noti:)), name: BOOKSHELF_DELETE, object: nil)
loginSuccessAction()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
}
self.navigationController?.navigationBar.barTintColor = UIColor ( red: 0.7235, green: 0.0, blue: 0.1146, alpha: 1.0 )
self.tableView.reloadData()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupSubviews(){
let header = initRefreshHeader(tableView) {
self.viewModel.fetchShelvesBooks(completion: { (_) in
self.view.showTip(tip: "更新了几本书")
self.tableView.reloadData()
})
self.viewModel.fetchShelfMessage(completion: { (_) in
self.tableView.reloadData()
})
}
headerRefresh = header
headerRefresh?.beginRefreshing()
viewModel
.autoSetRefreshHeaderStatus(header: header, footer: nil)
.disposed(by: disposeBag)
view.addSubview(tableView)
viewModel.fetchBlessingBag(token: ZSLogin.share.token) { (json) in
print(json)
}
viewModel.fetchJudgeIn(token: ZSLogin.share.token) { (json) in
if json?["ok"] as? Bool == true {
if let activityId = json?["activityId"] as? String {
self.viewModel.fetchSignIn(token: ZSLogin.share.token, activityId: activityId, version: "2", type: "2", completion: { (json) in
if json?["ok"] as? Bool == true {
print("签到成功")
let amount = json?["amount"] as? Int ?? 0
self.view.showTip(tip: "自动签到获得\(amount)书券")
}
})
}
}
}
shelfMsg.addTarget(self, action: #selector(openSafari), for: .touchUpInside)
}
@objc
func openSafari() {
// 存在三种可能,post,link,booklist
if let message = viewModel.shelfMessage {
let title = message.postMessage()
let type = title.2
if type == .link {
if let url = URL(string: title.0) {
let safariVC = SFSafariViewController(url: url)
self .present(safariVC, animated: true, completion: nil)
}
} else if type == .post {
let id = title.0
let comment = BookComment()
comment._id = id
let commentVC = ZSBookCommentViewController(style: .grouped)
commentVC.viewModel.model = comment
SideVC.navigationController?.pushViewController(commentVC, animated: true)
} else if type == .booklist {
let topicVC = QSTopicDetailRouter.createModule(id: title.0)
SideVC.navigationController?.pushViewController(topicVC, animated: true)
}
}
}
@objc
func loginSuccessAction() {
viewModel.fetchShelfAdd(books: viewModel.books.allValues() as! [BookDetail], token: ZSLogin.share.token) { (json) in
if json?["ok"] as? Bool == true {
self.view.showTip(tip: "书架书籍上传成功")
} else {
self.view.showTip(tip: "书架书籍上传失败")
}
}
viewModel.fetchUserBookshelf(token: ZSLogin.share.token) { (bookshelf) in
self.viewModel.fetchShelvesBooks(completion: { (_) in
self.view.showTip(tip: "更新了几本书")
self.tableView.reloadData()
})
self.tableView.reloadData()
}
}
@objc
func deleteFromShelf(noti:Notification) {
if let book = noti.object as? BookDetail {
self.tableView.reloadData()
if ZSLogin.share.hasLogin() {
viewModel.fetchShelfDelete(books: [book], token: ZSLogin.share.token) { (json) in
if json?["ok"] as? Bool == true {
self.view.showTip(tip: "\(book.title)从书架删除成功")
self.headerRefresh?.beginRefreshing()
} else {
self.view.showTip(tip: "\(book.title)从书架删除失败")
}
}
}
}
}
@objc
func addBookToShelf(noti:Notification) {
if let book = noti.object as? BookDetail {
self.tableView.reloadData()
if ZSLogin.share.hasLogin() {
viewModel.fetchShelfAdd(books: [book], token: ZSLogin.share.token) { (json) in
if json?["ok"] as? Bool == true {
self.view.showTip(tip: "添加到书架成功")
self.headerRefresh?.beginRefreshing()
} else {
self.view.showTip(tip: "添加到书架失败")
}
}
} else {
self.view.showTip(tip: "添加到书架成功")
self.headerRefresh?.beginRefreshing()
}
}
}
//MARK: - UITableView
func numberOfSections(in tableView: UITableView) -> Int {
if viewModel.localBooks.count > 0 {
return 2
}
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if viewModel.localBooks.count > 0 {
if section == 0 {
return 1
}
return viewModel.books.count
}
// return viewModel.fetchBooks().count
return viewModel.booksID.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SwipableCell.reuseIdentifier, for: indexPath) as! SwipableCell
cell.delegate = self
cell.selectionStyle = .none
if viewModel.localBooks.count > 0 {
if indexPath.section == 0 {
cell.title?.text = "本地书架"
return cell
}
let id = viewModel.booksID[indexPath.row]
if let item = viewModel.books[id] {
cell.configureCell(model: item)
}
} else {
// let book = viewModel.fetchBooks()[indexPath.row]
// cell.configureCell(model: book)
if viewModel.booksID.count > indexPath.row {
let id = viewModel.booksID[indexPath.row]
if let item = viewModel.books[id] {
cell.configureCell(model: item)
}
}
}
return cell
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if viewModel.localBooks.count > 0 {
if section == 0 {
if let message = viewModel.shelfMessage {
let title = message.postMessage()
shelfMsg.setTitle(title.1, for: .normal)
shelfMsg.setTitleColor(title.3, for: .normal)
return shelfMsg
}
}
} else {
if section == 0 {
if let message = viewModel.shelfMessage {
let title = message.postMessage()
shelfMsg.setTitle(title.1, for: .normal)
shelfMsg.setTitleColor(title.3, for: .normal)
return shelfMsg
}
}
}
return UIView()
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if viewModel.localBooks.count > 0 {
if section == 0 {
if let _ = viewModel.shelfMessage?.postLink {
return kHeaderBigHeight
}
}
} else {
if section == 0 {
if let _ = viewModel.shelfMessage?.postLink {
return kHeaderBigHeight
}
}
}
return 1
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// if let url = URL(string: "IFlySpeechPlus://?version=1.006&businessType=1&callType=0") {
// UIApplication.shared.openURL(url)
// return
// }
if viewModel.localBooks.count > 0 {
if indexPath.section == 0 {
let localVC = ZSLocalShelfViewController()
SideVC.navigationController?.pushViewController(localVC, animated: true)
return
}
}
// let books = viewModel.fetchBooks()
// let viewController = ZSReaderViewController()
// viewController.viewModel.book = books[indexPath.row]
// self.present(viewController, animated: true, completion: nil)
// self.tableView.reloadRow(at: indexPath, with: .automatic)
let books = self.viewModel.books
if let model = books[viewModel.booksID[indexPath.row]] {
// 刷新id的排序,当前点击的书籍置顶
viewModel.topBook(key: model._id)
let viewController = ZSReaderViewController()
viewController.viewModel.book = model
self.present(viewController, animated: true, completion: nil)
self.tableView.reloadData()
}
}
}
extension ZSShelfViewController:SwipableCellDelegate {
func swipableCell(swipableCell:SwipableCell, didSelectAt index:Int) {
if index == 0 {
if let indexPath = tableView.indexPath(for: swipableCell) {
alert(with: swipableCell, indexPath: indexPath)
} else {
self.hudAddTo(view: self.view, text: "当前书籍不存在...", animated: true)
}
}
else if index == 3 {
if let indexPath = tableView.indexPath(for: swipableCell) {
self.removeBook(at: indexPath.row)
}
self.tableView.reloadData()
} else {
self.hudAddTo(view: self.view, text: "暂不支持当前功能,敬请期待...", animated: true)
}
}
func alert(with cell:SwipableCell, indexPath:IndexPath) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let firstAcion = UIAlertAction(title: "全本缓存", style: .default, handler: { (action) in
cell.state = .prepare
let ids = self.viewModel.booksID
if indexPath.row >= 0 && indexPath.row < ids.count {
let id = ids[indexPath.row]
guard let book = self.viewModel.books[id] else { return }
cell.state = .download
ZSBookDownloader.shared.download(book: book, start: 0, handler: { (finish) in
// cell状态变更
cell.state = .finish
})
} else {
cell.state = .none
}
})
let secondAction = UIAlertAction(title: "从当前章节缓存", style: .default, handler: { (action) in
cell.state = .prepare
let ids = self.viewModel.booksID
if indexPath.row > 0 && indexPath.row < ids.count {
let id = ids[indexPath.row]
guard let book = self.viewModel.books[id] else { return }
if let chapter = book.record?.chapter, let chaptersInfo = book.chaptersInfo {
cell.state = .download
if chapter < chaptersInfo.count {
ZSBookDownloader.shared.download(book: book, start: chapter, handler: { (finish) in
// cell状态变更
cell.state = .finish
})
} else {
ZSBookDownloader.shared.download(book: book, start: 0, handler: { (finish) in
// cell状态变更
cell.state = .finish
})
}
} else {
cell.state = .none
}
} else {
cell.state = .none
}
})
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
cell.state = .none
})
alert.addAction(firstAcion)
alert.addAction(secondAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
func removeBook(at index:Int){
let books = self.viewModel.booksID
guard let bookid = books[safe: index] else {
return
}
if let book = self.viewModel.books[bookid] {
ZSBookManager.shared.deleteBook(book: book)
self.viewModel.fetchShelfDelete(books: [book], token: ZSLogin.share.token) { (json) in
if json?["ok"] as? Bool == true {
self.view.showTip(tip: "\(book.title)已从书架中删除")
} else {
self.view.showTip(tip: "\(book.title)从书架中删除失败")
}
}
} else {
let book = BookDetail()
book._id = bookid
ZSBookManager.shared.deleteBook(book: book)
}
}
}
| mit | 86b5592d156e3b16c1eb73d41d23b3e7 | 36.915094 | 147 | 0.543792 | 4.690983 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Layers/Control annotation sublayer visibility/ControlAnnotationSublayerVisibilitySublayersViewController.swift | 1 | 4536 | //
// Copyright © 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import ArcGIS
class ControlAnnotationSublayerVisibilitySublayersViewController: UITableViewController {
var annotationSublayers = [AGSAnnotationSublayer]() {
didSet {
guard isViewLoaded else { return }
tableView.reloadData()
}
}
var mapScale = Double.nan {
didSet {
mapScaleDidChange(oldValue)
}
}
/// The formatter used to generate strings from scale values.
private let scaleFormatter: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 0
return numberFormatter
}()
/// The observation of the table view's content size.
private var tableViewContentSizeObservation: NSKeyValueObservation?
func title(for annotationSublayer: AGSAnnotationSublayer) -> String {
let maxScale = annotationSublayer.maxScale
let minScale = annotationSublayer.minScale
var title = annotationSublayer.name
if !(maxScale.isNaN || minScale.isNaN) {
let maxScaleString = scaleFormatter.string(from: maxScale as NSNumber)!
let minScaleString = scaleFormatter.string(from: minScale as NSNumber)!
title.append(String(format: " (1:%@ - 1:%@)", maxScaleString, minScaleString))
}
return title
}
func mapScaleDidChange(_ previousMapScale: Double) {
var indexPaths = [IndexPath]()
for row in annotationSublayers.indices {
let annotationSublayer = annotationSublayers[row]
let wasVisible = annotationSublayer.isVisible(atScale: previousMapScale)
let isVisible = annotationSublayer.isVisible(atScale: mapScale)
if isVisible != wasVisible {
let indexPath = IndexPath(row: row, section: 0)
indexPaths.append(indexPath)
}
}
if !indexPaths.isEmpty {
tableView.reloadRows(at: indexPaths, with: .automatic)
}
}
// MARK: UIViewController
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableViewContentSizeObservation = tableView.observe(\.contentSize) { [unowned self] (tableView, _) in
self.preferredContentSize.height = tableView.contentSize.height
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
tableViewContentSizeObservation = nil
}
}
extension ControlAnnotationSublayerVisibilitySublayersViewController: ControlAnnotationSublayerVisibilitySublayerCellDelegate {
func sublayerCellDidToggleSwitch(_ sublayerCell: ControlAnnotationSublayerVisibilitySublayerCell) {
guard let indexPath = tableView.indexPath(for: sublayerCell) else {
return
}
annotationSublayers[indexPath.row].isVisible = sublayerCell.switch.isOn
}
}
extension ControlAnnotationSublayerVisibilitySublayersViewController /* UITableViewDataSource */ {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return annotationSublayers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let annotationSublayer = annotationSublayers[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "SublayerCell", for: indexPath) as! ControlAnnotationSublayerVisibilitySublayerCell
cell.textLabel?.text = title(for: annotationSublayer)
cell.textLabel?.isEnabled = annotationSublayer.isVisible(atScale: mapScale)
cell.switch.isOn = annotationSublayer.isVisible
cell.delegate = self
return cell
}
}
| apache-2.0 | e1732618bb314b6077d2db77ee384f9a | 38.094828 | 148 | 0.687982 | 5.341578 | false | false | false | false |
tardieu/swift | test/expr/unary/keypath/keypath.swift | 5 | 4879 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library %s -verify
import ObjectiveC
import Foundation
// REQUIRES: objc_interop
@objc class A : NSObject {
@objc var propB: B = B()
@objc var propString: String = "" // expected-note {{did you mean 'propString'}}
@objc var propArray: [String] = []
@objc var propDict: [String: B] = [:]
@objc var propSet: Set<String> = []
@objc var propNSString: NSString?
@objc var propNSArray: NSArray?
@objc var propNSDict: NSDictionary?
@objc var propNSSet: NSSet?
@objc var propAnyObject: AnyObject?
@objc var ambiguous: String? // expected-note{{'ambiguous' declared here}}
@objc func someMethod() { }
@objc var `repeat`: String?
}
@objc class B : NSObject {
@objc var propA: A?
@objc var ambiguous: String? // expected-note{{'ambiguous' declared here}}
}
class C {
var nonObjC: String? // expected-note{{add '@objc' to expose this var to Objective-C}}{{3-3=@objc }}
}
extension NSArray {
@objc class Foo : NSObject {
@objc var propString: String = ""
}
}
extension Array {
typealias Foo = NSArray.Foo
}
func testKeyPath(a: A, b: B) {
// Property
let _: String = #keyPath(A.propB)
// Chained property
let _: String = #keyPath(A.propB.propA)
// Optional property
let _: String = #keyPath(A.propB.propA.propB)
// String property
let _: String = #keyPath(A.propString)
// Property of String property (which looks on NSString)
let _: String = #keyPath(A.propString.URLsInText)
// Array property (make sure we look at the array element).
let _: String = #keyPath(A.propArray)
let _: String = #keyPath(A.propArray.URLsInText)
// Dictionary property (make sure we look at the value type).
let _: String = #keyPath(A.propDict.anyKeyName)
let _: String = #keyPath(A.propDict.anyKeyName.propA)
// Set property (make sure we look at the set element).
let _: String = #keyPath(A.propSet)
let _: String = #keyPath(A.propSet.URLsInText)
// AnyObject property
let _: String = #keyPath(A.propAnyObject.URLsInText)
let _: String = #keyPath(A.propAnyObject.propA)
let _: String = #keyPath(A.propAnyObject.propB)
let _: String = #keyPath(A.propAnyObject.description)
// NSString property
let _: String = #keyPath(A.propNSString.URLsInText)
// NSArray property (AnyObject array element).
let _: String = #keyPath(A.propNSArray)
let _: String = #keyPath(A.propNSArray.URLsInText)
// NSDictionary property (AnyObject value type).
let _: String = #keyPath(A.propNSDict.anyKeyName)
let _: String = #keyPath(A.propNSDict.anyKeyName.propA)
// NSSet property (AnyObject set element).
let _: String = #keyPath(A.propNSSet)
let _: String = #keyPath(A.propNSSet.URLsInText)
// Property with keyword name.
let _: String = #keyPath(A.repeat)
// Nested type of a bridged type (rdar://problem/28061409).
typealias IntArray = [Int]
let _: String = #keyPath(IntArray.Foo.propString)
let dict: [String: Int] = [:]
let _: Int? = dict[#keyPath(A.propB)]
}
func testAsStaticString() {
let _: StaticString = #keyPath(A.propB)
}
func testSemanticErrors() {
let _: String = #keyPath(A.blarg) // expected-error{{type 'A' has no member 'blarg'}}
let _: String = #keyPath(blarg) // expected-error{{use of unresolved identifier 'blarg'}}
let _: String = #keyPath(AnyObject.ambiguous) // expected-error{{ambiguous reference to member 'ambiguous'}}
let _: String = #keyPath(C.nonObjC) // expected-error{{argument of '#keyPath' refers to non-'@objc' property 'nonObjC'}}
let _: String = #keyPath(A.propArray.UTF8View) // expected-error{{type 'String' has no member 'UTF8View'}}
let _: String = #keyPath(A.someMethod) // expected-error{{'#keyPath' cannot refer to instance method 'someMethod()'}}
let _: String = #keyPath(A) // expected-error{{empty '#keyPath' does not refer to a property}}
let _: String = #keyPath(A.propDict.anyKeyName.unknown) // expected-error{{type 'B' has no member 'unknown'}}
let _: String = #keyPath(A.propNSDict.anyKeyName.unknown) // expected-error{{type 'AnyObject' has no member 'unknown'}}
}
func testParseErrors() {
let _: String = #keyPath; // expected-error{{expected '(' following '#keyPath'}}
let _: String = #keyPath(123; // expected-error{{expected property or type name within '#keyPath(...)'}}
let _: String = #keyPath(a.123; // expected-error{{expected property or type name within '#keyPath(...)'}}
let _: String = #keyPath(A(b:c:d:).propSet); // expected-error{{cannot use compound name 'A(b:c:d:)' in '#keyPath' expression}}
let _: String = #keyPath(A.propString; // expected-error{{expected ')' to complete '#keyPath' expression}}
// expected-note@-1{{to match this opening '('}}
}
func testTypoCorrection() {
let _: String = #keyPath(A.proString) // expected-error {{type 'A' has no member 'proString'}}
}
| apache-2.0 | 6ce63038c2f5382090e218d4161f6b47 | 35.684211 | 129 | 0.677393 | 3.624814 | false | false | false | false |
tkremenek/swift | test/decl/async/objc.swift | 1 | 1782 | // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 5 -enable-experimental-concurrency -disable-availability-checking
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 5 -enable-experimental-concurrency | %FileCheck %s
// REQUIRES: objc_interop
// REQUIRES: concurrency
import Foundation
import ObjectiveC
@objc protocol P {
func doBigJob() async -> Int
}
// Infer @objc from protocol conformance
// CHECK: class ConformsToP
class ConformsToP: P {
// CHECK: @objc func doBigJob() async -> Int
func doBigJob() async -> Int { 5 }
}
// Infer @objc from superclass
class Super {
@objc func longRunningRequest() async throws -> [String] { [] }
}
// CHECK: class Sub
class Sub : Super {
// CHECK-NEXT: @objc override func longRunningRequest() async throws -> [String]
override func longRunningRequest() async throws -> [String] { [] }
}
// Check selector computation.
@objc protocol MakeSelectors {
func selectorAsync() async -> Int
func selector(value: Int) async -> Int
}
func testSelectors() {
// expected-warning@+1{{use '#selector' instead of explicitly constructing a 'Selector'}}
_ = Selector("selectorAsyncWithCompletionHandler:")
// expected-warning@+1{{use '#selector' instead of explicitly constructing a 'Selector'}}
_ = Selector("selectorWithValue:completionHandler:")
_ = Selector("canary:") // expected-warning{{no method declared with Objective-C selector 'canary:'}}
// expected-note@-1{{wrap the selector name in parentheses to suppress this warning}}
}
| apache-2.0 | b7f11121b4803355b7a8592ded09ef8e | 38.6 | 318 | 0.734568 | 4.040816 | false | false | false | false |
kar1m/firefox-ios | UITests/Global.swift | 1 | 7759 | /* 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 Storage
import WebKit
let LabelAddressAndSearch = "Address and Search"
extension XCTestCase {
func tester(_ file: String = __FILE__, _ line: Int = __LINE__) -> KIFUITestActor {
return KIFUITestActor(inFile: file, atLine: line, delegate: self)
}
func system(_ file: String = __FILE__, _ line: Int = __LINE__) -> KIFSystemTestActor {
return KIFSystemTestActor(inFile: file, atLine: line, delegate: self)
}
}
extension KIFUITestActor {
/// Looks for a view with the given accessibility hint.
func tryFindingViewWithAccessibilityHint(hint: String) -> Bool {
let element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in
return element.accessibilityHint == hint
}
return element != nil
}
/**
* Finding views by accessibility label doesn't currently work with WKWebView:
* https://github.com/kif-framework/KIF/issues/460
* As a workaround, inject a KIFHelper class that iterates the document and finds
* elements with the given textContent or title.
*/
func waitForWebViewElementWithAccessibilityLabel(text: String) {
let webView = waitForViewWithAccessibilityLabel("Web content") as! WKWebView
// Wait for the webView to stop loading.
runBlock({ _ in
return webView.loading ? KIFTestStepResult.Wait : KIFTestStepResult.Success
})
lazilyInjectKIFHelper(webView)
var stepResult = KIFTestStepResult.Wait
let escaped = text.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
webView.evaluateJavaScript("KIFHelper.selectElementWithAccessibilityLabel(\"\(escaped)\");", completionHandler: { (result: AnyObject!, error: NSError!) in
stepResult = result as! Bool ? KIFTestStepResult.Success : KIFTestStepResult.Failure
})
runBlock({ (error: NSErrorPointer) in
if stepResult == KIFTestStepResult.Failure {
error.memory = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Accessibility label not found in webview: \(escaped)"])
}
return stepResult
})
}
private func lazilyInjectKIFHelper(webView: WKWebView) {
var stepResult = KIFTestStepResult.Wait
webView.evaluateJavaScript("typeof KIFHelper;", completionHandler: { (result: AnyObject!, error: NSError!) in
if result as! String == "undefined" {
let bundle = NSBundle(forClass: NavigationTests.self)
let path = bundle.pathForResource("KIFHelper", ofType: "js")!
let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)!
webView.evaluateJavaScript(source as String, completionHandler: nil)
}
stepResult = KIFTestStepResult.Success
})
runBlock({ _ in
return stepResult
})
}
public func deleteCharacterFromFirstResponser() {
enterTextIntoCurrentFirstResponder("\u{0008}")
}
// TODO: Click element, etc.
}
class BrowserUtils {
/// Close all tabs to restore the browser to startup state.
class func resetToAboutHome(tester: KIFUITestActor) {
if tester.tryFindingTappableViewWithAccessibilityLabel("Cancel", error: nil) {
tester.tapViewWithAccessibilityLabel("Cancel")
}
tester.tapViewWithAccessibilityLabel("Show Tabs")
let tabsView = tester.waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView
while tabsView.numberOfItemsInSection(0) > 1 {
let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))!
tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left)
tester.waitForAbsenceOfViewWithAccessibilityLabel(cell.accessibilityLabel)
}
// When the last tab is closed, the tabs tray will automatically be closed
// since a new about:home tab will be selected.
let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))!
tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left)
tester.waitForTappableViewWithAccessibilityLabel("Show Tabs")
}
/// Injects a URL and title into the browser's history database.
class func addHistoryEntry(title: String, url: NSURL) {
let notificationCenter = NSNotificationCenter.defaultCenter()
var info = [NSObject: AnyObject]()
info["url"] = url
info["title"] = title
info["visitType"] = VisitType.Link.rawValue
notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info)
}
}
class SimplePageServer {
class func getPageData(name: String, ext: String = "html") -> String {
var pageDataPath = NSBundle(forClass: self).pathForResource(name, ofType: ext)!
return NSString(contentsOfFile: pageDataPath, encoding: NSUTF8StringEncoding, error: nil)! as String
}
class func start() -> String {
let webServer: GCDWebServer = GCDWebServer()
webServer.addHandlerForMethod("GET", path: "/image.png", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
let img = UIImagePNGRepresentation(UIImage(named: "back"))
return GCDWebServerDataResponse(data: img, contentType: "image/png")
}
for page in ["noTitle", "readablePage"] {
webServer.addHandlerForMethod("GET", path: "/\(page).html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
return GCDWebServerDataResponse(HTML: self.getPageData(page))
}
}
// we may create more than one of these but we need to give them uniquie accessibility ids in the tab manager so we'll pass in a page number
webServer.addHandlerForMethod("GET", path: "/scrollablePage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
var pageData = self.getPageData("scrollablePage")
let page = (request.query["page"] as! String).toInt()!
pageData = pageData.stringByReplacingOccurrencesOfString("{page}", withString: page.description)
return GCDWebServerDataResponse(HTML: pageData as String)
}
webServer.addHandlerForMethod("GET", path: "/numberedPage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
var pageData = self.getPageData("numberedPage")
let page = (request.query["page"] as! String).toInt()!
pageData = pageData.stringByReplacingOccurrencesOfString("{page}", withString: page.description)
return GCDWebServerDataResponse(HTML: pageData as String)
}
webServer.addHandlerForMethod("GET", path: "/readerContent.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
return GCDWebServerDataResponse(HTML: self.getPageData("readerContent"))
}
if !webServer.startWithPort(0, bonjourName: nil) {
XCTFail("Can't start the GCDWebServer")
}
// We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our
// history exclusion code (Bug 1188626).
let webRoot = "http://127.0.0.1:\(webServer.port)"
return webRoot
}
}
| mpl-2.0 | cc2a59da2211e0975c8b392ac027e899 | 44.911243 | 163 | 0.675603 | 5.253216 | false | true | false | false |
zhugejunwei/Algorithms-in-Java-Swift-CPP | Sort algorithms/Merge Sort.swift | 1 | 4549 | /*
1. Split the array in half and sort each subarray.
2. Weave the arrays back together in one fluid pass.
O(nlog n) performance
O(n) space
*/
import Darwin
/*
1. Recursion
Function: func merge(), func mergeSort1()
*/
// Merge two subarrays of arr[]
// First subarray is arr[l...m]
// Second subarray is arr[m+1...r]
func merge(inout arr: [Int], _ l: Int, _ m: Int, _ r: Int)
{
var i = 0, j = 0, k = l // Initial index of first/second/merged subarray
let n1 = m - l + 1 // The length of first subarray
let n2 = r - m // The length of second subarray
// Create tmp arrays
var leftArr = Array(count: n1, repeatedValue: 0)
var rightArr = Array(count: n1, repeatedValue: 0)
for i in 0..<n1 {
leftArr[i] = arr[l + i]
}
for j in 0..<n2 {
rightArr[j] = arr[m + 1 + j]
}
// Merge the tmp arrays back into arr[l...r]
while i < n1 && j < n2 {
if leftArr[i] <= rightArr[j] {
arr[k] = leftArr[i]
i += 1
}else {
arr[k] = rightArr[j]
j += 1
}
k += 1
}
// Copy the remaining elements of leftArr[] into arr[]
while i < n1 {
arr[k] = leftArr[i]
i += 1
k += 1
}
// Copy the remaining elements of rightArr[] into arr[]
while j < n2 {
arr[k] = rightArr[j]
j += 1
k += 1
}
}
func mergeSort(inout arr: [Int], _ l: Int, _ r: Int)
{
if l < r {
let m = l + (r-l)/2
mergeSort(&arr, l, m)
mergeSort(&arr, m+1, r)
merge(&arr, l, m, r)
}
}
print("\n First Solution:")
var myArr = [12, 11, 13, 5, 6, 7]
print("\t Given array is: \(myArr)")
let size = myArr.count
mergeSort(&myArr, 0, size - 1)
print("\t Sorted array is: \(myArr)")
/*
2. Recursion
Function: func mergeSort2()
*/
func mergeSort2(inout arr: [Int], _ l: Int, _ r: Int) -> [Int]
{
if l == r {
return arr
}
let m = l + (r-l)/2
mergeSort2(&arr, l, m)
mergeSort2(&arr, m + 1, r)
var tmp = Array(count: arr.count, repeatedValue: 0)
var f1 = l, f2 = m + 1
for i in l...r {
if f1 > m {
tmp[i] = arr[f2]
f2 += 1
}else if f2 > r {
tmp[i] = arr[f1]
f1 += 1
}else if arr[f1] > arr[f2] {
tmp[i] = arr[f2]
f2 += 1
}else {
tmp[i] = arr[f1]
f1 += 1
}
}
for i in l...r {
arr[i] = tmp[i]
}
return arr
}
print("\n Second Solution:")
var myArr2 = [5,3,2,1,4,6,7]
print("\t Given array is: \(myArr2)")
let size2 = myArr2.count
mergeSort2(&myArr2, 0, size2 - 1)
print("\t Sorted array is: \(myArr2)")
/*
3. Iteration
Function: func mergeSort3()
*/
func mergeSort3(inout arr: [Int], _ n: Int) {
var range = 2, i = 0
while range <= n {
i = 0
while i + range <= n {
merge(&arr, i, i + range/2 - 1, i + range - 1)
i += range
}
// Last and left elements
merge(&arr, i, i + range/2 - 1, n - 1)
range *= 2
}
// The whole array
merge(&arr, 0, range/2-1, n - 1)
}
print("\n Third Solution:")
var myArr3 = [5,3,2,1,4,6,7]
print("\t Given array is: \(myArr3)")
let size3 = myArr3.count
mergeSort3(&myArr3, size3)
print("\t Sorted array is: \(myArr3)")
/*
4. Iteration
Function: func mergeSort()
*/
/*
func pass(inout arr: [Int], inout _ rec: [Int], _ n: Int) -> Int {
var num = 0
var biger = arr[0]
rec[num] = 0
num += 1
for i in 1..<n {
if arr[i] >= biger {
biger = arr[i]
}else {
rec[num] = i
num += 1
biger = arr[i]
}
}
rec[num] = n
num += 1
return num
}
func merge2(inout arr: [Int], _ f: Int, _ e: Int, _ m: Int) {
var tmp = Array(count: arr.count, repeatedValue: 0)
var f1 = f, f2 = m + 1
for i in f...e {
if f1 > m {
tmp[i] = arr[f2]
f2 += 1
}else if f2 > e {
tmp[i] = arr[f1]
f1 += 1
}else if arr[f1] > arr[f2] {
tmp[i] = arr[f2]
f2 += 1
}else {
tmp[i] = arr[f1]
f1 += 1
}
}
for i in f...e {
arr[i] = tmp[i]
}
}
func mergeSort4(inout arr: [Int], _ n: Int) {
var rec = arr
var num = pass(&arr, &rec, n)
while num != 2 {
var i = 0
while i < num {
merge2(&arr, rec[i], rec[i+2]-1, rec[i+1]-1)
i += 2
}
num = pass(&arr, &rec, n)
}
}
print("\n Fourth Solution:")
var arr = [4,2,3,1,5]
print("\t Given array is: \(arr)")
let size4 = arr.count
mergeSort4(&arr, size4)
print("\t Sorted array is: \(arr)")
*/ | mit | 8f0aba5f75a65c9319e74cdc4a66c65c | 18.037657 | 76 | 0.494175 | 2.795943 | false | false | false | false |
kumabook/MusicFav | MusicFav/UIAlertControllerExtension.swift | 1 | 1485 | //
// UIAlertControllerExtension.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 4/11/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import UIKit
extension UIAlertController {
class func show(_ vc: UIViewController, title: String, message: String, handler: @escaping (UIAlertAction!) -> Void) -> UIAlertController {
let ac = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK".localize(), style: UIAlertActionStyle.default, handler: handler)
ac.addAction(okAction)
vc.present(ac, animated: true, completion: nil)
return ac
}
class func showPurchaseAlert(_ vc: UIViewController, title: String, message: String, handler: (UIAlertAction!) -> Void) -> UIAlertController {
let ac = UIAlertController(title: "MusicFav", message: message, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Purchase".localize(), style: .default, handler: {action in
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.paymentManager?.viewController = vc
appDelegate.paymentManager?.purchaseUnlockEverything()
}
}))
ac.addAction(UIAlertAction(title: "Cancel".localize(), style: .cancel, handler: {action in }))
vc.present(ac, animated: true, completion: {})
return ac
}
}
| mit | 539a615deae44c1c31913fb0103d5e3e | 44 | 146 | 0.668687 | 4.699367 | false | false | false | false |
TabletopAssistant/DiceKit | DiceKit/AdditionExpressionResult.swift | 1 | 1630 | //
// AdditionExpressionResult.swift
// DiceKit
//
// Created by Brentley Jones on 7/19/15.
// Copyright © 2015 Brentley Jones. All rights reserved.
//
import Foundation
public struct AdditionExpressionResult<LeftAddendResult: protocol<ExpressionResultType, Equatable>, RightAddendResult: protocol<ExpressionResultType, Equatable>>: Equatable {
public let leftAddendResult: LeftAddendResult
public let rightAddendResult: RightAddendResult
public init(_ leftAddendResult: LeftAddendResult, _ rightAddendResult: RightAddendResult) {
self.leftAddendResult = leftAddendResult
self.rightAddendResult = rightAddendResult
}
}
// MARK: - CustomStringConvertible
extension AdditionExpressionResult: CustomStringConvertible {
public var description: String {
return "\(leftAddendResult) + \(rightAddendResult)"
}
}
// MARK: - CustomDebugStringConvertible
extension AdditionExpressionResult: CustomDebugStringConvertible {
public var debugDescription: String {
return "\(String(reflecting: leftAddendResult)) + \(String(reflecting: rightAddendResult))"
}
}
// MARK: - Equatable
public func == <L, R>(lhs: AdditionExpressionResult<L,R>, rhs: AdditionExpressionResult<L,R>) -> Bool {
return lhs.leftAddendResult == rhs.leftAddendResult && lhs.rightAddendResult == rhs.rightAddendResult
}
// MARK: - ExpressionResultType
extension AdditionExpressionResult: ExpressionResultType {
public var resultValue: ExpressionResultValue {
return leftAddendResult.resultValue + rightAddendResult.resultValue
}
}
| apache-2.0 | a35599e2df2ae07eda7248c37f0b8acb | 27.578947 | 174 | 0.73849 | 4.332447 | false | false | false | false |
JeffESchmitz/RideNiceRide | Pods/Sync/Source/Sync/NSArray+Sync.swift | 1 | 2188 | import Foundation
import DATAStack
import SYNCPropertyMapper
extension NSArray {
/**
Filters the items using the provided predicate, useful to exclude JSON objects from a JSON array by using a predicate.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some items, you just need to provide this predicate.
- parameter parent: The parent of the entity, optional since many entities are orphans.
- parameter dataStack: The DATAStack instance.
*/
func preprocessForEntityNamed(_ entityName: String, predicate: NSPredicate, parent: NSManagedObject?, dataStack: DATAStack, operations: Sync.OperationOptions) -> [[String : Any]] {
var filteredChanges = [[String : Any]]()
let validClasses = [NSDate.classForCoder(), NSNumber.classForCoder(), NSString.classForCoder()]
if let predicate = predicate as? NSComparisonPredicate, let selfArray = self as? [[String : Any]] , validClasses.contains(where: { $0 == predicate.rightExpression.classForCoder }) {
var objectChanges = [NSManagedObject]()
let context = dataStack.newDisposableMainContext()
if let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) {
for objectDictionary in selfArray {
let object = NSManagedObject(entity: entity, insertInto: context)
object.sync_fillWithDictionary(objectDictionary, parent: parent, parentRelationship: nil, dataStack: dataStack, operations: operations)
objectChanges.append(object)
}
guard let filteredArray = (objectChanges as NSArray).filtered(using: predicate) as? [NSManagedObject] else { fatalError("Couldn't cast filteredArray as [NSManagedObject]: \(objectChanges), predicate: \(predicate)") }
for filteredObject in filteredArray {
let change = filteredObject.hyp_dictionary(using: .array)
filteredChanges.append(change)
}
}
}
return filteredChanges
}
}
| mit | 6905ff8011e50a36b27de73dd4fc8b2a | 59.777778 | 232 | 0.674132 | 5.442786 | false | false | false | false |
ekgorter/MyWikiTravel | MyWikiTravel/MyWikiTravel/AppDelegate.swift | 1 | 7124 | //
// AppDelegate.swift
// MyWikiTravel
//
// Created by Elias Gorter on 04-06-15.
// Copyright (c) 2015 EliasGorter6052274. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var navigationBarAppearance = UINavigationBar.appearance()
// Change navigation bar and bar items colors.
navigationBarAppearance.tintColor = uicolorFromHex(0xffffff)
navigationBarAppearance.barTintColor = uicolorFromHex(0xb35a2d)
// Change navigation bar title color.
navigationBarAppearance.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
// Change status bar items color.
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
return true
}
// Allows use of hexadecimal color codes.
func uicolorFromHex(rgbValue:UInt32) -> UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:1.0)
}
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.xxxx.ProjectName" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MyWikiTravel", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MyWikiTravel.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| unlicense | bc7a1d9b72081038351abccfe66a9363 | 53.381679 | 290 | 0.705783 | 5.694644 | false | false | false | false |
BranchMetrics/iOS-Deferred-Deep-Linking-SDK | Branch-TestBed-Swift/TestBed-Swift/ProductArrayTableViewController.swift | 1 | 3652 | //
// ProductArrayTableViewController.swift
// TestBed-Swift
//
// Created by David Westgate on 7/13/17.
// Copyright © 2017 Branch Metrics. All rights reserved.
//
import UIKit
class ProductArrayTableViewController: UITableViewController {
var array = CommerceEventData.products()
var incumbantValue = ""
var viewTitle = "Default Array Title"
var header = "Default Array Header"
var placeholder = "Default Array Placeholder"
var footer = "Default Array Footer"
var keyboardType = UIKeyboardType.default
override func viewDidLoad() {
super.viewDidLoad()
title = viewTitle
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "ProductArrayTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ProductArrayTableViewCell
let product = array[(indexPath as NSIndexPath).row]
cell.elementLabel.text = product["name"]
return cell
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
array.remove(at: (indexPath as NSIndexPath).row)
CommerceEventData.setProducts(array)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
// MARK: - Navigation
@IBAction func unwindByCancelling(_ segue:UIStoryboardSegue) { }
@IBAction func unwindProductTableViewController(_ sender: UIStoryboardSegue) {
if let vc = sender.source as? ProductTableViewController {
let productProperties = [
"name": (vc.productNameTextField.text?.count)! > 0 ? vc.productNameTextField.text : vc.productNameTextField.placeholder,
"brand": (vc.productBrandTextField.text?.count)! > 0 ? vc.productBrandTextField.text : vc.productBrandTextField.placeholder,
"sku": (vc.productSKUTextField.text?.count)! > 0 ? vc.productSKUTextField.text : vc.productSKUTextField.placeholder,
"quantity": (vc.productQuantityTextField.text?.count)! > 0 ? vc.productQuantityTextField.text : vc.productQuantityTextField.placeholder,
"price": (vc.productPriceTextField.text?.count)! > 0 ? vc.productPriceTextField.text : vc.productPriceTextField.placeholder,
"variant": (vc.productVariantTextField.text?.count)! > 0 ? vc.productVariantTextField.text : vc.productVariantTextField.placeholder,
"category": (vc.productCategoryTextField.text?.count)! > 0 ? vc.productCategoryTextField.text : vc.productCategoryTextField.placeholder
]
array = CommerceEventData.productsWithAddedProduct(productProperties as! [String : String])
tableView.reloadData()
}
}
}
| mit | fbfcc2dd234684d36baeb4dcb5053e1c | 40.488636 | 152 | 0.662832 | 5.022008 | false | false | false | false |
inkyfox/SwiftySQL | Sources/SQLUpdate.swift | 3 | 2311 | //
// SQLUpdate.swift
// SwiftySQL
//
// Created by Yongha Yoo (inkyfox) on 2016. 10. 24..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import Foundation
public class SQLUpdate: SQLQueryType {
public enum OrAction {
case replace, rollback, abort, fail, ignore
}
let orAction: OrAction?
let table: SQLSourceTableType
var sets: [([SQLColumn], [SQLValueType])] = []
var condition: SQLConditionType?
init(_ orAction: OrAction?, _ table: SQLSourceTableType) {
self.orAction = orAction
self.table = table
}
}
extension SQLUpdate {
public func query(by generator: SQLGenerator) -> String {
return generator.generateQuery(self, forRead: false)
}
public func formattedQuery(withIndent indent: Int = 0, by generator: SQLGenerator) -> String {
return generator.generateFormattedQuery(self, forRead: false, withIndent: indent)
}
public var description: String {
return query(by: SQLGenerator.default)
}
public var debugDescription: String {
return formattedQuery(by: SQLGenerator.default)
}
}
extension SQL {
public static func update(_ table: SQLSourceTableType) -> SQLUpdate {
return SQLUpdate(nil, table)
}
public static func update(or orAction: SQLUpdate.OrAction,
_ table: SQLSourceTableType) -> SQLUpdate {
return SQLUpdate(orAction, table)
}
}
extension SQLUpdate {
public func set(_ column: SQLColumn, _ value: SQLValueType) -> SQLUpdate {
self.sets.append(([column], [value]))
return self
}
public func set(_ column: SQLColumn, _ value: SQLSelect) -> SQLUpdate {
self.sets.append(([column], [value]))
return self
}
public func set(_ columns: [SQLColumn], _ value: SQLSelect) -> SQLUpdate {
self.sets.append((columns, [value]))
return self
}
public func set(_ columns: [SQLColumn], _ values: [SQLValueType]) -> SQLUpdate {
self.sets.append((columns, values))
return self
}
public func `where`(_ condition: SQLConditionType) -> SQLUpdate {
self.condition = condition
return self
}
}
| mit | 74b99d07e301fc02364b8c6c955b1100 | 24.362637 | 98 | 0.613518 | 4.266174 | false | false | false | false |
yrchen/edx-app-ios | Source/CourseOutlineViewController.swift | 1 | 14700 | //
// CourseOutlineViewController.swift
// edX
//
// Created by Akiva Leffert on 4/30/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import UIKit
///Controls the space between the ModeChange icon and the View on Web Icon for CourseOutlineViewController and CourseContentPageViewController. Changing this constant changes the spacing in both places.
public let barButtonFixedSpaceWidth : CGFloat = 20
public class CourseOutlineViewController :
UIViewController,
CourseBlockViewController,
CourseOutlineTableControllerDelegate,
CourseOutlineModeControllerDelegate,
CourseContentPageViewControllerDelegate,
CourseLastAccessedControllerDelegate,
OpenOnWebControllerDelegate,
PullRefreshControllerDelegate
{
public struct Environment {
private let analytics : OEXAnalytics?
private let dataManager : DataManager
private let networkManager : NetworkManager
private let reachability : Reachability
private weak var router : OEXRouter?
private let styles : OEXStyles
public init(analytics : OEXAnalytics?, dataManager : DataManager, networkManager : NetworkManager, reachability : Reachability, router : OEXRouter, styles : OEXStyles) {
self.analytics = analytics
self.dataManager = dataManager
self.networkManager = networkManager
self.reachability = reachability
self.router = router
self.styles = styles
}
}
private var rootID : CourseBlockID?
private var environment : Environment
private let courseQuerier : CourseOutlineQuerier
private let tableController : CourseOutlineTableController
private let blockIDStream = BackedStream<CourseBlockID?>()
private let headersLoader = BackedStream<CourseOutlineQuerier.BlockGroup>()
private let rowsLoader = BackedStream<[CourseOutlineQuerier.BlockGroup]>()
private let loadController : LoadStateViewController
private let insetsController : ContentInsetsController
private let modeController : CourseOutlineModeController
private var lastAccessedController : CourseLastAccessedController
/// Strictly a test variable used as a trigger flag. Not to be used out of the test scope
private var t_hasTriggeredSetLastAccessed = false
public var blockID : CourseBlockID? {
return blockIDStream.value ?? nil
}
public var courseID : String {
return courseQuerier.courseID
}
private lazy var webController : OpenOnWebController = OpenOnWebController(delegate: self)
public init(environment: Environment, courseID : String, rootID : CourseBlockID?) {
self.rootID = rootID
self.environment = environment
courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID)
loadController = LoadStateViewController()
insetsController = ContentInsetsController()
modeController = environment.dataManager.courseDataManager.freshOutlineModeController()
let outlineEnvironment = CourseOutlineTableController.Environment(dataManager : environment.dataManager)
tableController = CourseOutlineTableController(environment : outlineEnvironment, courseID: courseID)
lastAccessedController = CourseLastAccessedController(blockID: rootID , dataManager: environment.dataManager, networkManager: environment.networkManager, courseQuerier: courseQuerier)
super.init(nibName: nil, bundle: nil)
lastAccessedController.delegate = self
modeController.delegate = self
addChildViewController(tableController)
tableController.didMoveToParentViewController(self)
tableController.delegate = self
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = barButtonFixedSpaceWidth
navigationItem.rightBarButtonItems = [webController.barButtonItem,fixedSpace,modeController.barItem]
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
self.blockIDStream.backWithStream(Stream(value: rootID))
}
public required init?(coder aDecoder: NSCoder) {
// required by the compiler because UIViewController implements NSCoding,
// but we don't actually want to serialize these things
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = self.environment.styles.standardBackgroundColor()
view.addSubview(tableController.view)
loadController.setupInController(self, contentView:tableController.view)
tableController.refreshController.setupInScrollView(tableController.tableView)
tableController.refreshController.delegate = self
insetsController.setupInController(self, scrollView : self.tableController.tableView)
insetsController.supportOfflineMode(styles: environment.styles)
insetsController.addSource(tableController.refreshController)
self.view.setNeedsUpdateConstraints()
addListeners()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
lastAccessedController.loadLastAccessed(forMode: modeController.currentMode)
lastAccessedController.saveLastAccessed()
let stream = joinStreams(courseQuerier.rootID, courseQuerier.blockWithID(blockID))
stream.extendLifetimeUntilFirstResult (success :
{ (rootID, block) in
if self.blockID == rootID || self.blockID == nil {
self.environment.analytics?.trackScreenWithName(OEXAnalyticsScreenCourseOutline, courseID: self.courseID, value: nil)
}
else {
self.environment.analytics?.trackScreenWithName(OEXAnalyticsScreenSectionOutline, courseID: self.courseID, value: block.internalName)
}
},
failure: {
Logger.logError("ANALYTICS", "Unable to load block: \($0)")
}
)
}
override public func updateViewConstraints() {
loadController.insets = UIEdgeInsets(top: self.topLayoutGuide.length, left: 0, bottom: self.bottomLayoutGuide.length, right : 0)
tableController.view.snp_updateConstraints {make in
make.edges.equalTo(self.view)
}
super.updateViewConstraints()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.insetsController.updateInsets()
}
private func setupNavigationItem(block : CourseBlock) {
self.navigationItem.title = block.displayName
self.webController.info = OpenOnWebController.Info(courseID : courseID, blockID : block.blockID, supported : block.displayType.isUnknown, URL: block.webURL)
}
public func viewControllerForCourseOutlineModeChange() -> UIViewController {
return self
}
public func courseOutlineModeChanged(courseMode: CourseOutlineMode) {
headersLoader.removeAllBackings()
lastAccessedController.loadLastAccessed(forMode: courseMode)
reload()
}
private func reload() {
self.blockIDStream.backWithStream(Stream(value : self.blockID))
}
private func emptyState() -> LoadState {
switch modeController.currentMode {
case .Full:
return LoadState.failed(NSError.oex_courseContentLoadError())
case .Video:
let style = loadController.messageStyle
let message = style.apply(Strings.noVideosTryModeSwitcher)
let iconText = Icon.CourseModeVideo.attributedTextWithStyle(style, inline: true)
let formattedMessage = message(iconText)
let accessibilityMessage = Strings.noVideosTryModeSwitcher(modeSwitcher: Strings.courseModePickerDescription)
return LoadState.empty(icon: Icon.CourseModeFull, attributedMessage : formattedMessage, accessibilityMessage : accessibilityMessage)
}
}
private func showErrorIfNecessary(error : NSError) {
if self.loadController.state.isInitial {
self.loadController.state = LoadState.failed(error)
}
}
private func loadedHeaders(headers : CourseOutlineQuerier.BlockGroup) {
self.setupNavigationItem(headers.block)
let children = headers.children.map {header in
return self.courseQuerier.childrenOfBlockWithID(header.blockID, forMode: self.modeController.currentMode)
}
rowsLoader.backWithStream(joinStreams(children))
}
private func addListeners() {
blockIDStream.listen(self,
success: {[weak self] blockID in
self?.backHeadersLoaderWithBlockID(blockID)
},
failure: {[weak self] error in
self?.headersLoader.backWithStream(Stream(error: error))
})
headersLoader.listen(self,
success: {[weak self] headers in
self?.loadedHeaders(headers)
},
failure: {[weak self] error in
self?.rowsLoader.backWithStream(Stream(error: error))
self?.showErrorIfNecessary(error)
}
)
rowsLoader.listen(self,
success : {[weak self] groups in
if let owner = self {
owner.tableController.groups = groups
owner.tableController.tableView.reloadData()
owner.loadController.state = groups.count == 0 ? owner.emptyState() : .Loaded
}
},
failure : {[weak self] error in
self?.showErrorIfNecessary(error)
},
finally: {[weak self] in
self?.tableController.refreshController.endRefreshing()
}
)
}
private func backHeadersLoaderWithBlockID(blockID : CourseBlockID?) {
self.headersLoader.backWithStream(courseQuerier.childrenOfBlockWithID(blockID, forMode: modeController.currentMode))
}
// MARK: Outline Table Delegate
func outlineTableControllerChoseShowDownloads(controller: CourseOutlineTableController) {
environment.router?.showDownloadsFromViewController(self)
}
private func canDownloadVideo() -> Bool {
let hasWifi = environment.reachability.isReachableViaWiFi() ?? false
let onlyOnWifi = environment.dataManager.interface?.shouldDownloadOnlyOnWifi ?? false
return !onlyOnWifi || hasWifi
}
func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideos videos: [OEXHelperVideoDownload], rootedAtBlock block:CourseBlock) {
guard canDownloadVideo() else {
self.loadController.showOverlayError(Strings.noWifiMessage)
return
}
self.environment.dataManager.interface?.downloadVideos(videos)
let courseID = self.courseID
let analytics = environment.analytics
courseQuerier.parentOfBlockWithID(block.blockID).listenOnce(self, success:
{ parentID in
analytics?.trackSubSectionBulkVideoDownload(parentID, subsection: block.blockID, courseID: courseID, videoCount: videos.count)
},
failure: {error in
Logger.logError("ANALYTICS", "Unable to find parent of block: \(block). Error: \(error.localizedDescription)")
}
)
}
func outlineTableController(controller: CourseOutlineTableController, choseDownloadVideoForBlock block: CourseBlock) {
guard canDownloadVideo() else {
self.loadController.showOverlayError(Strings.noWifiMessage)
return
}
self.environment.dataManager.interface?.downloadVideosWithIDs([block.blockID], courseID: courseID)
environment.analytics?.trackSingleVideoDownload(block.blockID, courseID: courseID, unitURL: block.webURL?.absoluteString)
}
func outlineTableController(controller: CourseOutlineTableController, choseBlock block: CourseBlock, withParentID parent : CourseBlockID) {
self.environment.router?.showContainerForBlockWithID(block.blockID, type:block.displayType, parentID: parent, courseID: courseQuerier.courseID, fromController:self)
}
private func expandAccessStream(stream : Stream<CourseLastAccessed>) -> Stream<(CourseBlock, CourseLastAccessed)> {
return stream.transform {[weak self] lastAccessed in
return joinStreams(self?.courseQuerier.blockWithID(lastAccessed.moduleId) ?? Stream<CourseBlock>(), Stream(value: lastAccessed))
}
}
//MARK: PullRefreshControllerDelegate
public func refreshControllerActivated(controller: PullRefreshController) {
courseQuerier.needsRefresh = true
reload()
}
//MARK: CourseContentPageViewControllerDelegate
public func courseContentPageViewController(controller: CourseContentPageViewController, enteredBlockWithID blockID: CourseBlockID, parentID: CourseBlockID) {
self.blockIDStream.backWithStream(courseQuerier.parentOfBlockWithID(parentID))
self.tableController.highlightedBlockID = blockID
}
//MARK: LastAccessedControllerDeleagte
public func courseLastAccessedControllerDidFetchLastAccessedItem(item: CourseLastAccessed?) {
if let lastAccessedItem = item {
self.tableController.showLastAccessedWithItem(lastAccessedItem)
}
else {
self.tableController.hideLastAccessed()
}
}
public func presentationControllerForOpenOnWebController(controller: OpenOnWebController) -> UIViewController {
return self
}
}
extension CourseOutlineViewController {
public func t_setup() -> Stream<Void> {
return rowsLoader.map { _ in
}
}
public func t_currentChildCount() -> Int {
return tableController.groups.count
}
public func t_populateLastAccessedItem(item : CourseLastAccessed) -> Bool {
self.tableController.showLastAccessedWithItem(item)
return self.tableController.tableView.tableHeaderView != nil
}
public func t_didTriggerSetLastAccessed() -> Bool {
return t_hasTriggeredSetLastAccessed
}
}
| apache-2.0 | 90fa5b43030c69eca29701e5c3ea8fe4 | 40.292135 | 202 | 0.685714 | 5.819477 | false | false | false | false |
ja-mes/experiments | Old/Random/Core Data Demo/Core Data Demo/ViewController.swift | 1 | 2054 | //
// ViewController.swift
// Core Data Demo
//
// Created by James Brown on 12/14/15.
// Copyright © 2015 James Brown. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
/*
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context)
newUser.setValue("Foo", forKey: "username")
newUser.setValue("fo100", forKey: "password")
do {
try context.save()
}
catch {
print("Error saving")
}
*/
let request = NSFetchRequest(entityName: "Users")
request.predicate = NSPredicate(format: "username = %@ ", "Baz")
request.returnsObjectsAsFaults = false
do {
let results = try context.executeFetchRequest(request)
if(results.count > 0) {
for result in results as! [NSManagedObject] {
context.Object(result)
//result.setValue("Baz", forKey: "username")
do {
try context.save()
}
catch {
print("There was a problem saving")
}
if let username = result.valueForKey("username") as? String {
print(username)
}
}
}
}
catch {
print("Fetch failed")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | c61d7a48fb6df3586acd9e2edb434b80 | 25.662338 | 115 | 0.49586 | 6.038235 | false | false | false | false |
xwu/swift | test/SourceKit/CursorInfo/cursor_symbol_graph_referenced.swift | 4 | 13123 | import SomeModule
let global = 1
struct Parent {
struct Inner {}
func method<T>(x: T) where T: Equatable {}
}
extension Parent {
struct ExtInner {
func extInnerMethod(z: Inner, other: Array<ExtInner>, again: FromSomeModule) {}
private struct PrivateType {}
private func privateFunc(_ x: PrivateType) {}
@_spi(OtherModule) public struct SPIType {}
internal func spiFunc(x: SPIType) {}
}
}
// RUN: %empty-directory(%t)
// RUN: echo 'public struct FromSomeModule {} ' > %t/SomeModule.swift
// RUN: %target-build-swift %t/SomeModule.swift -emit-module -module-name SomeModule -o %t/SomeModule.swiftmodule
// References should cover symbols from the symbol graph declaration fragments, even if not present in the original source.
// RUN: %sourcekitd-test -req=cursor -pos=3:5 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple -I %t | %FileCheck -check-prefixes=GLOBAL %s
//
// GLOBAL: SYMBOL GRAPH BEGIN
// GLOBAL: "declarationFragments": [
// GLOBAL-NEXT: {
// GLOBAL-NEXT: "kind": "keyword",
// GLOBAL-NEXT: "spelling": "let"
// GLOBAL-NEXT: },
// GLOBAL-NEXT: {
// GLOBAL-NEXT: "kind": "text",
// GLOBAL-NEXT: "spelling": " "
// GLOBAL-NEXT: },
// GLOBAL-NEXT: {
// GLOBAL-NEXT: "kind": "identifier",
// GLOBAL-NEXT: "spelling": "global"
// GLOBAL-NEXT: },
// GLOBAL-NEXT: {
// GLOBAL-NEXT: "kind": "text",
// GLOBAL-NEXT: "spelling": ": "
// GLOBAL-NEXT: },
// GLOBAL-NEXT: {
// GLOBAL-NEXT: "kind": "typeIdentifier",
// GLOBAL-NEXT: "preciseIdentifier": "[[Int_USR:.*]]",
// GLOBAL-NEXT: "spelling": "Int"
// GLOBAL-NEXT: }
// GLOBAL-NEXT: ],
// GLOBAL: SYMBOL GRAPH END
//
// GLOBAL: REFERENCED DECLS BEGIN
// GLOBAL-NEXT: [[Int_USR]] | public | <empty> | Swift | System | NonSPI | source.lang.swift
// GLOBAL-NEXT: Int swift.struct [[Int_USR]]
// GLOBAL-NEXT: REFERENCED DECLS END
// References to unsupported types (like generic parameters) should be ignored.
// RUN: %sourcekitd-test -req=cursor -pos=6:10 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple -I %t | %FileCheck -check-prefixes=GENERIC %s
//
// GENERIC: SYMBOL GRAPH BEGIN
// GENERIC: "declarationFragments": [
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "keyword",
// GENERIC-NEXT: "spelling": "func"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "text",
// GENERIC-NEXT: "spelling": " "
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "identifier",
// GENERIC-NEXT: "spelling": "method"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "text",
// GENERIC-NEXT: "spelling": "<"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "genericParameter",
// GENERIC-NEXT: "spelling": "T"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "text",
// GENERIC-NEXT: "spelling": ">("
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "externalParam",
// GENERIC-NEXT: "spelling": "x"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "text",
// GENERIC-NEXT: "spelling": ": "
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "typeIdentifier",
// GENERIC-NEXT: "preciseIdentifier": "s:30cursor_symbol_graph_referenced6ParentV6method1xyx_tSQRzlF1TL_xmfp",
// GENERIC-NEXT: "spelling": "T"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "text",
// GENERIC-NEXT: "spelling": ") "
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "keyword",
// GENERIC-NEXT: "spelling": "where"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "text",
// GENERIC-NEXT: "spelling": " "
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "typeIdentifier",
// GENERIC-NEXT: "spelling": "T"
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "text",
// GENERIC-NEXT: "spelling": " : "
// GENERIC-NEXT: },
// GENERIC-NEXT: {
// GENERIC-NEXT: "kind": "typeIdentifier",
// GENERIC-NEXT: "preciseIdentifier": "[[Equatable_USR:.*]]",
// GENERIC-NEXT: "spelling": "Equatable"
// GENERIC-NEXT: }
// GENERIC-NEXT: ],
// GENERIC: SYMBOL GRAPH END
//
// GENERIC: REFERENCED DECLS BEGIN
// GENERIC-NEXT: [[Equatable_USR]] | public | <empty> | Swift | System | NonSPI | source.lang.swift
// GENERIC-NEXT: Equatable swift.protocol [[Equatable_USR]]
// GENERIC-NEXT: REFERENCED DECLS END
// References to unsupported types (like generic parameters) should be ignored.
// RUN: %sourcekitd-test -req=cursor -pos=11:14 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple -I %t | %FileCheck -check-prefixes=NESTED %s
//
// NESTED: SYMBOL GRAPH BEGIN
// NESTED: "declarationFragments": [
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "keyword",
// NESTED-NEXT: "spelling": "func"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": " "
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "identifier",
// NESTED-NEXT: "spelling": "extInnerMethod"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": "("
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "externalParam",
// NESTED-NEXT: "spelling": "z"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": ": "
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "typeIdentifier",
// NESTED-NEXT: "preciseIdentifier": "[[Inner_USR:.*]]",
// NESTED-NEXT: "spelling": "Inner"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": ", "
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "externalParam",
// NESTED-NEXT: "spelling": "other"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": ": "
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "typeIdentifier",
// NESTED-NEXT: "preciseIdentifier": "[[Array_USR:.*]]",
// NESTED-NEXT: "spelling": "Array"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": "<"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "typeIdentifier",
// NESTED-NEXT: "preciseIdentifier": "[[ExtInner_USR:.*]]",
// NESTED-NEXT: "spelling": "ExtInner"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": ">, "
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "externalParam",
// NESTED-NEXT: "spelling": "again"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": ": "
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "typeIdentifier",
// NESTED-NEXT: "preciseIdentifier": "[[FromSomeModule_USR:.*]]",
// NESTED-NEXT: "spelling": "FromSomeModule"
// NESTED-NEXT: },
// NESTED-NEXT: {
// NESTED-NEXT: "kind": "text",
// NESTED-NEXT: "spelling": ")"
// NESTED-NEXT: }
// NESTED-NEXT: ],
// NESTED: SYMBOL GRAPH END
//
// NESTED: REFERENCED DECLS BEGIN
// NESTED-NEXT: [[Inner_USR]] | internal | {{.*}}cursor_symbol_graph_referenced.swift | cursor_symbol_graph_referenced | User | NonSPI | source.lang.swift
// NESTED-NEXT: Parent swift.struct s:30cursor_symbol_graph_referenced6ParentV
// NESTED-NEXT: Inner swift.struct [[Inner_USR]]
// NESTED-NEXT: [[Array_USR]] | public | <empty> | Swift | System | NonSPI | source.lang.swift
// NESTED-NEXT: Array swift.struct [[Array_USR]]
// NESTED-NEXT: [[ExtInner_USR]] | internal | {{.*}}cursor_symbol_graph_referenced.swift | cursor_symbol_graph_referenced | User | NonSPI | source.lang.swift
// NESTED-NEXT: Parent swift.struct s:30cursor_symbol_graph_referenced6ParentV
// NESTED-NEXT: ExtInner swift.struct [[ExtInner_USR]]
// NESTED-NEXT: [[FromSomeModule_USR]] | public | {{.*}}/SomeModule.swift | SomeModule | User | NonSPI | source.lang.swift
// NESTED-NEXT: FromSomeModule swift.struct [[FromSomeModule_USR]]
// NESTED-NEXT: REFERENCED DECLS END
// Check access level reporting
// RUN: %sourcekitd-test -req=cursor -pos=13:22 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple -I %t | %FileCheck -check-prefixes=PRIVATE %s
//
// PRIVATE: SYMBOL GRAPH BEGIN
// PRIVATE: "declarationFragments": [
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "keyword",
// PRIVATE-NEXT: "spelling": "private"
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "text",
// PRIVATE-NEXT: "spelling": " "
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "keyword",
// PRIVATE-NEXT: "spelling": "func"
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "text",
// PRIVATE-NEXT: "spelling": " "
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "identifier",
// PRIVATE-NEXT: "spelling": "privateFunc"
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "text",
// PRIVATE-NEXT: "spelling": "("
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "externalParam",
// PRIVATE-NEXT: "spelling": "_"
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "text",
// PRIVATE-NEXT: "spelling": " "
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "internalParam",
// PRIVATE-NEXT: "spelling": "x"
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "text",
// PRIVATE-NEXT: "spelling": ": "
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "typeIdentifier",
// PRIVATE-NEXT: "preciseIdentifier": "[[PrivateType_USR:.*]]",
// PRIVATE-NEXT: "spelling": "PrivateType"
// PRIVATE-NEXT: },
// PRIVATE-NEXT: {
// PRIVATE-NEXT: "kind": "text",
// PRIVATE-NEXT: "spelling": ")"
// PRIVATE-NEXT: }
// PRIVATE-NEXT: ],
// PRIVATE: SYMBOL GRAPH END
//
// PRIVATE: REFERENCED DECLS BEGIN
// PRIVATE-NEXT: [[PrivateType_USR]] | private | {{.*}}cursor_symbol_graph_referenced.swift | cursor_symbol_graph_referenced | User | NonSPI | source.lang.swift
// PRIVATE-NEXT: Parent swift.struct s:30cursor_symbol_graph_referenced6ParentV
// PRIVATE-NEXT: ExtInner swift.struct s:30cursor_symbol_graph_referenced6ParentV8ExtInnerV
// PRIVATE-NEXT: PrivateType swift.struct [[PrivateType_USR]]
// PRIVATE-NEXT: REFERENCED DECLS END
// Check SPI reporting
// RUN: %sourcekitd-test -req=cursor -pos=16:23 -req-opts=retrieve_symbol_graph=1 %s -- %s -target %target-triple -I %t | %FileCheck -check-prefixes=SPI %s
//
// SPI: SYMBOL GRAPH BEGIN
// SPI: "declarationFragments": [
// SPI-NEXT: {
// SPI-NEXT: "kind": "keyword",
// SPI-NEXT: "spelling": "internal"
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "text",
// SPI-NEXT: "spelling": " "
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "keyword",
// SPI-NEXT: "spelling": "func"
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "text",
// SPI-NEXT: "spelling": " "
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "identifier",
// SPI-NEXT: "spelling": "spiFunc"
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "text",
// SPI-NEXT: "spelling": "("
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "externalParam",
// SPI-NEXT: "spelling": "x"
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "text",
// SPI-NEXT: "spelling": ": "
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "typeIdentifier",
// SPI-NEXT: "preciseIdentifier": "[[SPIType_USR:.*]]",
// SPI-NEXT: "spelling": "SPIType"
// SPI-NEXT: },
// SPI-NEXT: {
// SPI-NEXT: "kind": "text",
// SPI-NEXT: "spelling": ")"
// SPI-NEXT: }
// SPI-NEXT: ],
// SPI: SYMBOL GRAPH END
// SPI: REFERENCED DECLS BEGIN
// SPI-NEXT: [[SPIType_USR]] | public | {{.*}}cursor_symbol_graph_referenced.swift | cursor_symbol_graph_referenced | User | SPI | source.lang.swift
// SPI-NEXT: Parent swift.struct s:30cursor_symbol_graph_referenced6ParentV
// SPI-NEXT: ExtInner swift.struct s:30cursor_symbol_graph_referenced6ParentV8ExtInnerV
// SPI-NEXT: SPIType swift.struct [[SPIType_USR]]
// SPI-NEXT: REFERENCED DECLS END
| apache-2.0 | 2a3332af7037c74f3f9c866862f27012 | 36.387464 | 160 | 0.570449 | 3.21721 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/RTMPStartController.swift | 1 | 6707 | //
// RTMPStartController.swift
// Telegram
//
// Created by Mike Renoir on 23.02.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
private final class Arguments {
let context: AccountContext
let copyToClipboard: (String)->Void
let toggleHideKey:()->Void
init(context: AccountContext, copyToClipboard: @escaping(String)->Void, toggleHideKey:@escaping()->Void) {
self.context = context
self.copyToClipboard = copyToClipboard
self.toggleHideKey = toggleHideKey
}
}
private struct State : Equatable {
var credentials: GroupCallStreamCredentials?
var error: String? = nil
var hideKey: Bool = true
}
private let _id_server_url = InputDataIdentifier("_id_server_url")
private let _id_stream_key = InputDataIdentifier("_id_stream_key")
private let _id_loading = InputDataIdentifier("_id_loading")
private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId:Int32 = 0
var index: Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatRTMPInfo), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
if let credentials = state.credentials {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_server_url, equatable: .init(state), comparable: nil, item: { initialSize, stableId in
return TextAndLabelItem(initialSize, stableId: stableId, label: strings().voiceChatRTMPServerURL, copyMenuText: strings().contextAlertCopied, labelColor: theme.colors.text, textColor: theme.colors.accent, text: credentials.url, context: arguments.context, viewType: .firstItem, isTextSelectable: false, callback: {
arguments.copyToClipboard(credentials.url)
}, selectFullWord: true, canCopy: true, _copyToClipboard: {
arguments.copyToClipboard(credentials.url)
}, textFont: .code(.title))
}))
index += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_stream_key, equatable: .init(state), comparable: nil, item: { initialSize, stableId in
return TextAndLabelItem(initialSize, stableId: stableId, label: strings().voiceChatRTMPStreamKey, copyMenuText: strings().contextAlertCopied, labelColor: theme.colors.text, textColor: theme.colors.accent, text: credentials.streamKey, context: arguments.context, viewType: .lastItem, isTextSelectable: false, callback: {
arguments.copyToClipboard(credentials.streamKey)
}, selectFullWord: true, canCopy: true, _copyToClipboard: {
arguments.copyToClipboard(credentials.streamKey)
}, textFont: .code(.title), hideText: state.hideKey, toggleHide: arguments.toggleHideKey)
}))
index += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().voiceChatRTMPDesc), data: .init(color: theme.colors.listGrayText, viewType: .textBottomItem)))
index += 1
} else if let error = state.error {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(error), data: .init(color: theme.colors.redUI, viewType: .textBottomItem)))
index += 1
} else {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_loading, equatable: nil, comparable: nil, item: { initialSize, stableId in
return GeneralLoadingRowItem(initialSize, stableId: stableId, viewType: .singleItem)
}))
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func RTMPStartController(context: AccountContext, peerId: PeerId, scheduleDate: Date?, completion: @escaping(PeerId, Date?, Bool)->Void) -> InputDataModalController {
let actionsDisposable = DisposableSet()
let initialState = State()
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((State) -> State) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
var close:(()->Void)? = nil
var getController:(()->ViewController?)? = nil
let arguments = Arguments(context: context, copyToClipboard: { value in
copyToClipboard(value)
getController?()?.show(toaster: ControllerToaster(text: strings().shareLinkCopied))
}, toggleHideKey: {
updateState { current in
var current = current
current.hideKey = !current.hideKey
return current
}
})
let signal = statePromise.get() |> deliverOnPrepareQueue |> map { state in
return InputDataSignalValue(entries: entries(state, arguments: arguments))
}
let controller = InputDataController(dataSignal: signal, title: strings().voiceChatRTMPTitle)
controller.onDeinit = {
actionsDisposable.dispose()
}
getController = { [weak controller] in
return controller
}
controller.validateData = { _ in
completion(peerId, scheduleDate, true)
return .success(.custom({
close?()
}))
}
let modalInteractions = ModalInteractions(acceptTitle: strings().voiceChatRTMPOK, accept: { [weak controller] in
_ = controller?.returnKeyAction()
}, drawBorder: true, height: 50, singleButton: true)
let modalController = InputDataModalController(controller, modalInteractions: modalInteractions)
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in
modalController?.close()
})
let getSignal = context.engine.calls.getGroupCallStreamCredentials(peerId: EnginePeer.Id.init(peerId.toInt64()), revokePreviousCredentials: false)
actionsDisposable.add(getSignal.start(next: { credentials in
updateState { current in
var current = current
current.credentials = credentials
current.error = nil
return current
}
}, error: { error in
updateState { current in
var current = current
current.credentials = nil
current.error = strings().unknownError
return current
}
}))
close = { [weak modalController] in
modalController?.close()
}
return modalController
}
| gpl-2.0 | 8fe746b999cc5118d0f4ed95209045ac | 39.39759 | 331 | 0.67119 | 4.696078 | false | false | false | false |
imaginary-cloud/ICSwipeActionsTableCell | ICSwipeActionsTableCell/ICDemoTableViewController.swift | 1 | 2956 |
import UIKit
class ICDemoTableViewController: UITableViewController, ICSwipeActionsTableCellDelegate {
// MARK: - properties
var numberOfDemoCells = 10
let moreButtonTitle = "MORE"
let deleteButtonTitle = "DELETE"
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(ICDemoTableViewCell.self, forCellReuseIdentifier: ICDemoTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "ICDemoTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: ICDemoTableViewCellIdentifier)
self.tableView.separatorColor = UIColor(red: 64.0/255.0, green: 0.0, blue: 128.0/255.0, alpha: 1.0)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfDemoCells
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(ICDemoTableViewCellIdentifier, forIndexPath: indexPath) as! ICDemoTableViewCell
cell.indexPathLabel.text = "\(indexPath.row)"
let textColor = UIColor(red: 1.0, green: 1.0, blue: 102.0/255.0, alpha: 1.0)
cell.rightButtonsTitles = [(title:moreButtonTitle, color:UIColor(red: 128.0/255.0, green: 0.0, blue: 128.0/255.0, alpha: 1.0), textColor:textColor), (title:deleteButtonTitle, color:UIColor(red: 1.0, green: 0.0, blue: 128.0/255.0, alpha: 1.0), textColor:textColor)]
cell.leftButtonsTitles = [(title:"FROG", color:UIColor(red: 128.0/255.0, green: 1.0, blue: 0.0, alpha: 1.0), textColor:textColor), (title:"LION", color:UIColor(red: 1.0, green: 128.0/255.0, blue: 0.0, alpha: 1.0), textColor:textColor)]
cell.delegate = self
cell.buttonsEqualSize = true
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 88.0
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20.0
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRectMake(0, 0, tableView.frame.width, 20))
view.backgroundColor = UIColor.whiteColor()
return view
}
// MARK: - ICSwipeActionsTableCellDelegate
func swipeCellButtonPressedWithTitle(title: String, indexPath: NSIndexPath) {
if title == deleteButtonTitle {
numberOfDemoCells -= 1
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
} else {
numberOfDemoCells += 1
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
}
}
}
| mit | b1dbf11fc479f02620fd900778731825 | 42.470588 | 272 | 0.683694 | 4.458522 | false | false | false | false |
momo13014/RayWenderlichDemo | CustomSliderExample/CustomSliderExample/ViewController.swift | 1 | 1608 | //
// ViewController.swift
// CustomSliderExample
//
// Created by shendong on 16/9/8.
// Copyright © 2016年 shendong. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let rangeSlider = RangeSlider(frame: CGRectZero)
@IBOutlet weak var localRangeSlider: RangeSlider!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(rangeSlider)
rangeSlider.addTarget(self, action: #selector(ViewController.rangeSliderValueChanged(_:)), forControlEvents: .ValueChanged)
let time = dispatch_time(DISPATCH_TIME_NOW, 2)
dispatch_after(time, dispatch_get_main_queue()) {
self.rangeSlider.trackHighlightTintColor = UIColor.redColor()
self.rangeSlider.curvaceousness = 0.3
self.rangeSlider.lowerValue = 0.5
self.rangeSlider.upperValue = 0.9
self.rangeSlider.thumbTintColor = UIColor.blueColor()
}
// UISlider
print("sss \(localRangeSlider.lowerValue), \(localRangeSlider.upperValue)")
}
override func viewDidLayoutSubviews() {
let margin: CGFloat = 20.0
let width = view.bounds.width - 2.0 * margin
print(topLayoutGuide.length)
print(bottomLayoutGuide)
rangeSlider.frame = CGRect(x: margin, y: margin + topLayoutGuide.length, width: width, height: 32.0)
}
func rangeSliderValueChanged(rangeSlider: RangeSlider){
print("RangeSlider value changed : \(rangeSlider.lowerValue), \(rangeSlider.upperValue)")
}
}
| mit | fdc86d26d8da23555e1e41d87a53edb1 | 31.1 | 131 | 0.649221 | 4.748521 | false | false | false | false |
yanif/circator | MetabolicCompass/NutritionManager/Model/NutritionQuantity.swift | 1 | 18037 | //
// NutritionQuantity.swift
// MetabolicCompassNutritionManager
//
// Created by Edwin L. Whitman on 7/21/16.
// Copyright © 2016 Edwin L. Whitman. All rights reserved.
//
import Foundation
import HealthKit
class NutritionalContent : NSObject {
var contents : [NutritionQuantity] = []
var FatTotal : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .FatTotal) {
return self.contents[index].quantity
}
return nil
}
}
var FatPolyunsaturated : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .FatPolyunsaturated) {
return self.contents[index].quantity
}
return nil
}
}
var FatMonounsaturated : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .FatMonounsaturated) {
return self.contents[index].quantity
}
return nil
}
}
var FatSaturated : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .FatSaturated) {
return self.contents[index].quantity
}
return nil
}
}
var Cholesterol : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Cholesterol) {
return self.contents[index].quantity
}
return nil
}
}
var Sodium : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Sodium) {
return self.contents[index].quantity
}
return nil
}
}
var Carbohydrates : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Carbohydrates) {
return self.contents[index].quantity
}
return nil
}
}
var Fiber : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Fiber) {
return self.contents[index].quantity
}
return nil
}
}
var Sugar : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Sugar) {
return self.contents[index].quantity
}
return nil
}
}
var EnergyConsumed : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .EnergyConsumed) {
print(index)
return self.contents[index].quantity
}
return nil
}
}
var Protein : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Protein) {
return self.contents[index].quantity
}
return nil
}
}
var VitaminA : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .VitaminA) {
return self.contents[index].quantity
}
return nil
}
}
var VitaminB6 : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .VitaminB6) {
return self.contents[index].quantity
}
return nil
}
}
var VitaminB12 : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .VitaminB12) {
return self.contents[index].quantity
}
return nil
}
}
var VitaminC : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .VitaminC) {
return self.contents[index].quantity
}
return nil
}
}
var VitaminD : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .VitaminD) {
return self.contents[index].quantity
}
return nil
}
}
var VitaminE : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .VitaminE) {
return self.contents[index].quantity
}
return nil
}
}
var VitaminK : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .VitaminK) {
return self.contents[index].quantity
}
return nil
}
}
var Calcium : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Calcium) {
return self.contents[index].quantity
}
return nil
}
}
var Iron : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Iron) {
return self.contents[index].quantity
}
return nil
}
}
var Thiamin : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Thiamin) {
return self.contents[index].quantity
}
return nil
}
}
var Riboflavin : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Riboflavin) {
return self.contents[index].quantity
}
return nil
}
}
var Niacin : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Niacin) {
return self.contents[index].quantity
}
return nil
}
}
var Folate : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Folate) {
return self.contents[index].quantity
}
return nil
}
}
var Biotin : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Biotin) {
return self.contents[index].quantity
}
return nil
}
}
var PantothenicAcid : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .PantothenicAcid) {
return self.contents[index].quantity
}
return nil
}
}
var Phosphorus : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Phosphorus) {
return self.contents[index].quantity
}
return nil
}
}
var Iodine : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Iodine) {
return self.contents[index].quantity
}
return nil
}
}
var Magnesium : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Magnesium) {
return self.contents[index].quantity
}
return nil
}
}
var Zinc : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Zinc) {
return self.contents[index].quantity
}
return nil
}
}
var Selenium : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Selenium) {
return self.contents[index].quantity
}
return nil
}
}
var Copper : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Copper) {
return self.contents[index].quantity
}
return nil
}
}
var Manganese : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Manganese) {
return self.contents[index].quantity
}
return nil
}
}
var Chromium : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Chromium) {
return self.contents[index].quantity
}
return nil
}
}
var Molybdenum : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Molybdenum) {
return self.contents[index].quantity
}
return nil
}
}
var Chloride : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Chloride) {
return self.contents[index].quantity
}
return nil
}
}
var Potassium : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Potassium) {
return self.contents[index].quantity
}
return nil
}
}
var Caffeine : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Caffeine) {
return self.contents[index].quantity
}
return nil
}
}
var Water : HKQuantity? {
get {
if let index = self.indexOfNutritionOfType(typeOfNutrition: .Water) {
return self.contents[index].quantity
}
return nil
}
}
func containsNutritionOfType(typeOfNutrition type : NutritionQuantityType) -> Bool {
for i in 0..<self.contents.count {
if self.contents[i].quantityType == type.identifier {
return true
}
}
return false
}
func indexOfNutritionOfType(typeOfNutrition type : NutritionQuantityType) -> Int? {
for i in 0..<self.contents.count {
if self.contents[i].quantityType == HKObjectType.quantityTypeForIdentifier(type.identifier) {
return i
}
}
return nil
}
func addNutritionQuantity(nutritionQuantity : NutritionQuantity) {
for i in 0..<self.contents.count {
if self.contents[i].quantityType.identifier == nutritionQuantity.quantityType.identifier && self.contents[i].quantity.isCompatibleWithUnit(nutritionQuantity.unit) {
let sum = self.contents[i].quantity.doubleValueForUnit(self.contents[i].unit) + nutritionQuantity.quantity.doubleValueForUnit(nutritionQuantity.unit)
self.contents[i].quantity = HKQuantity(unit: self.contents[i].unit, doubleValue: sum)
return
}
}
self.contents.append(nutritionQuantity)
}
}
class NutritionQuantity : NSObject {
var quantityType: HKQuantityType
var quantity: HKQuantity
var unit : HKUnit
init(type quantityType: NutritionQuantityType, amount: Double) {
self.quantityType = HKObjectType.quantityTypeForIdentifier(quantityType.identifier)!
self.quantity = HKQuantity(unit: quantityType.unit, doubleValue: amount)
self.unit = quantityType.unit
}
}
enum NutritionQuantityType : String {
case FatTotal
case FatPolyunsaturated
case FatMonounsaturated
case FatSaturated
case Cholesterol
case Sodium
case Carbohydrates
case Fiber
case Sugar
case EnergyConsumed
case Protein
case VitaminA
case VitaminB6
case VitaminB12
case VitaminC
case VitaminD
case VitaminE
case VitaminK
case Calcium
case Iron
case Thiamin
case Riboflavin
case Niacin
case Folate
case Biotin
case PantothenicAcid
case Phosphorus
case Iodine
case Magnesium
case Zinc
case Selenium
case Copper
case Manganese
case Chromium
case Molybdenum
case Chloride
case Potassium
case Caffeine
case Water
var identifier : String {
switch self {
case FatTotal:
return HKQuantityTypeIdentifierDietaryFatTotal
case FatPolyunsaturated:
return HKQuantityTypeIdentifierDietaryFatPolyunsaturated
case FatMonounsaturated:
return HKQuantityTypeIdentifierDietaryFatMonounsaturated
case FatSaturated:
return HKQuantityTypeIdentifierDietaryFatSaturated
case Cholesterol:
return HKQuantityTypeIdentifierDietaryCholesterol
case Sodium:
return HKQuantityTypeIdentifierDietarySodium
case Carbohydrates:
return HKQuantityTypeIdentifierDietaryCarbohydrates
case Fiber:
return HKQuantityTypeIdentifierDietaryFiber
case Sugar:
return HKQuantityTypeIdentifierDietarySugar
case EnergyConsumed:
return HKQuantityTypeIdentifierDietaryEnergyConsumed
case Protein:
return HKQuantityTypeIdentifierDietaryProtein
case VitaminA:
return HKQuantityTypeIdentifierDietaryVitaminA
case VitaminB6:
return HKQuantityTypeIdentifierDietaryVitaminB6
case VitaminB12:
return HKQuantityTypeIdentifierDietaryVitaminB12
case VitaminC:
return HKQuantityTypeIdentifierDietaryVitaminC
case VitaminD:
return HKQuantityTypeIdentifierDietaryVitaminD
case VitaminE:
return HKQuantityTypeIdentifierDietaryVitaminE
case VitaminK:
return HKQuantityTypeIdentifierDietaryVitaminK
case Calcium:
return HKQuantityTypeIdentifierDietaryCalcium
case Iron:
return HKQuantityTypeIdentifierDietaryIron
case Thiamin:
return HKQuantityTypeIdentifierDietaryThiamin
case Riboflavin:
return HKQuantityTypeIdentifierDietaryRiboflavin
case Niacin:
return HKQuantityTypeIdentifierDietaryNiacin
case Folate:
return HKQuantityTypeIdentifierDietaryFolate
case Biotin:
return HKQuantityTypeIdentifierDietaryBiotin
case PantothenicAcid:
return HKQuantityTypeIdentifierDietaryPantothenicAcid
case Phosphorus:
return HKQuantityTypeIdentifierDietaryPhosphorus
case Iodine:
return HKQuantityTypeIdentifierDietaryIodine
case Magnesium:
return HKQuantityTypeIdentifierDietaryMagnesium
case Zinc:
return HKQuantityTypeIdentifierDietaryZinc
case Selenium:
return HKQuantityTypeIdentifierDietarySelenium
case Copper:
return HKQuantityTypeIdentifierDietaryCopper
case Manganese:
return HKQuantityTypeIdentifierDietaryManganese
case Chromium:
return HKQuantityTypeIdentifierDietaryChromium
case Molybdenum:
return HKQuantityTypeIdentifierDietaryMolybdenum
case Chloride:
return HKQuantityTypeIdentifierDietaryChloride
case Potassium:
return HKQuantityTypeIdentifierDietaryPotassium
case Caffeine:
return HKQuantityTypeIdentifierDietaryCaffeine
case Water:
return HKQuantityTypeIdentifierDietaryWater
}
}
var unit : HKUnit {
switch self {
case FatTotal:
return HKUnit.gramUnit()
case FatPolyunsaturated:
return HKUnit.gramUnit()
case FatMonounsaturated:
return HKUnit.gramUnit()
case FatSaturated:
return HKUnit.gramUnit()
case Cholesterol:
return HKUnit.gramUnitWithMetricPrefix(.Milli)
case Sodium:
return HKUnit.gramUnitWithMetricPrefix(.Milli)
case Carbohydrates:
return HKUnit.gramUnit()
case Fiber:
return HKUnit.gramUnit()
case Sugar:
return HKUnit.gramUnit()
case EnergyConsumed:
return HKUnit.kilocalorieUnit()
case Protein:
return HKUnit.gramUnit()
case VitaminA:
return HKUnit.gramUnit()
case VitaminB6:
return HKUnit.gramUnit()
case VitaminB12:
return HKUnit.gramUnit()
case VitaminC:
return HKUnit.gramUnit()
case VitaminD:
return HKUnit.gramUnit()
case VitaminE:
return HKUnit.gramUnit()
case VitaminK:
return HKUnit.gramUnit()
case Calcium:
return HKUnit.gramUnit()
case Iron:
return HKUnit.gramUnit()
case Thiamin:
return HKUnit.gramUnit()
case Riboflavin:
return HKUnit.gramUnit()
case Niacin:
return HKUnit.gramUnit()
case Folate:
return HKUnit.gramUnit()
case Biotin:
return HKUnit.gramUnit()
case PantothenicAcid:
return HKUnit.gramUnit()
case Phosphorus:
return HKUnit.gramUnit()
case Iodine:
return HKUnit.gramUnit()
case Magnesium:
return HKUnit.gramUnit()
case Zinc:
return HKUnit.gramUnit()
case Selenium:
return HKUnit.gramUnit()
case Copper:
return HKUnit.gramUnit()
case Manganese:
return HKUnit.gramUnit()
case Chromium:
return HKUnit.gramUnit()
case Molybdenum:
return HKUnit.gramUnit()
case Chloride:
return HKUnit.gramUnit()
case Potassium:
return HKUnit.gramUnitWithMetricPrefix(.Milli)
case Caffeine:
return HKUnit.gramUnit()
case Water:
return HKUnit.gramUnit()
}
}
} | apache-2.0 | ea1b642e5203a24a70d3bdba0b976b86 | 29.67517 | 176 | 0.574739 | 4.976821 | false | false | false | false |
MisterZhouZhou/Objective-C-Swift-StudyDemo | SwiftDemo/SwiftDemo/classes/modules/CarouselFigure/controller/ZWEasyScrollViewViewController.swift | 1 | 1602 | //
// ZWEasyScrollViewViewController.swift
// SwiftDemo
//
// Created by rayootech on 16/6/18.
// Copyright © 2016年 rayootech. All rights reserved.
//
import UIKit
class ZWEasyScrollViewViewController: ZWBaseViewController,EasyScrollViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "轮播图控制器"
// 设置CGRectZero从导航栏下开始计算
if self.respondsToSelector(Selector("setEdgesForExtendedLayout")){
self.edgesForExtendedLayout = .None;
}
let array = ["beijing","Brisbane","CityofLosAngeles","CityofVancouver"]
let width = self.view.frame.size.width
let height = self.view.frame.size.height/3
let easyView = EasyScrollView(frame: CGRectMake(0,64,width,height))
easyView.delegate = self
easyView.initScrollview(array)
self.view.addSubview(easyView)
}
func EasyScrollViewDidClicked(index:Int){
print("index==\(index)");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 541edf24768572e5422347787dd22399 | 27.454545 | 106 | 0.650479 | 4.589443 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Model/Bucket.swift | 1 | 1753 | //
// Bucket.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 27/01/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import SwiftyJSON
struct Bucket: BucketType {
let identifier: String
let name: String
let attributedDescription: NSAttributedString?
let shotsCount: UInt
let createdAt: Date
let owner: UserType
}
extension Bucket: Mappable {
static var map: (JSON) -> Bucket {
return { json in
let stringDate = json[Key.CreatedAt.rawValue].stringValue
let attributedDescription: NSAttributedString? = {
guard let htmlString = json[Key.Description.rawValue].string else {
return nil
}
return NSAttributedString(htmlString: htmlString)
}()
return Bucket(
identifier: json[Key.Identifier.rawValue].stringValue,
name: json[Key.Name.rawValue].stringValue,
attributedDescription: attributedDescription,
shotsCount: json[Key.ShotsCount.rawValue].uIntValue,
createdAt: Formatter.Date.Timestamp.date(from: stringDate)!,
owner: User.map(json[Key.User.rawValue])
)
}
}
fileprivate enum Key: String {
case Identifier = "id"
case Name = "name"
case Description = "description"
case CreatedAt = "created_at"
case ShotsCount = "shots_count"
case User = "user"
}
}
extension Bucket: Hashable {
var hashValue: Int {
return identifier.hashValue
}
}
extension Bucket: Equatable {}
func == (lhs: Bucket, rhs: Bucket) -> Bool {
return lhs.identifier == rhs.identifier
}
| gpl-3.0 | c50915bd87438c10e10f89bbbe72819e | 25.953846 | 83 | 0.606164 | 4.598425 | false | false | false | false |
gewill/Feeyue | Feeyue/GlobalSetting.swift | 1 | 2701 | //
// GlobalSetting.swift
// Feeyue
//
// Created by Will on 14-11-16.
// Copyright (c) 2014年 Will. All rights reserved.
//
import Foundation
import UIKit
import QMUIKit
// 系统有关
let BOUND = UIScreen.main.bounds
let ScreenWidth = UIScreen.main.bounds.size.width
let ScreenHeight = UIScreen.main.bounds.size.height
let CoordinateSpaceScreenWidth = UIScreen.main.coordinateSpace.bounds.size.width
let CoordinateSpaceScreenHeight = UIScreen.main.coordinateSpace.bounds.size.height
// Color
let SystemTintColor = UIColor(red: 0.0, green: 0.4784, blue: 1.0, alpha: 1.0)
let HalfSystemTintColor = UIColor(red: 0.0, green: 0.4784, blue: 1.0, alpha: 0.5)
let SeparatorColor = UIColor(red: 0.78, green: 0.78, blue: 0.8, alpha: 1.0)
@discardableResult
func QMUICMI() -> QMUIConfiguration {
QMUIConfiguration.sharedInstance()!.rj_applyInitialTemplate()
return QMUIConfiguration.sharedInstance()!
}
func themeColor() -> UIColor {
return QDThemeManager.sharedInstance().currentTheme.themeTintColor()
}
struct GWColor {
static let color3: UIColor = UIColor.qmui_color(withHexString: "#333333")!
static let color4: UIColor = UIColor.qmui_color(withHexString: "#444444")!
static let color6: UIColor = UIColor.qmui_color(withHexString: "#666666")!
static let color9: UIColor = UIColor.qmui_color(withHexString: "#999999")!
static let black: UIColor = UIColor.qmui_color(withHexString: "#000000")!
static let white: UIColor = UIColor.qmui_color(withHexString: "#FFFFFF")!
static let d8: UIColor = UIColor.qmui_color(withHexString: "#D8D8D8")!
static let e7: UIColor = UIColor.qmui_color(withHexString: "#E7E7E7")!
static let f2: UIColor = UIColor.qmui_color(withHexString: "#F2F2F2")!
static let blue: UIColor = UIColor.qmui_color(withHexString: "#4A90E2")!
}
struct GWFont {
static let size18: UIFont = UIFont.systemFont(ofSize: 18)
static let size17: UIFont = UIFont.systemFont(ofSize: 17)
static let size16: UIFont = UIFont.systemFont(ofSize: 16)
static let size15: UIFont = UIFont.systemFont(ofSize: 15)
static let size14: UIFont = UIFont.systemFont(ofSize: 14)
static let size13: UIFont = UIFont.systemFont(ofSize: 13)
static let size12: UIFont = UIFont.systemFont(ofSize: 12)
static let size11: UIFont = UIFont.systemFont(ofSize: 11)
}
// constant
let Placeholder = UIImage(named: "placeholder")
enum TableViewType {
case comment
case repost
}
enum PictureSettingsType {
case high
case medium
case adaptive
}
typealias VoidClosure = () -> Void
#if swift(>=4.2)
import UIKit.UIGeometry
extension UIEdgeInsets {
public static let zero = UIEdgeInsets()
}
#endif
| mit | 08938eaf25c9e360e402148f65322da7 | 30.658824 | 82 | 0.723523 | 3.641407 | false | false | false | false |
mortenjust/cleartext-mac | Simpler/C.swift | 1 | 2564 | //
// C.swift
// Simpler
//
// Created by Morten Just Petersen on 11/23/15.
// Copyright © 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
struct Language {
var code:String
var name:String
}
class C: NSObject {
static let editorBackgroundColor = NSColor(red:0.988, green:0.988, blue:0.980, alpha:1)
static let editorTextColor = NSColor(red:0.349, green:0.349, blue:0.314, alpha:1)
static let canvasBackgroundColor = NSColor(red:0.988, green:0.988, blue:0.980, alpha:1)
static let languageItemColor = NSColor(red:0.745, green:0.741, blue:0.749, alpha:1)
static let editorFont = NSFont(name: "Avenir Next", size: 23)
static let editorAtts:[String:AnyObject] = [
NSFontNameAttribute : C.editorFont!,
NSForegroundColorAttributeName : C.editorTextColor,
NSBackgroundColorAttributeName : C.editorBackgroundColor
]
static let PREF_MAKESOUND = "makeSound"
static let PREF_FORCESELECT = "forceSelect"
static let defaultPrefValues = [
"makeSound":true,
"forceSelect":true,
"language":"English"
] as [String : Any]
static let languages = [
Language(code: "English", name: "English"),
Language(code: "Español", name: "Español"),
Language(code: "Čeština", name: "Čeština"),
Language(code: "Français", name: "Français"),
Language(code: "Português", name: "Português"),
Language(code: "Deutsch", name: "Deutsch"),
Language(code: "Italiano", name: "Italiano"),
Language(code: "Nederlands", name: "Nederlands"),
Language(code: "Norsk", name: "Norsk"),
Language(code: "Dansk", name: "Dansk"),
Language(code: "Suomi", name: "Suomi"),
Language(code: "Svenska", name: "Svenska"),
Language(code: "Íslenska", name: "Íslenska"),
Language(code: "Italiano", name: "Italiano"),
Language(code: "Shqip", name: "Shqip"),
Language(code: "Hrvatski", name: "Hrvatski"),
Language(code: "Srpski", name: "Srpski"),
Language(code: "Bahasa", name: "Bahasa"),
Language(code: "русский", name: "русский"),
Language(code: "Trump", name: "Trump"),
Language(code: "xkcd", name: "xkcd"),
Language(code: "Jobs", name: "Jobs"),
Language(code: "Hemingway", name: "Hemingway"),
]
//
// font = NSFont(name: "Avenir Next", size: 23)
// backgroundColor = C.editorBackgroundColor
// textColor = C.editorTextColor
//
}
| gpl-3.0 | 8e31f07754134a051d0c82abff53073c | 35.242857 | 91 | 0.614899 | 3.333771 | false | false | false | false |
jopamer/swift | test/Interpreter/generic_objc_subclass.swift | 1 | 6857 | // RUN: %empty-directory(%t)
//
// RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o
// RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ -Xlinker %t/ObjCClasses.o %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import ObjCClasses
@objc protocol P {
func calculatePrice() -> Int
}
protocol PP {
func calculateTaxes() -> Int
}
//
// Generic subclass of an @objc class
//
class A<T> : HasHiddenIvars, P {
var first: Int = 16
var second: T?
var third: Int = 61
override var description: String {
return "Grilled artichokes"
}
func calculatePrice() -> Int {
return 400
}
}
let a = A<Int>()
// CHECK: Grilled artichokes
// CHECK: Grilled artichokes
print(a.description)
print((a as NSObject).description)
let f = { (a.x, a.y, a.z, a.t, a.first, a.second, a.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(f())
// CHECK: (25, 225, 255, 2255, 16, nil, 61)
a.x = 25
a.y = 225
a.z = 255
a.t = 2255
print(f())
// CHECK: (36, 225, 255, 2255, 16, nil, 61)
a.x = 36
print(f())
// CHECK: (36, 225, 255, 2255, 16, Optional(121), 61)
a.second = 121
print(f())
//
// Instantiate the class with a different set of generic parameters
//
let aa = A<(Int, Int)>()
let ff = { (aa.x, aa.y, aa.z, aa.t, aa.first, aa.second, aa.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(ff())
aa.x = 101
aa.second = (19, 84)
aa.third = 17
// CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17)
print(ff())
//
// Concrete subclass of generic subclass of @objc class
//
class B : A<(Int, Int)> {
override var description: String {
return "Salmon"
}
@nonobjc override func calculatePrice() -> Int {
return 1675
}
}
class BB : B {}
class C : A<(Int, Int)>, PP {
@nonobjc override var description: String {
return "Invisible Chicken"
}
override func calculatePrice() -> Int {
return 650
}
func calculateTaxes() -> Int {
return 110
}
}
// CHECK: 400
// CHECK: 400
// CHECK: 650
// CHECK: 110
print((BB() as P).calculatePrice())
print((B() as P).calculatePrice())
print((C() as P).calculatePrice())
print((C() as PP).calculateTaxes())
// CHECK: Salmon
// CHECK: Grilled artichokes
print((B() as NSObject).description)
print((C() as NSObject).description)
let b = B()
let g = { (b.x, b.y, b.z, b.t, b.first, b.second, b.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(g())
b.x = 101
b.second = (19, 84)
b.third = 17
// CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17)
print(g())
//
// Generic subclass of @objc class without any generically-sized members
//
class FixedA<T> : HasHiddenIvars, P {
var first: Int = 16
var second: [T] = []
var third: Int = 61
override var description: String {
return "Grilled artichokes"
}
func calculatePrice() -> Int {
return 400
}
}
let fixedA = FixedA<Int>()
// CHECK: Grilled artichokes
// CHECK: Grilled artichokes
print(fixedA.description)
print((fixedA as NSObject).description)
let fixedF = { (fixedA.x, fixedA.y, fixedA.z, fixedA.t, fixedA.first, fixedA.second, fixedA.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedF())
// CHECK: (25, 225, 255, 2255, 16, [], 61)
fixedA.x = 25
fixedA.y = 225
fixedA.z = 255
fixedA.t = 2255
print(fixedF())
// CHECK: (36, 225, 255, 2255, 16, [], 61)
fixedA.x = 36
print(fixedF())
// CHECK: (36, 225, 255, 2255, 16, [121], 61)
fixedA.second = [121]
print(fixedF())
//
// Instantiate the class with a different set of generic parameters
//
let fixedAA = FixedA<(Int, Int)>()
let fixedFF = { (fixedAA.x, fixedAA.y, fixedAA.z, fixedAA.t, fixedAA.first, fixedAA.second, fixedAA.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedFF())
fixedAA.x = 101
fixedAA.second = [(19, 84)]
fixedAA.third = 17
// CHECK: (101, 0, 0, 0, 16, [(19, 84)], 17)
print(fixedFF())
//
// Concrete subclass of generic subclass of @objc class
// without any generically-sized members
//
class FixedB : FixedA<Int> {
override var description: String {
return "Salmon"
}
override func calculatePrice() -> Int {
return 1675
}
}
// CHECK: 675
print((FixedB() as P).calculatePrice())
// CHECK: Salmon
print((FixedB() as NSObject).description)
let fixedB = FixedB()
let fixedG = { (fixedB.x, fixedB.y, fixedB.z, fixedB.t, fixedB.first, fixedB.second, fixedB.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedG())
fixedB.x = 101
fixedB.second = [19, 84]
fixedB.third = 17
// CHECK: (101, 0, 0, 0, 16, [19, 84], 17)
print(fixedG())
// Problem with field alignment in direct generic subclass of NSObject -
// <https://bugs.swift.org/browse/SR-2586>
public class PandorasBox<T>: NSObject {
final public var value: T
public init(_ value: T) {
// Uses ConstantIndirect access pattern
self.value = value
}
}
let c = PandorasBox(30)
// CHECK: 30
// Uses ConstantDirect access pattern
print(c.value)
// Super method calls from a generic subclass of an @objc class
class HasDynamicMethod : NSObject {
@objc dynamic class func funkyTown() {
print("Here we are with \(self)")
}
}
class GenericOverrideOfDynamicMethod<T> : HasDynamicMethod {
override class func funkyTown() {
print("Hello from \(self) with T = \(T.self)")
super.funkyTown()
print("Goodbye from \(self) with T = \(T.self)")
}
}
class ConcreteOverrideOfDynamicMethod : GenericOverrideOfDynamicMethod<Int> {
override class func funkyTown() {
print("Hello from \(self)")
super.funkyTown()
print("Goodbye from \(self)")
}
}
// CHECK: Hello from ConcreteOverrideOfDynamicMethod
// CHECK: Hello from ConcreteOverrideOfDynamicMethod with T = Int
// CHECK: Here we are with ConcreteOverrideOfDynamicMethod
// CHECK: Goodbye from ConcreteOverrideOfDynamicMethod with T = Int
// CHECK: Goodbye from ConcreteOverrideOfDynamicMethod
ConcreteOverrideOfDynamicMethod.funkyTown()
class Foo {}
class Bar {}
class DependOnAlignOf<T> : HasHiddenIvars2 {
var first = Foo()
var second = Bar()
var third: T?
}
let ad = DependOnAlignOf<Double>()
let ai = DependOnAlignOf<Int>()
do {
let fd = { (ad.x, ad.first, ad.second, ad.third) }
let fi = { (ai.x, ai.first, ai.second, ai.third) }
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fd())
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fi())
}
// Same as above, but there's another class in between the
// Objective-C class and us
class HasHiddenIvars3 : HasHiddenIvars2 { }
class AlsoDependOnAlignOf<T> : HasHiddenIvars3 {
var first = Foo()
var second = Bar()
var third: T?
}
do {
let ad = AlsoDependOnAlignOf<Double>()
let ai = AlsoDependOnAlignOf<Int>()
let fd = { (ad.x, ad.first, ad.second, ad.third) }
let fi = { (ai.x, ai.first, ai.second, ai.third) }
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fd())
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fi())
}
| apache-2.0 | 24a99378a63004d5f57df1233a5807ac | 20.033742 | 108 | 0.642993 | 3.044849 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Foundation/Extensions/UIDevice+Conveniences.swift | 1 | 6015 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public enum DevicePresenter {
public enum DeviceType: Int, Comparable {
case superCompact = 1 // SE
case compact = 2 // 8
case regular = 3 // Plus, X
case max = 4 // Max
public static func < (lhs: DevicePresenter.DeviceType, rhs: DevicePresenter.DeviceType) -> Bool {
lhs.rawValue < rhs.rawValue
}
}
public static let type: DeviceType = UIDevice.current.type
}
extension UIDevice {
public enum PhoneHeight: CGFloat {
case se = 568
case eight = 667
case plus = 736
case x = 812
case max = 896
}
fileprivate var type: DevicePresenter.DeviceType {
guard userInterfaceIdiom == .phone
else { return .regular }
let size = UIScreen.main.bounds.size
let height = max(size.width, size.height)
switch height {
case let height where height <= PhoneHeight.se.rawValue:
return .superCompact
case let height where height <= PhoneHeight.eight.rawValue:
return .compact
case let height where height <= PhoneHeight.x.rawValue:
return .regular
case let height where height > PhoneHeight.x.rawValue:
return .max
default:
// Impossible case
return .regular
}
}
// swiftlint:disable:next cyclomatic_complexity
private func modelName(for machineName: String) -> String {
switch machineName {
// iPod Touch line
case "iPod7,1":
return "iPod Touch 6"
case "iPod9,1":
return "iPod Touch 7"
// iPhone 5 line
case "iPhone6,1", "iPhone6,2":
return "iPhone 5s"
// iPhone SE line
case "iPhone8,4":
return "iPhone SE"
// iPhone 6 line
case "iPhone7,2":
return "iPhone 6"
case "iPhone7,1":
return "iPhone 6 Plus"
case "iPhone8,1":
return "iPhone 6s"
case "iPhone8,2":
return "iPhone 6s Plus"
// iPhone 7 line
case "iPhone9,1", "iPhone9,3":
return "iPhone 7"
case "iPhone9,2", "iPhone9,4":
return "iPhone 7 Plus"
// iPhone 8 line
case "iPhone10,1", "iPhone10,4":
return "iPhone 8"
case "iPhone10,2", "iPhone10,5":
return "iPhone 8 Plus"
// iPhone X Line
case "iPhone10,3", "iPhone10,6":
return "iPhone X"
case "iPhone11,2":
return "iPhone XS"
case "iPhone11,4", "iPhone11,6":
return "iPhone XS Max"
case "iPhone11,8":
return "iPhone XR"
// iPhone 11 Line
case "iPhone12,1":
return "iPhone 11"
case "iPhone12,3":
return "iPhone 11 Pro"
case "iPhone12,5":
return "iPhone 11 Pro Max"
case "iPhone12,8":
return "iPhone SE 2nd Gen"
// iPhone 12 Line
case "iPhone13,1":
return "iPhone 12 Mini"
case "iPhone13,2":
return "iPhone 12"
case "iPhone13,3":
return "iPhone 12 Pro"
case "iPhone13,4":
return "iPhone 12 Pro Max"
// iPhone 13 Line
case "iPhone14,2":
return "iPhone 13 Pro"
case "iPhone14,3":
return "iPhone 13 Pro Max"
case "iPhone14,4":
return "iPhone 13 Mini"
case "iPhone14,5":
return "iPhone 13"
// iPhone 14 Line
case "iPhone14,7":
return "iPhone 14"
case "iPhone14,8":
return "iPhone 14 Plus"
case "iPhone15,2":
return "iPhone 14 Pro"
case "iPhone15,3":
return "iPhone 14 Pro Max"
// iPad Air Line
case "iPad4,1", "iPad4,2", "iPad4,3":
return "iPad Air"
case "iPad5,3", "iPad5,4":
return "iPad Air 2"
case "iPad11,3", "iPad11,4":
return "iPad Air 3"
// iPad Line
case "iPad6,11", "iPad6,12":
return "iPad 5"
case "iPad7,5", "iPad7,6":
return "iPad 6"
case "iPad7,11", "iPad7,12":
return "iPad 7"
// iPad Mini Line
case "iPad4,4", "iPad4,5", "iPad4,6":
return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9":
return "iPad Mini 3"
case "iPad5,1", "iPad5,2":
return "iPad Mini 4"
// iPad Pro Line
case "iPad6,3", "iPad6,4":
return "iPad Pro 9.7 Inch"
case "iPad6,7", "iPad6,8":
return "iPad Pro 12.9 Inch"
case "iPad7,1", "iPad7,2":
return "iPad Pro 12.9 Inch 2. Generation"
case "iPad7,3", "iPad7,4":
return "iPad Pro 10.5 Inch"
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":
return "iPad Pro 12.9 Inch 3. Generation"
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":
return "iPad Pro 11 Inch"
case "iPad8,11", "iPad8,12":
return "iPad Pro 12.9 Inch 4. Generation"
case "iPad8,9", "iPad8,10":
return "iPad Pro 11 Inch 2. Generation"
case "i386", "x86_64":
return "Simulator"
default:
return "Unknown device: identifier \(machineName)"
}
}
private var machineName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = Mirror(reflecting: systemInfo.machine)
let machineName = machine.children.reduce(into: "") { result, element in
guard let value = element.value as? Int8, value != 0 else {
return
}
result.append(String(UnicodeScalar(UInt8(value))))
}
return machineName
}
public var modelName: String {
modelName(for: machineName)
}
}
| lgpl-3.0 | ed4a0033d03f5201c8a79c95ca8bd4b8 | 28.336585 | 105 | 0.520951 | 4.030831 | false | false | false | false |
qx/SiriAudioRecorder | ISAudioRecorder/ISAudioRecorderDemo.swift | 1 | 1878 | //
// ViewController.swift
// ISAudioRecorder
//
// Created by VSquare on 14/12/2015.
// Copyright © 2015 IgorSokolovsky. All rights reserved.
//
import UIKit
import AVFoundation
class ISAudioRecorderDemo: UIViewController,ISAudioRecorderViewDelegate {
var audioPlayer:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func openRecordController(sender: UIButton) {
let rvc = ISAudioRecorderViewController()
rvc.prepareViewForLoading(self)
rvc.recorderDelegate = self
}
@IBAction func playAudio(sender: AnyObject) {
if audioPlayer != nil && !audioPlayer.playing{
audioPlayer.play()
}else if audioPlayer != nil && audioPlayer.playing{
audioPlayer.stop()
}else{
print("Damn Man thers a problem need to learn Swift beter ")
}
}
func ISAudioRecorderViewWillDismiss(fileName: String, audioDuration: Int) {
print(fileName)
print(audioDuration)
let docDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let url = docDir.URLByAppendingPathComponent(fileName)
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
audioPlayer.prepareToPlay() // for AVAudioPlayerDelegate
}catch let error as NSError{
print(error)
}
}
}
| mit | 0e5658199557bd88dfc88f7159c7c150 | 30.283333 | 128 | 0.653703 | 5.30226 | false | false | false | false |
Merlini93/Weibo | Weibo/Weibo/Classes/Home/Popover/PopoverPresentationController.swift | 1 | 1307 | //
// PopoverPresentationController.swift
// Weibo
//
// Created by 李遨东 on 16/9/9.
// Copyright © 2016年 Merlini. All rights reserved.
//
import UIKit
class PopoverPresentationController: UIPresentationController {
var presentFrame = CGRectZero
override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
}
override func containerViewWillLayoutSubviews() {
if presentFrame == CGRectZero {
presentedView()?.frame = CGRect(x: 100, y: 56, width: 200, height: 200)
} else {
presentedView()?.frame = presentFrame
}
containerView?.insertSubview(cover, atIndex: 0)
}
private lazy var cover: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.0, alpha: 0.2)
view.frame = UIScreen.mainScreen().bounds
let tap = UITapGestureRecognizer(target: self, action: #selector(close))
view.addGestureRecognizer(tap)
return view
}()
func close() {
presentedViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | eab20cc5effb343205d81ac5de8ea146 | 28.5 | 120 | 0.657935 | 5.212851 | false | false | false | false |
vlaminck/LD33 | LD33/LD33/GameScene.swift | 1 | 8443 | //
// GameScene.swift
// LD33
//
// Created by Steven Vlaminck on 8/22/15.
// Copyright (c) 2015 MikeDave. All rights reserved.
//
import SpriteKit
struct PhysicsCategory {
static let None : UInt32 = 0
static let All : UInt32 = UInt32.max
static let Player : UInt32 = 0b1 // 1
static let Enemy : UInt32 = 0b10 // 2
static let Bullet : UInt32 = 0b100 // 4
static let Powerup : UInt32 = 0b1000 // 8
}
let playerCategory: UInt32 = 0x1 << 0
let enemyCategory: UInt32 = 0x1 << 1
let bulletCategory: UInt32 = 0x1 << 2
class GameScene: SKScene {
let playerMovePointsPerSec: CGFloat = 1000.0
var lastUpdateTime: NSTimeInterval = 0
var dt: NSTimeInterval = 0
var velocity = CGPointZero
var lastTouchLocation: CGPoint?
var player: Player!
var moveBulletAction: SKAction!
var waveCount = 0
var score: Int = 0 {
willSet {
if score / 1000 < newValue / 1000 {
// drop a free powerup for every 100 points earned
dropPowerup()
}
}
didSet {
scoreLabel.text = String(format: "Score: %06d", score)
}
}
var scoreLabel: SKLabelNode = SKLabelNode(text: "")
override func didMoveToView(view: SKView) {
/* Setup your scene here */
player = Player()
player.position = CGPoint(x: -200, y: size.height / 2)
addChild(player)
physicsWorld.contactDelegate = self
score = 0
addChild(scoreLabel)
scoreLabel.fontColor = SKColor.whiteColor()
scoreLabel.horizontalAlignmentMode = .Right
scoreLabel.position = CGPoint(x: size.width - 20, y: size.height - scoreLabel.frame.size.height - 110)
runAction(SKAction.repeatActionForever(SKAction.sequence([
SKAction.playSoundFileNamed("Invader.mp3", waitForCompletion: true),
SKAction.waitForDuration(10)
])))
testWave()
gameStart()
}
func testWave() {
}
func gameStart() {
let delayedStart = SKAction.waitForDuration(20)
runAction(SKAction.sequence([
delayedStart,
SKAction.runBlock { [weak self] in self?.sendWave(1) }
]))
let introScreen = SKSpriteNode(texture: nil, color: UIColor.blackColor(), size: size)
introScreen.anchorPoint = CGPointZero
addChild(introScreen)
let label = SKLabelNode(text: "You are the Monster")
label.fontSize = 100
introScreen.addChild(label)
label.position = CGPoint(x: introScreen.size.width / 2, y: introScreen.size.height / 2)
introScreen.runAction(SKAction.repeatActionForever(SKAction.sequence([
SKAction.waitForDuration(0.1),
SKAction.runBlock {
introScreen.color = SKColor.whiteColor()
},
SKAction.waitForDuration(0.1),
SKAction.runBlock { [weak self] in
if let randomColor = self?.randomColor() {
introScreen.color = randomColor
}
},
SKAction.waitForDuration(0.1),
SKAction.runBlock {
introScreen.color = SKColor.blackColor()
},
])))
introScreen.runAction(SKAction.sequence([
SKAction.moveByX(-size.width, y: 0, duration: 15),
SKAction.removeFromParent()
]))
player.runAction(SKAction.scaleBy(2, duration: 0))
player.position = CGPoint(x: size.width + 200, y: size.height * 3/4)
player.zRotation = CGFloat(M_PI_2) // face left
let flyIn = SKAction.moveByX(400, y: 0, duration: 2)
flyIn.timingMode = .EaseOut
player.runAction(SKAction.sequence([
SKAction.waitForDuration(10),
SKAction.moveByX((size.width + 400) * -1, y: 0, duration: 4),
SKAction.moveTo(CGPoint(x: -200, y: size.height / 2), duration: 1),
SKAction.scaleBy(0.5, duration: 0),
SKAction.rotateToAngle(CGFloat(-M_PI_2), duration: 0),
flyIn,
SKAction.runBlock { [weak self] in self?.player.startShooting() }
]))
}
func sendWave(var number: Int) {
if number > 2 {
number = 1
}
let wave = Wave(number: number, scene: self, delegate: self)
wave.start()
}
func randomColor() -> SKColor {
return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
sceneTouched(touches.first)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
sceneTouched(touches.first)
}
override func update(currentTime: CFTimeInterval) {
if lastUpdateTime > 0 {
dt = currentTime - lastUpdateTime
} else {
dt = 0
}
lastUpdateTime = currentTime
if let lastTouch = lastTouchLocation {
let diff = lastTouch - player.position
if (diff.length() <= playerMovePointsPerSec * CGFloat(dt)) {
player.position = lastTouchLocation!
velocity = CGPointZero
} else {
moveSprite(player, velocity: velocity)
}
}
}
func sceneTouched(touch: UITouch?) {
guard let touch = touch else { return }
let location = touch.locationInNode(self)
let offset = location - player.position
let direction = offset.normalized()
velocity = direction * playerMovePointsPerSec
lastTouchLocation = location
}
func moveSprite(sprite: SKSpriteNode, velocity: CGPoint) {
let amountToMove = velocity * CGFloat(dt)
sprite.position += amountToMove
}
func shoot() {
let bulletNode = SKShapeNode(rect: CGRect(x: 0, y: -2, width: 20, height: 4))
bulletNode.fillColor = SKColor.whiteColor()
bulletNode.strokeColor = SKColor.redColor()
bulletNode.glowWidth = 3
bulletNode.position = CGPoint(x: player.position.x + player.size.width / 2 - 20, y: player.position.y)
addChild(bulletNode)
bulletNode.runAction(moveBulletAction)
}
func updateBulletAction() {
// TODO: update based on player powerup level
moveBulletAction = SKAction.sequence([
SKAction.moveByX(size.width, y: 0, duration: 1),
SKAction.removeFromParent()
])
}
func dropPowerup() {
let powerup = PowerUp()
powerup.position = CGPoint(x: size.width + 100, y: size.height / 2)
addChild(powerup)
powerup.move()
}
}
extension GameScene: SKPhysicsContactDelegate {
func didBeginContact(contact: SKPhysicsContact) {
if let (_, _) = collision(contact, ordered: (Player.self, Enemy.self)) {
do {
try player.decrementPowerup()
} catch {
player.die()
}
}
if let (bullet, enemy) = collision(contact, ordered: (Bullet.self, Enemy.self)) {
bullet.removeFromParent()
do {
try enemy.hitByBullet(bullet.type)
} catch {
score += enemy.type.rawValue
}
}
if let (_, powerup) = collision(contact, ordered: (Player.self, PowerUp.self)) {
player.incrementPowerup()
powerup.removeFromParent()
score += 100
}
}
func collision<T, U>(contact: SKPhysicsContact, ordered: (T.Type, U.Type)) -> (T, U)? {
let things = (contact.bodyA.node, contact.bodyB.node)
if let first = things.0 as? T, second = things.1 as? U {
return (first, second)
}
if let first = things.1 as? T, second = things.0 as? U {
return (first, second)
}
return nil
}
}
extension GameScene: WaveDelegate {
func waveCompleted(number: Int) {
runAction(SKAction.sequence([
SKAction.waitForDuration(5),
SKAction.runBlock { [weak self] in self?.sendWave(number + 1) }
]))
}
}
| mit | 8bb49cc06eb10740a643443fc69caa10 | 30.621723 | 112 | 0.566505 | 4.505336 | false | false | false | false |
Brightify/DataMapper | Tests/Core/Map/SerializableMappableDataWrapperTest.swift | 1 | 12565 | //
// SerializableMappableDataWrapperTest.swift
// DataMapper
//
// Created by Filip Dolnik on 24.12.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Quick
import Nimble
import DataMapper
class SerializableMappableDataWrapperTest: QuickSpec {
private typealias CustomIntTransformation = TestData.CustomIntTransformation
override func spec() {
describe("SerializableMappableDataWrapper") {
describe("map optional") {
describe("mappable") {
it("sets data if value is not nil") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
var value: Int? = 1
var array: [Int]? = [1, 2]
var dictionary: [String: Int]? = ["a": 1, "b": 2]
var optionalArray: [Int?]? = [1, nil]
var optionalDictionary: [String: Int?]? = ["a": 1, "b": nil]
data["value"].map(&value)
data["array"].map(&array)
data["dictionary"].map(&dictionary)
data["optionalArray"].map(&optionalArray)
data["optionalDictionary"].map(&optionalDictionary)
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.validType
}
it("sets .null if value is nil") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
var value: Int?
var array: [Int]?
var dictionary: [String: Int]?
var optionalArray: [Int?]?
var optionalDictionary: [String: Int?]?
data["value"].map(&value)
data["array"].map(&array)
data["dictionary"].map(&dictionary)
data["optionalArray"].map(&optionalArray)
data["optionalDictionary"].map(&optionalDictionary)
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.nullType
}
}
describe("using transformation") {
it("sets data if value is not nil") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
var valueTransformation: Int? = 2
var arrayTransformation: [Int]? = [2, 4]
var dictionaryTransformation: [String: Int]? = ["a": 2, "b": 4]
var optionalArrayTransformation: [Int?]? = [2, nil]
var optionalDictionaryTransformation: [String: Int?]? = ["a": 2, "b": nil]
data["value"].map(&valueTransformation, using: CustomIntTransformation())
data["array"].map(&arrayTransformation, using: CustomIntTransformation())
data["dictionary"].map(&dictionaryTransformation, using: CustomIntTransformation())
data["optionalArray"].map(&optionalArrayTransformation, using: CustomIntTransformation())
data["optionalDictionary"].map(&optionalDictionaryTransformation, using: CustomIntTransformation())
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.validType
}
it("sets .null if value is nil") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
var valueTransformation: Int?
var arrayTransformation: [Int]?
var dictionaryTransformation: [String: Int]?
var optionalArrayTransformation: [Int?]?
var optionalDictionaryTransformation: [String: Int?]?
data["value"].map(&valueTransformation, using: CustomIntTransformation())
data["array"].map(&arrayTransformation, using: CustomIntTransformation())
data["dictionary"].map(&dictionaryTransformation, using: CustomIntTransformation())
data["optionalArray"].map(&optionalArrayTransformation, using: CustomIntTransformation())
data["optionalDictionary"].map(&optionalDictionaryTransformation, using: CustomIntTransformation())
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.nullType
}
}
}
describe("map value or") {
describe("mappable") {
it("sets data") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
var value: Int = 1
var array: [Int] = [1, 2]
var dictionary: [String: Int] = ["a": 1, "b": 2]
var optionalArray: [Int?] = [1, nil]
var optionalDictionary: [String: Int?] = ["a": 1, "b": nil]
data["value"].map(&value, or: 0)
data["array"].map(&array, or: [0])
data["dictionary"].map(&dictionary, or: ["a": 0])
data["optionalArray"].map(&optionalArray, or: [0])
data["optionalDictionary"].map(&optionalDictionary, or: ["a": 0])
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.validType
}
}
describe("using transformation") {
it("sets data") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
var valueTransformation: Int = 2
var arrayTransformation: [Int] = [2, 4]
var dictionaryTransformation: [String: Int] = ["a": 2, "b": 4]
var optionalArrayTransformation: [Int?] = [2, nil]
var optionalDictionaryTransformation: [String: Int?] = ["a": 2, "b": nil]
data["value"].map(&valueTransformation, using: CustomIntTransformation(), or: 0)
data["array"].map(&arrayTransformation, using: CustomIntTransformation(),or: [0])
data["dictionary"].map(&dictionaryTransformation, using: CustomIntTransformation(), or: ["a": 0])
data["optionalArray"].map(&optionalArrayTransformation, using: CustomIntTransformation(), or: [0])
data["optionalDictionary"].map(&optionalDictionaryTransformation, using: CustomIntTransformation(), or: ["a": 0])
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.validType
}
}
}
describe("map throws") {
describe("mappable") {
it("sets data") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
expect {
var value: Int = 1
var array: [Int] = [1, 2]
var dictionary: [String: Int] = ["a": 1, "b": 2]
var optionalArray: [Int?] = [1, nil]
var optionalDictionary: [String: Int?] = ["a": 1, "b": nil]
try data["value"].map(&value)
try data["array"].map(&array)
try data["dictionary"].map(&dictionary)
try data["optionalArray"].map(&optionalArray)
try data["optionalDictionary"].map(&optionalDictionary)
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.validType
return 0
}.toNot(throwError())
}
}
describe("using transformation") {
it("sets data") {
let delegate = SerializableData(objectMapper: ObjectMapper())
var data: MappableData = SerializableMappableDataWrapper(delegate: delegate)
expect {
var valueTransformation: Int = 2
var arrayTransformation: [Int] = [2, 4]
var dictionaryTransformation: [String: Int] = ["a": 2, "b": 4]
var optionalArrayTransformation: [Int?] = [2, nil]
var optionalDictionaryTransformation: [String: Int?] = ["a": 2, "b": nil]
try data["value"].map(&valueTransformation, using: CustomIntTransformation())
try data["array"].map(&arrayTransformation, using: CustomIntTransformation())
try data["dictionary"].map(&dictionaryTransformation, using: CustomIntTransformation())
try data["optionalArray"].map(&optionalArrayTransformation, using: CustomIntTransformation())
try data["optionalDictionary"].map(&optionalDictionaryTransformation, using: CustomIntTransformation())
expect((data as? SerializableMappableDataWrapper)?.delegate.raw) == TestData.Map.validType
return 0
}.toNot(throwError())
}
}
}
describe("subscript") {
let delegate = SerializableData(objectMapper: ObjectMapper(polymorph: StaticPolymorph()))
var value: Int? = 1
it("sets data with subData") {
var data = SerializableMappableDataWrapper(delegate: delegate)
data["a"]["b"].map(&value)
expect(data.delegate.raw) == TestData.Map.pathType
}
it("accepts array") {
var data = SerializableMappableDataWrapper(delegate: delegate)
data[["a", "b"]].map(&value)
expect(data.delegate.raw) == TestData.Map.pathType
}
it("accepts vararg") {
var data = SerializableMappableDataWrapper(delegate: delegate)
data["a", "b"].map(&value)
expect(data.delegate.raw) == TestData.Map.pathType
}
it("passes correct ObjectMapper") {
var data = SerializableMappableDataWrapper(delegate: delegate)
expect((data["a"] as? SerializableMappableDataWrapper)?.delegate.objectMapper) === data.delegate.objectMapper
}
}
}
}
}
| mit | 1e88389ea03703178a9fd1402711b16e | 55.594595 | 137 | 0.477714 | 6.152791 | false | true | false | false |
bryancmiller/rockandmarty | Text Adventure/Text Adventure/GameMaker.swift | 1 | 13639 | //
// GameMaker.swift
// Text Adventure
//
// Created by Bryan Miller on 5/1/17.
// Copyright © 2017 Bryan Miller. All rights reserved.
//
import UIKit
class GameMaker {
static func makeMap() -> Map {
let n = 8
let map: Map = Map(n: n)
// set everything in map
let place00 = Place(name: "sea", description: "On water", item: "")
map.setPlaceAt(place: place00, x: 0, y: 0)
let place10 = Place(name: "sea", description: "The water is deep here, we better head back to the church", item: "")
map.setPlaceAt(place: place10, x: 1, y: 0)
let place20 = Place(name: "sea", description: "the water is deep here, we better head back", item: "")
map.setPlaceAt(place: place20, x: 2, y: 0)
let place30 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place30, x: 3, y: 0)
let place40 = Place(name: "Lighthouse", description: "Ah, the lighthouse, we finally made it. Hopefully we have everything we need to send that signal, I think we're safe now", item: "win")
map.setPlaceAt(place: place40, x: 4, y: 0)
let place50 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place50, x: 5, y: 0)
let place60 = Place(name: "sea", description: "The water is deep here, we better head back to the mansion", item: "")
map.setPlaceAt(place: place60, x: 6, y: 0)
let place70 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place70, x: 7, y: 0)
let place01 = Place(name: "sea", description: "The water is deep here, we better head back to the church", item: "")
map.setPlaceAt(place: place01, x: 0, y: 1)
let place11 = Place(name: "Church", description: "Creepy old amish church, looks like no one has been here in years", item: "golden key")
map.setPlaceAt(place: place11, x: 1, y: 1)
let place21 = Place(name: "beach", description: "There's a little beach, it is very peaceful here", item: "")
map.setPlaceAt(place: place21, x: 2, y: 1)
let place31 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place31, x: 3, y: 1)
let place41 = Place(name: "Bridge", description: "A rickety bridge that has been poorly fixed by theft of a seesaw. The lighthouse is just ahead, do we have everything we need to send that beacon signal?", item: "")
map.setPlaceAt(place: place41, x: 4, y: 1)
let place51 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place51, x: 5, y: 1)
let place61 = Place(name: "Rich Mansion", description: "This must be the place where the rich hide during the festivals, I bet there's some good stuff in there, if only we had the key", item: "lighthouse key")
map.setPlaceAt(place: place61, x: 6, y: 1)
let place71 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place71, x: 7, y: 1)
let place02 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place02, x: 0, y: 2)
let place12 = Place(name: "Cliffs", description: "There is an extremely old church nearby on the coast", item: "")
map.setPlaceAt(place: place12, x: 1, y: 2)
let place22 = Place(name: "Cliffs", description: "Wow, this purge must do wonders for the overpopulation problem, I mean, look at the size of this cemetery below", item: "")
map.setPlaceAt(place: place22, x: 2, y: 2)
let place32 = Place(name: "cliffs", description: "From these cliffs you see a large cemetery with a church past it in one direction and a lighthouse of in the distance in another", item: "")
map.setPlaceAt(place: place32, x: 3, y: 2)
let place42 = Place(name: "cliffs", description: "There is a broken bridge just north of these cliffs, looks like we'll need something to help get across it, but the lighthouse is on the other side", item: "")
map.setPlaceAt(place: place42, x: 4, y: 2)
let place52 = Place(name: "cliffs", description: "These cliffs seem pretty high, we better be careful not to fall", item: "")
map.setPlaceAt(place: place52, x: 5, y: 2)
let place62 = Place(name: "cliffs", description: "More cliffs, there's a massive mansion in the distance, but it looks like it's on lock down and requires a key", item: "")
map.setPlaceAt(place: place62, x: 6, y: 2)
let place72 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place72, x: 7, y: 2)
let place03 = Place(name: "forest", description: "We're getting too far away from anything helpful, we better head back", item: "")
map.setPlaceAt(place: place03, x: 0, y: 3)
let place13 = Place(name: "Cemetery", description: "This cemetery is absolutely massive, there's a surprisingly familiar building nearby. There's also a church on the other side of these cliffs. But how do we get there?", item: "")
map.setPlaceAt(place: place13, x: 1, y: 3)
let place23 = Place(name: "Cemetery", description: "This cemetery looks bigger than the town. There are cliffs just north and a creepy playground nearby too", item: "")
map.setPlaceAt(place: place23, x: 2, y: 3)
let place33 = Place(name: "Spacecraft", description: "There is a spacecraft in the middle of some wheat here, but where did the key go? There are cliffs to the north where the lighthouse is way off in the distance, but they're too steep to climb", item: "beacon")
map.setPlaceAt(place: place33, x: 3, y: 3)
let place43 = Place(name: "wheat field", description: "Wheat as far as the eye can see, except for that farm nearby, and those cliffs to the north, we'll need something to climb them", item: "")
map.setPlaceAt(place: place43, x: 4, y: 3)
let place53 = Place(name: "small forest", description: "A tiny area where a lot of trees are growing, you can barely see through them and see what looks like cliffs just north", item: "")
map.setPlaceAt(place: place53, x: 5, y: 3)
let place63 = Place(name: "beach", description: "The beach looks like a nice retreat from the purge happening near the town, cliffs are just north", item: "")
map.setPlaceAt(place: place63, x: 6, y: 3)
let place73 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place73, x: 7, y: 3)
let place04 = Place(name: "forest", description: "The forest is too thick to go deeper, let's go back", item: "")
map.setPlaceAt(place: place04, x: 0, y: 4)
let place14 = Place(name: "General Store", description: "Vague memories pop up about a nice guy selling you some windshield wipers or something at this empty general store", item: "windshield wiper fluid")
map.setPlaceAt(place: place14, x: 1, y: 4)
let place24 = Place(name: "Playground", description: "A nice little playground, it's kind of morbid though that there's a smell of dead people nearby", item: "plank from the seesaw")
map.setPlaceAt(place: place24, x: 2, y: 4)
let place34 = Place(name: "field", description: "A field that looks like fun to run around in with small hills, but there's a creepy old farm in one direction and another creepy playground in the other", item: "")
map.setPlaceAt(place: place34, x: 3, y: 4)
let place44 = Place(name: "farm", description: "This farm looks old and abandoned, probably because the farmer is out purging", item: "")
map.setPlaceAt(place: place44, x: 4, y: 4)
let place54 = Place(name: "wheat field", description: "Just how much wheat does this guy farm? oh and there's a farm nearby", item: "")
map.setPlaceAt(place: place54, x: 5, y: 4)
let place64 = Place(name: "beach", description: "More beaches, it's kind of reminiscent of home", item: "")
map.setPlaceAt(place: place64, x: 6, y: 4)
let place74 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place74, x: 7, y: 4)
let place05 = Place(name: "forest", description: "The forest is too thick to go deeper, let's go back", item: "")
map.setPlaceAt(place: place05, x: 0, y: 5)
let place15 = Place(name: "town", description: "The outskirts of town, if we're going to head in there, we need something to defend ourselves", item: "")
map.setPlaceAt(place: place15, x: 1, y: 5)
let place25 = Place(name: "town", description: "If we're going to head into town, we need something to defend ourselves", item: "")
map.setPlaceAt(place: place25, x: 2, y: 5)
let place35 = Place(name: "town", description: "You see a town in the distance, it looks dangerous over there", item: "")
map.setPlaceAt(place: place35, x: 3, y: 5)
let place45 = Place(name: "Barn", description: "The farmer's barn, it's probably just filled with some wheat", item: "gun")
map.setPlaceAt(place: place45, x: 4, y: 5)
let place55 = Place(name: "wheat field", description: "You see more wheat, but it looks like there is an empty barn in one direction and an abandoned building in the other, but it looks like the abandoned building has lights on so we may need a defensive weapon", item: "")
map.setPlaceAt(place: place55, x: 5, y: 5)
let place65 = Place(name: "beach", description: "Honestly surprised that it's not more wheat. It's a beach, with really deep looking water to the south", item: "")
map.setPlaceAt(place: place65, x: 6, y: 5)
let place75 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place75, x: 7, y: 5)
let place06 = Place(name: "forest", description: "The forest is too thick to go deeper, let's go back", item: "")
map.setPlaceAt(place: place06, x: 0, y: 6)
let place16 = Place(name: "town", description: "The rest of the town, do we have that gun yet?", item: "")
map.setPlaceAt(place: place16, x: 1, y: 6)
let place26 = Place(name: "town square", description: "The middle of town, maybe there's something useful, maybe not", item: "ladder")
map.setPlaceAt(place: place26, x: 2, y: 6)
let place36 = Place(name: "town", description: "You hear a mixture of shouting and screaming off in the distance near the town square, we need a defensive weapon", item: "")
map.setPlaceAt(place: place36, x: 3, y: 6)
let place46 = Place(name: "road", description: "This road looks like it connects the town to the farm", item: "")
map.setPlaceAt(place: place46, x: 4, y: 6)
let place56 = Place(name: "Abandoned Building", description: "An abandoned building is here, but it looks quiet so we should be safe with a gun or something", item: "strange looking key")
map.setPlaceAt(place: place56, x: 5, y: 6)
let place66 = Place(name: "beach", description: "The sand at the beach is very soft this time of year", item: "")
map.setPlaceAt(place: place66, x: 6, y: 6)
let place76 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place76, x: 7, y: 6)
let place07 = Place(name: "forest", description: "The forest is too thick to go deeper, let's go back", item: "")
map.setPlaceAt(place: place07, x: 0, y: 7)
let place17 = Place(name: "forest", description: "The forest is too thick to go deeper, let's go back", item: "")
map.setPlaceAt(place: place17, x: 1, y: 7)
let place27 = Place(name: "forest", description: "The forest is too thick to go deeper, let's go back", item: "")
map.setPlaceAt(place: place27, x: 2, y: 7)
let place37 = Place(name: "forest", description: "The forest is too thick to go deeper, let's go back", item: "")
map.setPlaceAt(place: place37, x: 3, y: 7)
let place47 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place47, x: 4, y: 7)
let place57 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place57, x: 5, y: 7)
let place67 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place67, x: 6, y: 7)
let place77 = Place(name: "sea", description: "The water is deep here, we better head back", item: "")
map.setPlaceAt(place: place77, x: 7, y: 7)
return map
}
}
| apache-2.0 | e01cded8f4f748fe2c24ff9718c919c9 | 62.728972 | 281 | 0.624212 | 3.54879 | false | false | false | false |
HeMet/DLife | DLife/ViewModels/PostViewModel.swift | 1 | 1501 | //
// EntryViewModel.swift
// DLife
//
// Created by Евгений Губин on 16.06.15.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Foundation
import MVVMKit
class PostViewModel: BaseViewModel {
var data = ObservableArray<AnyObject>()
var currentEntry: EntryViewModel {
didSet {
onEntryChanged?()
loadComments()
}
}
var comments: ObservableArray<DLComment> = []
var onEntryChanged: (() -> ())?
var onAlert: (String -> ())?
private let api = DevsLifeAPI()
init(entry: DLEntry) {
currentEntry = EntryViewModel(entry: entry)
super.init()
}
func nextRandomPost() {
api.getRandomEntry(handleApiResult)
}
func handleApiResult(result: ApiResult<DLEntry>) {
switch result {
case .OK(let box):
currentEntry = EntryViewModel(entry: box.value)
case .Error(let error):
println(error)
onAlert?("Не удалось загрузить запись.")
}
}
func loadComments() {
api.getComments(currentEntry.entry.id) { [unowned self] result in
switch result {
case .OK(let box):
self.comments.replaceAll(box.value)
case .Error(let error):
println(error)
}
}
}
func showPost(id: String) {
api.getEntry(id, callback: handleApiResult)
}
} | mit | 3a3eaf611d9cb7e867c4ef43c3c0b312 | 22.269841 | 73 | 0.556997 | 4.246377 | false | false | false | false |
kiliankoe/apodidae | Sources/swift-library/Util.swift | 1 | 1045 | import Foundation
import Dispatch
import SwiftLibrary
func allPackages(query: String) -> [PackageData] {
let semaphore = DispatchSemaphore(value: 0)
var packages: [PackageData] = []
SwiftLibrary.query(query) { result in
switch result {
case .failure(let error):
print(error.localizedDescription)
semaphore.signal()
case .success(let fetchedPackages):
packages = fetchedPackages
semaphore.signal()
}
}
semaphore.wait()
return packages
}
func firstPackage(query: String) -> PackageData? {
return allPackages(query: query).first
}
func run(cmd: String, args: [String]) {
let task = Process()
task.launchPath = cmd
task.arguments = args
task.launch()
}
#if canImport(AppKit)
import AppKit
func addToPasteboard(string: String) {
let pb = NSPasteboard.general
pb.string(forType: .string)
pb.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pb.setString(string, forType: .string)
}
#endif
| mit | 70453ac34c702e45c39d1394f883b8b2 | 21.717391 | 69 | 0.660287 | 4.146825 | false | false | false | false |
zjjzmw1/speedxSwift | speedxSwift/speedxSwift/BikeVC.swift | 1 | 2186 | //
// Brand_VC.swift
// LBTabBar
//
// Created by chenlei_mac on 15/8/25.
// Copyright (c) 2015年 Bison. All rights reserved.
//
import UIKit
class BikeVC: BaseViewController {
/// 本月里程值
var distanceValueLabel : UILabel?
/// 本月里程
var distanceLabel : UILabel?
// 开始骑行按钮
var startButton : UIButton?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "骑行"
// 初始化控件
self.myView()
}
func myView() {
// 里程值
distanceValueLabel = Tool.initALabel(CGRectMake(0, 30, kScreenWidth, 120), textString: "0", font: UIFont.boldSystemFontOfSize(90), textColor: UIColor.whiteColor())
distanceValueLabel!.textAlignment = .Center
self.view.addSubview(distanceValueLabel!)
// 本月里程文字
distanceLabel = Tool.initALabel(CGRectMake((distanceValueLabel!.left()), distanceValueLabel!.bottom(), distanceValueLabel!.width(), 30), textString: "总里程", font: UIFont.systemFontOfSize(16), textColor: UIColor.whiteColor())
distanceLabel!.textAlignment = .Center
self.view.addSubview(distanceLabel!)
// 开始骑行按钮
startButton = Tool.initAButton(CGRectMake(0, kScreenHeight - kTabBarHeight - kNavBarHeight - 100, 70, 70), titleString: "", font: UIFont.boldSystemFontOfSize(12), textColor: UIColor.clearColor(), bgImage: UIImage.init(named: "ridding_start_button_image")!)
startButton?.center = CGPointMake(kScreenWidth/2, startButton!.centerY())
self.view.addSubview(startButton!)
startButton?.addTarget(self, action: #selector(BikeVC.startRidingAction), forControlEvents: UIControlEvents.TouchUpInside)
}
/// 开始骑行方法
func startRidingAction() {
var detailVC : RidingVC?
detailVC = RidingVC()
var navi : UINavigationController?
navi = UINavigationController(rootViewController: detailVC!)
// self.navigationController?.pushViewController(navi!, animated: true)
self.presentViewController(navi!, animated: true, completion: nil)
}
}
| mit | 33ab266b3f535c79bae6e325950f46a5 | 34.457627 | 264 | 0.669694 | 4.413502 | false | false | false | false |
johnno1962d/swift | benchmark/single-source/ProtocolDispatch.swift | 3 | 684 | //===--- ProtocolDispatch.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_ProtocolDispatch(_ N: Int) {
let x = someProtocolFactory()
for _ in 0...1000000 * N {
x.getValue()
}
}
| apache-2.0 | 73f6570cc76432d6182000bd8441c13e | 27.5 | 80 | 0.571637 | 4.684932 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/DescriptionHelpViewController.swift | 1 | 6424 | import UIKit
class DescriptionHelpViewController: ViewController {
@IBOutlet private weak var helpScrollView: UIScrollView!
@IBOutlet private weak var aboutTitleLabel: UILabel!
@IBOutlet private weak var aboutDescriptionLabel: UILabel!
@IBOutlet private weak var tipsTitleLabel: UILabel!
@IBOutlet private weak var tipsDescriptionLabel: UILabel!
@IBOutlet private weak var tipsForExampleLabel: UILabel!
@IBOutlet private weak var exampleOneTitleLabel: UILabel!
@IBOutlet private weak var exampleOneDescriptionLabel: UILabel!
@IBOutlet private weak var exampleTwoTitleLabel: UILabel!
@IBOutlet private weak var exampleTwoDescriptionLabel: UILabel!
@IBOutlet private weak var moreInfoTitleLabel: UILabel!
@IBOutlet private weak var moreInfoDescriptionLabel: UILabel!
@IBOutlet private weak var aboutWikidataLabel: UILabel!
@IBOutlet private weak var wikidataGuideLabel: UILabel!
@IBOutlet private var allLabels: [UILabel]!
@IBOutlet private var headingLabels: [UILabel]!
@IBOutlet private var italicLabels: [UILabel]!
@IBOutlet private var exampleBackgroundViews: [UIView]!
@IBOutlet private var imageViews: [UIImageView]!
@IBOutlet private var dividerViews: [UIView]!
required convenience init?(coder aDecoder: NSCoder) {
self.init(theme: Theme.standard)
}
public override func viewDidLoad() {
scrollView = helpScrollView
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:)))
navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
title = WMFLocalizedString("description-help-title", value:"Article description help", comment:"Title for description editing help page")
aboutTitleLabel.text = WMFLocalizedString("description-help-about-title", value:"About", comment:"Description editing about label text")
aboutDescriptionLabel.text = WMFLocalizedString("description-help-about-description", value:"Article descriptions summarize an article to help readers understand the subject at a glance.", comment:"Description editing details label text")
tipsTitleLabel.text = WMFLocalizedString("description-help-tips-title", value:"Tips for creating descriptions", comment:"Description editing tips label text")
tipsDescriptionLabel.text = WMFLocalizedString("description-help-tips-description", value:"Descriptions should ideally fit on one line, and are between two to twelve words long. They are not capitalized unless the first word is a proper noun.", comment:"Description editing tips details label text")
tipsForExampleLabel.text = WMFLocalizedString("description-help-tips-for-example", value:"For example:", comment:"Examples label text")
exampleOneTitleLabel.text = WMFLocalizedString("description-help-tips-example-title-one", value:"painting by Leonardo Da Vinci", comment:"First example label text")
exampleOneDescriptionLabel.text = WMFLocalizedString("description-help-tips-example-description-one", value:"article description for an article about the Mona Lisa", comment:"First example description text")
exampleTwoTitleLabel.text = WMFLocalizedString("description-help-tips-example-title-two", value:"Earth’s highest mountain", comment:"Second example label text")
exampleTwoDescriptionLabel.text = WMFLocalizedString("description-help-tips-example-description-two", value:"article description for an article about Mount Everest", comment:"Second example description text")
moreInfoTitleLabel.text = WMFLocalizedString("description-help-more-info-title", value:"More information", comment:"Article descriptions more info heading text")
moreInfoDescriptionLabel.text = WMFLocalizedString("description-help-more-info-description", value:"Descriptions are stored and maintained on Wikidata, a project of the Wikimedia Foundation which provides a free, collaborative, multilingual, secondary database supporting Wikipedia and other projects.", comment:"Article descriptions more info details text")
aboutWikidataLabel.text = WMFLocalizedString("description-help-about-wikidata", value:"About Wikidata", comment:"About Wikidata label text")
wikidataGuideLabel.text = WMFLocalizedString("description-help-wikidata-guide", value:"Wikidata guide for writing descriptions", comment:"Wikidata guide label text")
updateFonts()
}
@objc func closeButtonPushed(_ : UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
override func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.midBackground
imageViews.forEach {
$0.tintColor = theme.colors.primaryText
}
allLabels.forEach {
$0.textColor = theme.colors.primaryText
}
exampleBackgroundViews.forEach {
$0.backgroundColor = theme.colors.descriptionBackground
}
headingLabels.forEach {
$0.textColor = theme.colors.secondaryText
}
dividerViews.forEach {
$0.backgroundColor = theme.colors.border
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
allLabels.forEach {
$0.set(dynamicTextStyle: .body)
}
headingLabels.forEach {
$0.set(dynamicTextStyle: .headline)
}
italicLabels.forEach {
$0.set(dynamicTextStyle: .italicBody)
}
}
@IBAction func showAboutWikidataPage() {
navigate(to: URL(string: "https://m.wikidata.org/wiki/Wikidata:Introduction"))
}
@IBAction func showWikidataGuidePage() {
navigate(to: URL(string: "https://m.wikidata.org/wiki/Help:Description#Guidelines_for_descriptions_in_English"))
}
}
private extension UILabel {
func set(dynamicTextStyle: DynamicTextStyle) {
font = UIFont.wmf_font(dynamicTextStyle, compatibleWithTraitCollection: traitCollection)
}
}
| mit | 291620282b6b1b1c39c805b3ca6ce1af | 50.376 | 366 | 0.724541 | 5.1376 | false | false | false | false |
Arti3DPlayer/USBDeviceSwift | RaceflightControllerHIDExample/RaceflightControllerHIDExample/RFDevice.swift | 1 | 2237 | //
// RFDevice.swift
// RaceflightControllerHIDExample
//
// Created by Artem Hruzd on 6/17/17.
// Copyright © 2017 Artem Hruzd. All rights reserved.
//
import Cocoa
import USBDeviceSwift
class RFDevice: NSObject {
let deviceInfo:HIDDevice
required init(_ deviceInfo:HIDDevice) {
self.deviceInfo = deviceInfo
}
func sendCommad(command:String) {
let safeStr = command.trimmingCharacters(in: .whitespacesAndNewlines)
if let commandData = safeStr.data(using: .utf8) {
self.write(commandData)
}
}
func write(_ data: Data) {
var bytesArray = [UInt8](data)
let reportId:UInt8 = 2
bytesArray.insert(reportId, at: 0)
bytesArray.append(0)// hack every report should end with 0 byte
if (bytesArray.count > self.deviceInfo.reportSize) {
print("Output data too large for USB report")
return
}
let correctData = Data(bytes: UnsafePointer<UInt8>(bytesArray), count: self.deviceInfo.reportSize)
IOHIDDeviceSetReport(
self.deviceInfo.device,
kIOHIDReportTypeOutput,
CFIndex(reportId),
(correctData as NSData).bytes.bindMemory(to: UInt8.self, capacity: correctData.count),
correctData.count
)
}
// Additional: convertion bytes to specific string, removing garbage etc.
func convertByteDataToString(_ data:Data, removeId:Bool=true, cleanGarbage:Bool=true) -> String {
let count = data.count / MemoryLayout<UInt8>.size
var array = [UInt8](repeating: 0, count: count)
data.copyBytes(to: &array, count:count * MemoryLayout<UInt8>.size)
if (array.count>0 && removeId) {
array.remove(at: 0)
}
var strResp:String = ""
for byte in array {
strResp += String(UnicodeScalar(byte))
}
if (cleanGarbage) {
if let dotRange = strResp.range(of: "\0") {
strResp.removeSubrange(dotRange.lowerBound..<strResp.endIndex)
}
}
strResp = strResp.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return strResp
}
}
| mit | cb2f27d5f659dd965899387f63c784a1 | 31.882353 | 106 | 0.61136 | 4.226843 | false | false | false | false |
BigZhanghan/DouYuLive | DouYuLive/DouYuLive/Classes/Home/ViewModel/RecommandViewModel.swift | 1 | 4370 | //
// RecommandViewModel.swift
// DouYuLive
//
// Created by zhanghan on 2017/10/9.
// Copyright © 2017年 zhanghan. All rights reserved.
//
import UIKit
class RecommandViewModel {
lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]()
lazy var hotData : AnchorGroup = AnchorGroup()
lazy var prettyData : AnchorGroup = AnchorGroup()
lazy var cycleModels : [CycleModel] = [CycleModel]()
}
extension RecommandViewModel {
func requestData(finishedCallBack : @escaping () -> ()) {
let disGroup = DispatchGroup()
//热门
disGroup.enter()
NetworkTools.requestData(type: MethodType.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : NSDate.getCurrentTime()]) { (result) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else {
return
}
// 2.根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {
return
}
self.hotData.tag_name = "热门"
self.hotData.icon_name = "home_header_hot"
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.hotData.anchors.append(anchor)
}
disGroup.leave()
}
let parameters = ["limit" : "4", "offset" : "0", "time" : NSDate.getCurrentTime()]
//颜值
disGroup.enter()
NetworkTools.requestData(type: MethodType.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom",parameters: parameters) { (result) in
guard let resultDict = result as? [String : NSObject] else {
return
}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {
return
}
self.prettyData.tag_name = "颜值"
self.prettyData.icon_name = "home_header_phone"
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.prettyData.anchors.append(anchor)
}
disGroup.leave()
}
//热门
disGroup.enter()
// http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1507532912
// print(NSDate.getCurrentTime())
NetworkTools.requestData(type: MethodType.get, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate",parameters: parameters) { (result) in
guard let resultDict = result as? [String : NSObject] else {
return
}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {
return
}
for dict in dataArray {
let group = AnchorGroup(dict: dict)
self.anchorGroups.append(group)
}
// for group in self.anchorGroups {
// print(group.tag_name)
// for anchor in group.anchors {
// print(anchor.nickname)
// }
// print("----------------")
// }
disGroup.leave()
}
//所有请求结束,进行数据排序
disGroup.notify(queue: DispatchQueue.main) {
self.anchorGroups.insert(self.prettyData, at: 0)
self.anchorGroups.insert(self.hotData, at: 0)
finishedCallBack()
}
}
func requsetCycleData(finishedCallBack : @escaping () -> ()) {
NetworkTools.requestData(type: MethodType.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in
guard let resultDict = result as? [String : NSObject] else {
return
}
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {
return
}
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishedCallBack()
}
}
}
| mit | 07bc8431d99fd870374f70d3703495f1 | 32.80315 | 176 | 0.511297 | 4.775306 | false | false | false | false |
chourobin/GPUImage2 | framework/Source/Framebuffer.swift | 1 | 9088 | #if os(Linux)
import Glibc
#if GLES
import COpenGLES.gles2
let GL_BGRA = GL_RGBA // A hack: Raspberry Pi needs this or framebuffer creation fails
#else
import COpenGL
#endif
#else
#if GLES
import OpenGLES
#else
import OpenGL.GL3
#endif
#endif
import Foundation
// TODO: Add a good lookup table to this to allow for detailed error messages
struct FramebufferCreationError:Error {
let errorCode:GLenum
}
public enum FramebufferTimingStyle {
case stillImage
case videoFrame(timestamp:Timestamp)
func isTransient() -> Bool {
switch self {
case .stillImage: return false
case .videoFrame: return true
}
}
var timestamp:Timestamp? {
get {
switch self {
case .stillImage: return nil
case let .videoFrame(timestamp): return timestamp
}
}
}
}
public class Framebuffer {
public var timingStyle:FramebufferTimingStyle = .stillImage
public var orientation:ImageOrientation
public let texture:GLuint
let framebuffer:GLuint?
let stencilBuffer:GLuint?
let size:GLSize
let internalFormat:Int32
let format:Int32
let type:Int32
let hash:Int64
let textureOverride:Bool
public init(context:OpenGLContext, orientation:ImageOrientation, size:GLSize, textureOnly:Bool = false, minFilter:Int32 = GL_LINEAR, magFilter:Int32 = GL_LINEAR, wrapS:Int32 = GL_CLAMP_TO_EDGE, wrapT:Int32 = GL_CLAMP_TO_EDGE, internalFormat:Int32 = GL_RGBA, format:Int32 = GL_BGRA, type:Int32 = GL_UNSIGNED_BYTE, stencil:Bool = false, overriddenTexture:GLuint? = nil) throws {
self.size = size
self.orientation = orientation
self.internalFormat = internalFormat
self.format = format
self.type = type
self.hash = hashForFramebufferWithProperties(orientation:orientation, size:size, textureOnly:textureOnly, minFilter:minFilter, magFilter:magFilter, wrapS:wrapS, wrapT:wrapT, internalFormat:internalFormat, format:format, type:type, stencil:stencil)
if let newTexture = overriddenTexture {
textureOverride = true
texture = newTexture
} else {
textureOverride = false
texture = generateTexture(minFilter:minFilter, magFilter:magFilter, wrapS:wrapS, wrapT:wrapT)
}
if (!textureOnly) {
do {
let (createdFrameBuffer, createdStencil) = try generateFramebufferForTexture(texture, width:size.width, height:size.height, internalFormat:internalFormat, format:format, type:type, stencil:stencil)
framebuffer = createdFrameBuffer
stencilBuffer = createdStencil
} catch {
stencilBuffer = nil
framebuffer = nil
throw error
}
} else {
stencilBuffer = nil
framebuffer = nil
}
}
deinit {
if (!textureOverride) {
var mutableTexture = texture
glDeleteTextures(1, &mutableTexture)
debugPrint("Delete texture at size: \(size)")
}
if let framebuffer = framebuffer {
var mutableFramebuffer = framebuffer
glDeleteFramebuffers(1, &mutableFramebuffer)
}
if let stencilBuffer = stencilBuffer {
var mutableStencil = stencilBuffer
glDeleteRenderbuffers(1, &mutableStencil)
}
}
public func sizeForTargetOrientation(_ targetOrientation:ImageOrientation) -> GLSize {
if self.orientation.rotationNeededForOrientation(targetOrientation).flipsDimensions() {
return GLSize(width:size.height, height:size.width)
} else {
return size
}
}
func aspectRatioForRotation(_ rotation:Rotation) -> Float {
if rotation.flipsDimensions() {
return Float(size.width) / Float(size.height)
} else {
return Float(size.height) / Float(size.width)
}
}
func texelSize(for rotation:Rotation) -> Size {
if rotation.flipsDimensions() {
return Size(width:1.0 / Float(size.height), height:1.0 / Float(size.width))
} else {
return Size(width:1.0 / Float(size.width), height:1.0 / Float(size.height))
}
}
func initialStageTexelSize(for rotation:Rotation) -> Size {
if rotation.flipsDimensions() {
return Size(width:1.0 / Float(size.height), height:0.0)
} else {
return Size(width:0.0, height:1.0 / Float(size.height))
}
}
func texturePropertiesForOutputRotation(_ rotation:Rotation) -> InputTextureProperties {
return InputTextureProperties(textureCoordinates:rotation.textureCoordinates(), texture:texture)
}
func texturePropertiesForTargetOrientation(_ targetOrientation:ImageOrientation) -> InputTextureProperties {
return texturePropertiesForOutputRotation(self.orientation.rotationNeededForOrientation(targetOrientation))
}
public func activateFramebufferForRendering() {
guard let framebuffer = framebuffer else { fatalError("ERROR: Attempted to activate a framebuffer that has not been initialized") }
glBindFramebuffer(GLenum(GL_FRAMEBUFFER), framebuffer)
glViewport(0, 0, size.width, size.height)
}
// MARK: -
// MARK: Framebuffer cache
weak var cache:FramebufferCache?
var framebufferRetainCount = 0
public func lock() {
framebufferRetainCount += 1
}
func resetRetainCount() {
framebufferRetainCount = 0
}
func unlock() {
framebufferRetainCount -= 1
if (framebufferRetainCount < 1) {
if ((framebufferRetainCount < 0) && (cache != nil)) {
print("WARNING: Tried to overrelease a framebuffer")
}
framebufferRetainCount = 0
cache?.returnToCache(self)
}
}
}
func hashForFramebufferWithProperties(orientation:ImageOrientation, size:GLSize, textureOnly:Bool = false, minFilter:Int32 = GL_LINEAR, magFilter:Int32 = GL_LINEAR, wrapS:Int32 = GL_CLAMP_TO_EDGE, wrapT:Int32 = GL_CLAMP_TO_EDGE, internalFormat:Int32 = GL_RGBA, format:Int32 = GL_BGRA, type:Int32 = GL_UNSIGNED_BYTE, stencil:Bool = false) -> Int64 {
var result:Int64 = 1
let prime:Int64 = 31
let yesPrime:Int64 = 1231
let noPrime:Int64 = 1237
// TODO: Complete the rest of this
result = prime * result + Int64(size.width)
result = prime * result + Int64(size.height)
result = prime * result + Int64(internalFormat)
result = prime * result + Int64(format)
result = prime * result + Int64(type)
result = prime * result + (textureOnly ? yesPrime : noPrime)
result = prime * result + (stencil ? yesPrime : noPrime)
return result
}
// MARK: -
// MARK: Framebuffer-related extensions
extension Rotation {
func textureCoordinates() -> [GLfloat] {
switch self {
case .noRotation: return [0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]
case .rotateCounterclockwise: return [0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0]
case .rotateClockwise: return [1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0]
case .rotate180: return [1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0]
case .flipHorizontally: return [1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0]
case .flipVertically: return [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0]
case .rotateClockwiseAndFlipVertically: return [0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]
case .rotateClockwiseAndFlipHorizontally: return [1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
}
}
func croppedTextureCoordinates(offsetFromOrigin:Position, cropSize:Size) -> [GLfloat] {
let minX = GLfloat(offsetFromOrigin.x)
let minY = GLfloat(offsetFromOrigin.y)
let maxX = GLfloat(offsetFromOrigin.x) + GLfloat(cropSize.width)
let maxY = GLfloat(offsetFromOrigin.y) + GLfloat(cropSize.height)
switch self {
case .noRotation: return [minX, minY, maxX, minY, minX, maxY, maxX, maxY]
case .rotateCounterclockwise: return [minX, maxY, minX, minY, maxX, maxY, maxX, minY]
case .rotateClockwise: return [maxX, minY, maxX, maxY, minX, minY, minX, maxY]
case .rotate180: return [maxX, maxY, minX, maxY, maxX, minY, minX, minY]
case .flipHorizontally: return [maxX, minY, minX, minY, maxX, maxY, minX, maxY]
case .flipVertically: return [minX, maxY, maxX, maxY, minX, minY, maxX, minY]
case .rotateClockwiseAndFlipVertically: return [minX, minY, minX, maxY, maxX, minY, maxX, maxY]
case .rotateClockwiseAndFlipHorizontally: return [maxX, maxY, maxX, minY, minX, maxY, minX, minY]
}
}
}
public extension Size {
func glWidth() -> GLint {
return GLint(round(Double(self.width)))
}
func glHeight() -> GLint {
return GLint(round(Double(self.height)))
}
}
| bsd-3-clause | db7bfc2cb02cdcfb56d3ba79127aa93b | 36.399177 | 380 | 0.631712 | 4.037317 | false | false | false | false |
brokenseal/iOS-exercises | Team Treehouse/VendingMachine-Swift3/VendingMachine/VendingMachine.swift | 1 | 4128 | //
// VendingMachine.swift
// VendingMachine
//
// Created by Screencast on 12/6/16.
// Copyright © 2016 Treehouse Island, Inc. All rights reserved.
//
import Foundation
import UIKit
enum VendingSelection: String {
case soda
case dietSoda
case chips
case cookie
case sandwich
case wrap
case candyBar
case popTart
case water
case fruitJuice
case sportsDrink
case gum
func icon() -> UIImage {
if let image = UIImage(named: self.rawValue) {
return image
} else {
return #imageLiteral(resourceName: "default")
}
}
}
protocol VendingItem {
var price: Double { get }
var quantity: Int { get set }
}
protocol VendingMachine {
var selection: [VendingSelection] { get }
var inventory: [VendingSelection: VendingItem] { get set }
var amountDeposited: Double { get set }
init(inventory: [VendingSelection: VendingItem])
func vend(_ selection: VendingSelection, quantity: Int) throws
func deposit(_ amount: Double)
func item(forSelection selection: VendingSelection) -> VendingItem?
}
struct Item: VendingItem {
let price: Double
var quantity: Int
}
enum VendingMachineError : Error {
case invalidSelection
case outOfStock
case insufficientFunds(require: Double)
}
class FoodVendingMachine: VendingMachine {
let selection: [VendingSelection] = [.soda, .dietSoda, .chips, .cookie, .wrap, .sandwich, .candyBar, .popTart, .water, .fruitJuice, .sportsDrink, .gum]
var inventory: [VendingSelection : VendingItem]
var amountDeposited: Double = 10.0
required init(inventory: [VendingSelection : VendingItem]) {
self.inventory = inventory
}
func vend(_ selection: VendingSelection, quantity: Int) throws {
guard var item = inventory[selection] else {
throw VendingMachineError.invalidSelection
}
guard item.quantity >= quantity else {
throw VendingMachineError.outOfStock
}
let totalPrice = item.price * Double(quantity)
if amountDeposited >= totalPrice {
amountDeposited -= totalPrice
item.quantity -= quantity
inventory.updateValue(item, forKey: selection)
} else {
let amountRequired = totalPrice - amountDeposited
throw VendingMachineError.insufficientFunds(require: amountRequired)
}
}
func deposit(_ amount: Double) {
amountDeposited += amount
}
func item(forSelection selection: VendingSelection) -> VendingItem? {
return inventory[selection]
}
}
enum InventoryError : Error {
case invalidResource
case conversionFailure
case invalidSelection
}
class PListConverter {
static func dictionary(fromFile name: String, ofType type: String) throws -> [String: AnyObject]{
guard let path = Bundle.main.path(forResource: name, ofType: type) else {
throw InventoryError.invalidResource
}
guard let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] else {
throw InventoryError.conversionFailure
}
return dictionary
}
}
class InventoryUnarchiver {
static func vendingInventory(fromDictionary dictionary: [String: AnyObject]) throws -> [VendingSelection: VendingItem]{
var inventory: [VendingSelection: VendingItem] = [:]
for (key, value) in dictionary {
if let itemDictionary = value as? [String: Any],
let price = itemDictionary["price"] as? Double,
let quantity = itemDictionary["quantity"] as? Int {
let item = Item(price: price, quantity: quantity)
guard let selection = VendingSelection(rawValue: key) else {
throw InventoryError.invalidSelection
}
inventory.updateValue(item, forKey: selection)
}
}
return inventory
}
}
| mit | 8188972aeb1436d43c6bf714df8348fd | 27.86014 | 155 | 0.626363 | 4.684449 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Analytics/Events/Analytics+MediaActionEvents.swift | 1 | 1606 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireSyncEngine
let conversationMediaCompleteActionEventName = "contributed"
extension Analytics {
func tagLiked(in conversation: ZMConversation) {
var attributes = conversation.ephemeralTrackingAttributes
attributes["message_action"] = "like"
attributes.merge(conversation.attributesForConversation, strategy: .preferNew)
tagEvent(conversationMediaCompleteActionEventName, attributes: attributes)
}
func tagMediaActionCompleted(_ action: ConversationMediaAction,
inConversation conversation: ZMConversation) {
var attributes = conversation.ephemeralTrackingAttributes
attributes["message_action"] = action.attributeValue
attributes.merge(conversation.attributesForConversation, strategy: .preferNew)
tagEvent(conversationMediaCompleteActionEventName, attributes: attributes)
}
}
| gpl-3.0 | a8a6223dc9c22cdfb0e1770b305c15a2 | 39.15 | 86 | 0.742839 | 4.896341 | false | false | false | false |
brittlewis12/vim-config | bundle/vim-swift/test/constants_and_variables.swift | 1 | 97 | let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
var x = 0.0, y = 0.0, z = 0.0
| mit | 3051d6e266fc2986b793a450d748d93f | 23.25 | 37 | 0.701031 | 2.852941 | false | false | false | false |
developerY/Active-Learning-Swift-2.0_OLD | ActiveLearningSwift2.playground/Pages/Properties.xcplaygroundpage/Contents.swift | 3 | 10798 | //: [Previous](@previous)
//: ------------------------------------------------------------------------------------------------
//: Things to know:
//:
//: * Properties store values in classes, structures and enumerations.
//: ------------------------------------------------------------------------------------------------
//: Here's a structure with a couple simple stored properties:
struct FixedLengthRange
{
var firstValue: Int
let length: Int
}
//: Structures must have all of their properties initialized upon instantiation.
//:
//: This won't compile since the struct includes properties that havn't been initialized with
//: default values:
//:
//: var anotherRangeOfThreeItems = FixedLengthRange()
//:
//: In order to instantiate a FixedLengthRange struct, we must use the memberwise initializer. Note
//: that this will initialize a constant property and a variable property inside the struct:
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
rangeOfThreeItems.firstValue = 6
//: ------------------------------------------------------------------------------------------------
//: Lazy Stored Properties
//:
//: A Lazy Stored Property is a value that is not calculated until its first use.
//:
//: They are declared using the "lazy" attribute and may not be constant.
//:
//: Global and local variables are all lazy, except that they don't need the lazy attribute.
//:
//: Here, we'll define a couple classes to showcase Lazy Stored Properties. In this example, let's
//: assume that DataImporter is a time-consuming process, and as such, we will want to use a lazy
//: stored property whenever we use it. This way, if we end up never using it, we never pay the
//: penalty of instantiating it.
class DataImporter
{
var filename = "data.txt"
}
class DataManager
{
lazy var importer = DataImporter()
var data = [String]()
}
//: Now let's instantiate the data manager and add some simple data to the class:
let manager = DataManager()
manager.data.append("Some data")
manager.data.append("Some more data")
//: Notice how we haven't used the importer yet, so it is nil:
manager
//: So now let's access it:
manager.importer.filename
//: And now we see the importer was created:
manager
//: ------------------------------------------------------------------------------------------------
//: Computed Properties
//:
//: Computed properties don't store data, but rather use getters and setters for accessing values
//: that are computed up on request.
//:
//: Computed Properties are available for global as well as local variables.
//:
//: We'll start with a few structures that we'll use to show how computed properties work.
struct Point
{
var x = 0.0, y = 0.0
}
struct Size
{
var width = 0.0, height = 0.0
}
//: The following structure includes a computed property with a Point type named 'center'. Notice
//: that 'center' is variable (not constant) which is a requirement of computed properties.
//:
//: Every computed property must have a getter, but does not need a setter. If we provide a setter,
//: we need to know the new value being assigned to the computed property. We've called this
//: value 'newCenter'. Note that this value does not have a type annotation because the computed
//: property already knows that it is a Point type. Providing a type annotation would be an error.
struct Rect
{
var origin = Point()
var size = Size()
var center: Point
{
get
{
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter)
{
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
//: Here, we'll create a square from our Rect structure
var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))
//: We can now get the center point, computed from the Rect's origin and size. Being a computed
//: property, we can treat it just like any other peroperty.
let initialSquareCenter = square.center
//: Since we provided a setter, we can also set the center point as if it is a stored property.
//: This will effectively update the Rect's origin and size based on the specified center point.
square.center = Point(x: 15, y: 15)
//: We can see that the origin has been updated from (0, 0) to (10, 10):
square.origin
//: Shorthand Setter Declaration
//:
//: The computed property's setter from the Rect structure provided a parameter on the setter named
//: 'newCenter'. If we don't specify this parameter, Swift will automatically generate an input
//: value named 'newValue' for us.
//:
//: Here, AlternativeRect is the same declaration as Rect above, except that the setter uses
//: Swift's default setter value, 'newValue':
struct AlternativeRect
{
var origin = Point()
var size = Size()
var center: Point
{
get
{
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set
{
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
//: We can also have a read-only computed property by simply omitting the setter:
struct Cube
{
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double
{
get
{
return width * height * depth
}
}
}
//: Alternatively, Swift allows us to shorten the syntax of a read-only computed property by
//: omitting the get{} construct and inserting the code for the getter directly into the property
//: declaration:
struct AnotherCube
{
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double
{
return width * height * depth
}
}
//: Let's declare our structure and read the 'volume' property
var cube = AnotherCube(width: 4, height: 5, depth: 2)
cube.volume
//: Since the 'volume' property is read-only, if we tried to assign a value to it, it would
//: would generate a compiler error.
//:
//: The following line of code will not compile:
//:
//: cube.volume = 8.0
//: ------------------------------------------------------------------------------------------------
//: Property Observers
//:
//: Property observers allow us to respond to changes in a property's value. We can declare an
//: observer that contains our code that is run just before a property is set (optionally allowing
//: us to alter the value being set) and an observer that is run just after a property has been
//: modified.
//:
//: Property observers are available for global as well as local variables.
//:
//: These observers are not called when a property is first initialized, but only when it changes.
//:
//: Similar to setters, each 'willSet' and 'didSet' will receive a parameter that represents (in
//: the case of 'willSet') the value about to be assigned to the property and (in the case of
//: 'didSet') the value that was previously stored in the property prior to modification.
class StepCounter
{
var totalSteps: Int = 0
{
willSet(newTotalSteps)
{
"About to step to \(newTotalSteps)"
}
didSet(oldTotalSteps)
{
"Just stepped from \(oldTotalSteps)"
}
}
}
//: Let's create an instance of StepCounter so we can try out our observer
let stepCounter = StepCounter()
//: The following will first call 'willSet' on the 'totalSteps' property, followed by a change to
//: the value itself, followed by a call to 'didSet'
stepCounter.totalSteps = 200;
//: Similar to setters, we can shorten our observers by omitting the parameter list for each. When
//: we co this, Swift automatically provides parameters named 'newValue' and 'oldValue'
class StepCounterShorter
{
var totalSteps: Int = 0
{
willSet{ "About to step to \(newValue)" }
didSet { "Just stepped from \(oldValue)" }
}
}
//: We can also override the value being set by modifying the property itself within the 'didSet'
//: observer. This only works in the 'didSet'. If you attempt to modify the property in 'willSet'
//: you will receive a compiler warning.
//:
//: Let's try wrapping our value to the range of 0...255
class StepCounterShorterWithModify
{
var totalSteps: Int = 0
{
willSet{ "About to step to \(newValue)" }
didSet { totalSteps = totalSteps & 0xff }
}
}
var stepper = StepCounterShorterWithModify()
stepper.totalSteps = 345
stepper.totalSteps //: This reports totalSteps is now set to 89
//: ------------------------------------------------------------------------------------------------
//: Type Properties
//:
//: Until now, we've been working with Instance Properties and Instance Methods, which are
//: associated to an instance of a class, structure or enumeration. Each instance gets its own copy
//: of the property or method.
//:
//: Type properties are properties that are attached to the class, structure or enumeration's type
//: itself and not any specific instance. All instances of a type will share the same Type Property.
//:
//: These are similar to 'static' properties in C-like languages.
//:
//: For Value types (structs, enums) we use the 'static' keyword. For Class types with the 'class'
//: keyword.
//:
//: Type properties can be in the form of stored properties or computed properties. As with normal
//: stored or computed properties, all the same rules apply except that stored type properties must
//: always have a default value. This exception is necessary because the initializer (which we'll
//: learn about later) is associated to a specific instance and as such, cannot be reliable for
//: initializing type properties.
//:
//: Here is a class with a couple of type properties
struct SomeStructure
{
static var storedTypeProperty = "some value"
//: Here's a read-only computed type property using the short-hand read-only syntax
static var computedTypeProperty: Int { return 4 }
}
//: Similarly, here's an enumeration with a couple of type properties
enum SomeEnum
{
static let storedTypeProperty = "some value"
static var computedTypeProperty: Int { return 4 }
}
//: Classes are a little different in that they cannot contain stored type properties, but may
//: only contain computed type properties
class SomeClass
{
//: The following line won't compile because classes aren't allowed stored type properties
//:
//: class var storedTypeProperty = "some value"
//: This is read-only, but you can also do read/write
class var computedTypeProperty: Int { return 4 }
}
//: [Next](@next)
| apache-2.0 | 8638223b7d954d44327d83c4f35227ec | 34.287582 | 100 | 0.65151 | 4.42541 | false | false | false | false |
segej87/koramap | iPhone/EcoMapper/EcoMapper/UserVars.swift | 2 | 8640 | //
// UserVars.swift
// EcoMapper
//
// Created by Jon on 6/30/16.
// Copyright © 2016 Sege Industries. All rights reserved.
//
import Foundation
import UIKit
struct UserVars {
/*
The user ID of the current user, which sets record and media save paths
*/
static var UUID: String? {
didSet {
if let uuid = UUID {
UserVarsURL = DocumentsDirectory.appendingPathComponent("UserVars-\(uuid)")
RecordsURL = DocumentsDirectory.appendingPathComponent("Records-\(uuid)")
MediasURL = DocumentsDirectory.appendingPathComponent("Media-\(uuid)")
} else {
UserVarsURL = nil
RecordsURL = nil
MediasURL = nil
}
}
}
/*
The username of the current user
*/
static var UName: String?
/*
Filepath to save these user variables
*/
static var UserVarsURL: URL?
/*
Filepath to save records
*/
static var RecordsURL: URL?
/*
Filepath to save medias
*/
static var MediasURL: URL?
/*
The documents directory for the application
*/
static let DocumentsDirectory = FileManager()
.urls(for: .documentDirectory, in: .userDomainMask).first!
/*
Filepath to save photos
*/
static let PhotosURL = DocumentsDirectory.appendingPathComponent("Photos", isDirectory: true)
/*
An array of access levels, with the built-in public and private options
*/
static var AccessLevels = ["Public", "Private"]
/*
New key-value pairs object for tags
*/
static var Tags = [String:[AnyObject]]()
/*
New key-value pairs object for species
*/
static var Species = [String:[AnyObject]]()
/*
New key-value pairs object for Units
*/
static var Units = [String:[AnyObject]]()
/*
Defaults
*/
static var AccessDefaults = [String]()
static var TagsDefaults = [String]()
static var SpecDefault: String?
static var UnitsDefault: String?
/*
Location settings
*/
// static let maxUpdateTime = 1
// static let minGPSAccuracy = 50 as Double
// static let minGPSStability = 50 as Double
/*
Static string server URLs
*/
// URL of the authorization script
static let authScript = "http://ecocollector.azurewebsites.net/get_login.php"
//URL of the list-getting script
static let listScript = "http://ecocollector.azurewebsites.net/get_lists.php"
// URL to PHP script for uploading new records via POST.
static let recordAddScript = "http://ecocollector.azurewebsites.net/add_records.php"
// URL to blob storage Account.
static let blobRootURLString = "https://ecomapper.blob.core.windows.net/"
// MARK: General functions
static func saveLogin(loginInfo: LoginInfo) {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(loginInfo, toFile: LoginInfo.ArchiveURL.path)
if !isSuccessfulSave {
NSLog("Failed to save login info...")
}
}
static func meshUserVars(array: [String:AnyObject]) {
// Initialize an array of all keys to read from the server response
let keys = ["institutions","tags","species","units"]
// Read the arrays corresponding to the keys, and write to user variables
for k in keys {
let kArray = array[k] as! [String]
if !(kArray.count == 1 && kArray[0].contains("Warning:")) {
for i in kArray {
switch k {
case "institutions":
if !AccessLevels.contains(i) {
AccessLevels.append(i)
}
case "tags":
if !Tags.keys.contains(i) || (Tags.keys.contains(i) && Tags[i]![0] as! String == "Local") {
Tags[i] = ["Server" as AnyObject,0 as AnyObject]
}
case "species":
if !Species.keys.contains(i) || (Species.keys.contains(i) && Species[i]![0] as! String == "Local") {
Species[i] = ["Server" as AnyObject,0 as AnyObject]
}
case "units":
if !Units.keys.contains(i) || (Units.keys.contains(i) && Units[i]![0] as! String == "Local") {
Units[i] = ["Server" as AnyObject,0 as AnyObject]
}
default:
print("Login list retrieval error: unexpected key")
}
}
//TODO: deal with any items that are no longer on the server.
}
}
}
static func saveUserVars() {
let userVars = UserVarsSaveFile(userName: UName, accessLevels: AccessLevels, tags: Tags, species: Species, units: Units, accessDefaults: AccessDefaults, tagDefaults: TagsDefaults, speciesDefault: SpecDefault, unitsDefault: UnitsDefault)
NSLog("Attempting to save user variables to \(UserVarsURL!.path)")
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(userVars, toFile: UserVarsURL!.path)
if !isSuccessfulSave {
NSLog("Failed to save user variables...")
}
}
static func loadUserVars(uuid: String) -> Bool {
if let path = UserVarsURL?.path {
if let loadedUserVars = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? UserVarsSaveFile {
NSLog("Loading user variables")
UName = loadedUserVars.userName
AccessLevels = loadedUserVars.accessLevels!
Species = loadedUserVars.species!
Tags = loadedUserVars.tags!
Units = loadedUserVars.units!
AccessDefaults = loadedUserVars.accessDefaults
TagsDefaults = loadedUserVars.tagDefaults
SpecDefault = loadedUserVars.speciesDefault
UnitsDefault = loadedUserVars.unitsDefault
return true;
}
}
return false;
}
static func clearUserVars() {
// Clear all of the user variables
UUID = nil
UName = nil
AccessLevels = ["Public", "Private"]
Tags = [String:[AnyObject]]()
Species = [String:[AnyObject]]()
Units = [String:[AnyObject]]()
AccessDefaults = [String]()
TagsDefaults = [String]()
SpecDefault = nil
UnitsDefault = nil
}
static func handleDeletedRecord(record: Record) {
// Modify the UserVar lists associated with the record
let prevArray = record.props["tags"] as? [String]
for p in prevArray! {
if var pTag = UserVars.Tags[p] {
if pTag[0] as! String == "Local" {
pTag[1] = ((pTag[1] as! Int - 1) as AnyObject)
if pTag[1] as! Int == 0 {
UserVars.Tags.removeValue(forKey: p)
} else {
UserVars.Tags[p] = pTag
}
}
}
}
if record.props["datatype"] as! String == "meas" {
let specArray = record.props["species"]?.components(separatedBy: ", ")
for s in specArray! {
if var sTag = UserVars.Species[s] {
if sTag[0] as! String == "Local" {
sTag[1] = ((sTag[1] as! Int - 1) as AnyObject)
if sTag[1] as! Int == 0 {
UserVars.Species.removeValue(forKey: s)
} else {
UserVars.Species[s] = sTag
}
}
}
}
let unitArray = record.props["units"]?.components(separatedBy: ", ")
for u in unitArray! {
if var uTag = UserVars.Units[u] {
if uTag[0] as! String == "Local" {
uTag[1] = ((uTag[1] as! Int - 1) as AnyObject)
if uTag[1] as! Int == 0 {
UserVars.Units.removeValue(forKey: u)
} else {
UserVars.Units[u] = uTag
}
}
}
}
}
}
}
| gpl-3.0 | 280a2a72c1692274dfafdb15fa949297 | 33.146245 | 244 | 0.517537 | 4.75978 | false | false | false | false |
CleanCocoa/FatSidebar | FatSidebar/DragViewContainer.swift | 1 | 6663 | // Copyright © 2017 Christian Tietze. All rights reserved. Distributed under the MIT License.
import Cocoa
protocol DragViewContainer {
var draggingZOffset: NSSize { get }
func reorder(subview: NSView, event: NSEvent)
func didDrag(view: NSView, from: Int, to: Int)
}
private func fillHorizontal(_ subview: NSView) -> [NSLayoutConstraint] {
return NSLayoutConstraint.constraints(
withVisualFormat: "H:|[subview]|",
options: [],
metrics: nil,
views: ["subview": subview])
}
extension DragViewContainer where Self: NSView {
var draggingZOffset: NSSize { return NSSize(width: 0, height: 2) }
func reorder(subview: NSView, event: NSEvent) {
guard let windowContentView = window?.contentView else { preconditionFailure("Expected window with contentView") }
let subviewFrame = convert(subview.frame, to: nil)
let yPosition = subviewFrame.origin.y
let initialY = event.locationInWindow.y
let draggingView = subview.draggingView
draggingView.frame = subviewFrame
windowContentView.addSubview(draggingView)
let yPositionConstraint = NSLayoutConstraint(
item: window!.contentView!,
attribute: .bottom,
relatedBy: .equal,
toItem: draggingView,
attribute: .bottom,
multiplier: 1,
constant: yPosition)
let xPositionConstraint = NSLayoutConstraint(
item: draggingView,
attribute: .leading,
relatedBy: .equal,
toItem: windowContentView,
attribute: .leading,
multiplier: 1,
constant: subviewFrame.origin.x)
let draggingViewPositionConstraints = [
yPositionConstraint,
xPositionConstraint
]
windowContentView.addConstraints(draggingViewPositionConstraints)
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.2
context.allowsImplicitAnimation = true
xPositionConstraint.constant += draggingZOffset.width
yPositionConstraint.constant += draggingZOffset.height
draggingView.layoutSubtreeIfNeeded()
draggingView.layer?.shadowRadius = 3
draggingView.layer?.shadowOffset = NSSize(width: 0, height: -2)
draggingView.alphaValue = 0.8
}, completionHandler: nil)
subview.isHidden = true
var previousY = initialY
let draggedItemIndex = subviews.firstIndex(of: subview)!
var draggedPositionOffset = 0
window?.trackEvents(
matching: [.leftMouseUp, .leftMouseDragged],
timeout: Date.distantFuture.timeIntervalSinceNow,
mode: .eventTracking)
{ [unowned self] (dragEvent, stop) in
guard let dragEvent = dragEvent else { return }
guard dragEvent.type != .leftMouseUp else {
draggingView.layoutSubtreeIfNeeded()
let subviewFrame = self.convert(subview.frame, to: nil)
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.2
context.allowsImplicitAnimation = true
context.timingFunction = CAMediaTimingFunction(name: .easeOut)
yPositionConstraint.constant = subviewFrame.origin.y
xPositionConstraint.constant = subviewFrame.origin.x
draggingView.layoutSubtreeIfNeeded()
draggingView.layer?.shadowRadius = 0
draggingView.layer?.shadowOffset = NSSize(width: 0, height: 0)
draggingView.alphaValue = 1.0
}, completionHandler: {
draggingView.removeFromSuperview()
windowContentView.removeConstraints(draggingViewPositionConstraints)
subview.isHidden = false
})
stop.pointee = true
subview.mouseUp(with: dragEvent)
self.didDrag(
view: subview,
from: draggedItemIndex,
to: draggedItemIndex + draggedPositionOffset)
return
}
self.autoscroll(with: dragEvent)
let nextY = dragEvent.locationInWindow.y
let draggedY = nextY - initialY
yPositionConstraint.constant = yPosition + draggedY + self.draggingZOffset.height
let middle = NSMidY(self.convert(draggingView.frame, from: nil))
let top = NSMaxY(subview.frame)
let bottom = NSMinY(subview.frame)
let movingUp = nextY > previousY && (middle > top)
let movingDown = nextY < previousY && (middle < bottom)
func moveSubview(_ direction: DragDirection) {
self.subviews.move(subview, by: direction.offset)
self.layoutSubviews(self.subviews)
}
if movingUp && subview != self.subviews.first! {
moveSubview(.up)
draggedPositionOffset -= 1
}
if movingDown && subview != self.subviews.last! {
moveSubview(.down)
draggedPositionOffset += 1
}
previousY = nextY
}
}
func layoutSubviews(_ subviews: [NSView]) {
removeConstraints(self.constraints)
if subviews.isEmpty { return }
var prev: NSView?
for subview in subviews {
addConstraints(fillHorizontal(subview))
// Constrain first item to container top;
// Constrain all other items' top anchor to predecessor's bottom anchor.
addConstraint(
NSLayoutConstraint(
item: subview,
attribute: .top,
relatedBy: .equal,
toItem: prev != nil ? prev! : self,
attribute: prev != nil ? .bottom : .top,
multiplier: 1,
constant: 0)
)
prev = subview
}
// Constrain last item to container bottom
addConstraint(NSLayoutConstraint(
item: prev!,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1,
constant: 0)
)
}
}
enum DragDirection {
case up, down
var offset: Int {
switch self {
case .up: return -1
case .down: return 1
}
}
}
| mit | f3d28b1465637cc6305ae1f416696788 | 32.31 | 122 | 0.57175 | 5.433931 | false | false | false | false |
VBVMI/VerseByVerse-iOS | Pods/VimeoNetworking/VimeoNetworking/Sources/AccountStore.swift | 1 | 5019 | //
// AccountStore.swift
// VimeoNetworkingExample-iOS
//
// Created by Huebner, Rob on 3/24/16.
// Copyright © 2016 Vimeo. 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
/// `AccountStore` handles saving and loading authenticated accounts securely using the keychain
final class AccountStore
{
/// `AccountType` categorizes an account based on its level of access
enum AccountType
{
/// Client credentials accounts can access only public resources
case clientCredentials
/// User accounts have an authenticated user and can act on the user's behalf
case user
func keychainKey() -> String
{
switch self
{
case .clientCredentials:
return "ClientCredentialsAccountKey"
case .user:
return "UserAccountKey"
}
}
}
// MARK: -
private struct Constants
{
static let ErrorDomain = "AccountStoreErrorDomain"
}
// MARK: -
private let keychainStore: KeychainStore
// MARK: -
/**
Create a new account store
- parameter configuration: your application's configuration
- returns: an initialized `AccountStore`
*/
init(configuration: AppConfiguration)
{
self.keychainStore = KeychainStore(service: configuration.keychainService, accessGroup: configuration.keychainAccessGroup)
}
// MARK: -
/**
Save an account
- parameter account: the account to save
- parameter type: the type of the account
- throws: an error if the data could not be saved
*/
func save(_ account: VIMAccount, ofType type: AccountType) throws
{
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(account)
archiver.finishEncoding()
try self.keychainStore.set(data: data, forKey: type.keychainKey())
}
/**
Load an account
- parameter type: type of account requested
- throws: an error if data could not be loaded
- returns: an account of the specified type, if one was found
*/
func loadAccount(ofType type: AccountType) throws -> VIMAccount?
{
do
{
guard let data = try self.keychainStore.data(for: type.keychainKey())
else
{
return nil
}
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
var decodedAccount: VIMAccount? = nil
try ExceptionCatcher.doUnsafe
{
decodedAccount = unarchiver.decodeObject() as? VIMAccount
}
guard let account = decodedAccount
else
{
let description = "Received corrupted VIMAccount data from keychain"
let error = NSError(domain: Constants.ErrorDomain, code: LocalErrorCode.accountCorrupted.rawValue, userInfo: [NSLocalizedDescriptionKey: description])
throw error
}
if let userJSON = account.userJSON
{
try account.user = VIMObjectMapper.mapObject(responseDictionary: userJSON) as VIMUser
}
return account
}
catch let error
{
_ = try? self.removeAccount(ofType: type)
throw error
}
}
/**
Removes a saved account
- parameter type: type of account to remove
- throws: an error if the data exists but could not be removed
*/
func removeAccount(ofType type: AccountType) throws
{
try self.keychainStore.deleteData(for: type.keychainKey())
}
}
| mit | e6722c755e944ef621f9d6543db28423 | 29.975309 | 166 | 0.608011 | 5.227083 | false | false | false | false |
306244907/Weibo | JLSina/JLSina/Classes/Tools(工具)/Extensions/String+Extensions.swift | 1 | 1207 | //
// String+Extensions.swift
// 正则表达式
//
// Created by 盘赢 on 2017/12/6.
// Copyright © 2017年 盘赢. All rights reserved.
//
import Foundation
extension String {
//<a href=\"http://app.weibo.com/t/feed/4fw5aJ\" rel=\"nofollow\">秒拍网页版</a>
//从当前字符串中提取链接和文本
//Swift提供了'元组' , 同时返回多个值
//如果是OC ,可以返回字典/自定义对象/指针的指针
func JL_href() -> (link: String , text: String)? {
//0,匹配方案
let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>"
//1,创建正则表达式 , 并且匹配到第一项
guard let regx = try? NSRegularExpression(pattern: pattern, options: []) ,
let resule = regx.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.count)) else {
return nil
}
//2,获取结果
let link = (self as NSString).substring(with: resule.range(at: 1))
let text = (self as NSString).substring(with: resule.range(at: 2))
print(link + "----" + text)
return (link , text)
}
}
| mit | 5fae025879ba0973e714b017f76d9fba | 25.615385 | 119 | 0.525048 | 3.403279 | false | false | false | false |
huangboju/AsyncDisplay_Study | AsyncDisplay/Weibo/WebController.swift | 1 | 1196 | //
// WebController.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/5/22.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import WebKit
class WebController: UIViewController {
let url: URL
init(url: URL) {
self.url = url
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var webView: WKWebView = {
let webView = WKWebView(frame: self.view.frame)
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.showTitleView(text: "Loading")
view.addSubview(webView)
let request = URLRequest(url: url)
webView.load(request)
webView.navigationDelegate = self
}
}
extension WebController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
navigationItem.hideTitleView()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
navigationItem.hideTitleView()
}
}
| mit | 1afb4477a930d903fc7ef7028d2fde3a | 20.87037 | 99 | 0.626588 | 4.559846 | false | false | false | false |
weipin/jewzruxin | Playground/Files/Playground.playground/Pages/HTTP Intermediate.xcplaygroundpage/Contents.swift | 1 | 569 | //: [Previous](@previous)
import Foundation
import XCPlayground
import JewzruxinMac
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
/*:
### Formal methods
Using the formal methods is less convenient but more flexible, unleashing the full ability.
*/
/*:
1. GET content from the specified URL.
*/
let URL = NSURL(string: BaseURL + "/core/playground/hello/")!
let cycle = HTTPCycle(requestURL: URL)
cycle.start {(cycle, error) in
if error != nil {
print(error)
return
}
let text = cycle.response.text!
}
//: [Next](@next)
| mit | 37ca354940a9d58a002c75c66ffe9917 | 17.966667 | 91 | 0.6942 | 3.768212 | false | false | false | false |
ProjectDent/LinkLabel | Source/TouchGestureRecognizer.swift | 1 | 872 | //
// TouchDownGestureRecognizer.swift
// TwIM
//
// Created by Andrew Hart on 07/08/2015.
// Copyright (c) 2015 Project Dent. All rights reserved.
//
import UIKit
class TouchGestureRecognizer: UIGestureRecognizer {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
if self.state == UIGestureRecognizerState.possible {
self.state = UIGestureRecognizerState.began
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
self.state = UIGestureRecognizerState.changed
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
self.state = UIGestureRecognizerState.ended
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
self.state = UIGestureRecognizerState.cancelled
}
}
| mit | 22c5476b7726e82db9d1ae1c2052208e | 29.068966 | 82 | 0.683486 | 4.791209 | false | false | false | false |
meika-tea-room/SDC-DIOS | Studio Inventory/Controller/LoginViewController.swift | 1 | 2551 | //
// LoginViewController.swift
// Studio Inventory
//
// Created by William PHETSINORATH on 20/04/2017.
// Copyright © 2017 ETNA. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var emailErrorMessageLabel: UILabel!
@IBOutlet weak var passwordErrorMessageLabel: UILabel!
@IBAction func connectButton(_ sender: Any) {
var error = [String: String]()
if emailTextField.text?.isEmpty == true {
error["email"] = "Veuillez entrer un email"
}
if passwordTextField.text?.isEmpty == true {
error["password"] = "Veuillez entrer un mot de passe"
}
if !error.isEmpty {
emailErrorMessageLabel.alpha = 1
emailErrorMessageLabel.text = error["email"]
passwordErrorMessageLabel.alpha = 1
passwordErrorMessageLabel.text = error["password"]
return
}
// prepare json data
let data: [String: String] = [
"email":emailTextField.text!,
"password":passwordTextField.text!,
]
let json: [String: Any] = [
"authorization" : "Pour survivre à la guerre, il faut devenir la guerre.",
"data": data
]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
var req = URLRequest(url: URL(string: "http://172.16.1.175:25125/account/login")!)
req.httpMethod = "POST"
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
// insert json data to the request
req.httpBody = jsonData
let task = URLSession.shared.dataTask(with: req) { data, res, err in
guard let data = data, err == nil else {
print(err?.localizedDescription ?? "No data into the respond")
return
}
let resJson = try? JSONSerialization.jsonObject(with: data, options: [])
if let resJson = resJson as? [String: Any] {
print(resJson)
}
}
task.resume()
performSegue(withIdentifier: "Logged", sender: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | d719d363315b2019f1ba9efea8859fab | 28.988235 | 91 | 0.597097 | 4.601083 | false | false | false | false |
renshu16/DouyuSwift | DouyuSwift/DouyuSwift/Classes/Tools/NetworkTools.swift | 1 | 809 | //
// NetworkTools.swift
// DouyuSwift
//
// Created by ToothBond on 16/11/15.
// Copyright © 2016年 ToothBond. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
class NetworkTools {
class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) {
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else {
print(response.result.error)
return
}
finishedCallback(result)
}
}
}
| mit | 7ce5dbae243975d04878094647117fec | 25 | 158 | 0.595533 | 4.477778 | false | false | false | false |
kaushaldeo/Olympics | Olympics/Views/KDWinnerViewCell.swift | 1 | 2412 | //
// KDWinnerViewCell.swift
// Olympics
//
// Created by Kaushal Deo on 8/6/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
class KDWinnerViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var medalLabel: UILabel!
@IBOutlet weak var sportsLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.medalLabel.layer.borderWidth = 1.0
self.medalLabel.textAlignment = .Center
self.medalLabel.layer.masksToBounds = true
self.medalLabel.layer.cornerRadius = 15.0
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
var bezierPath = UIBezierPath(rect: rect)
UIColor.cellBackgroundColor().setFill()
bezierPath.fill()
bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: 16, y: CGRectGetHeight(rect)))
bezierPath.addLineToPoint(CGPoint(x: CGRectGetWidth(rect), y: CGRectGetHeight(rect)))
bezierPath.lineWidth = 0.25
UIColor.sepratorColor().setStroke()
bezierPath.strokeWithBlendMode(.Exclusion, alpha: 1.0)
}
func setWinner(winner: Winner) {
self.nameLabel.text = winner.name()
self.sportsLabel.text = winner.sports()
var color = UIColor.clearColor()
var string = ""
if let medal = winner.medal {
switch medal.lowercaseString {
case "1":
color = UIColor(red: 218, green: 181, blue: 10)
string = "G"
case "2":
color = UIColor.silverColor()
string = "S"
default:
color = UIColor(red: 232, green: 147, blue: 114)
string = "B"
}
}
self.medalLabel.layer.borderColor = color.CGColor
self.medalLabel.text = string
self.medalLabel.textColor = color
}
}
| apache-2.0 | 1aae2a6308a263d084d6b0928c648e7c | 28.765432 | 93 | 0.583161 | 4.699805 | false | false | false | false |
Tommy1990/swiftWibo | SwiftWibo/SwiftWibo/Classes/View/Compose/View/EPMComposePictureView.swift | 1 | 4044 | //
// EPMComposePictureView.swift
// SwiftWibo
//
// Created by 马继鵬 on 17/3/29.
// Copyright © 2017年 7TH. All rights reserved.
//
import UIKit
fileprivate let sizeMargin:CGFloat = 5.0
fileprivate let itemWH = (screenWidth - 2*margine - 2 * sizeMargin)/3
class EPMComposePictureView: UICollectionView {
var imgList:[UIImage] = [UIImage]()
var closure:(()->())?
func addImg(img:UIImage){
imgList.append(img)
reloadData()
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: itemWH, height: itemWH)
flowLayout.minimumLineSpacing = sizeMargin
flowLayout.minimumInteritemSpacing = sizeMargin
super.init(frame: frame, collectionViewLayout: flowLayout)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
backgroundColor = UIColor.lightGray
register(EPMComposeCollectionView.self, forCellWithReuseIdentifier: "cell")
dataSource = self
delegate = self
}
}
extension EPMComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let s = imgList.count
if s == 0 || s == 9{
return s
}else{
return s+1
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! EPMComposeCollectionView
if indexPath.item == imgList.count{
cell.img = nil
}else{
cell.img = imgList[indexPath.item]
cell.closure = {[weak self] in
self?.imgList.remove(at: indexPath.item)
if self?.imgList.count == 0{
self?.isHidden = true
}
self?.reloadData()
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
if indexPath.item == imgList.count{
closure!()
}
}
}
class EPMComposeCollectionView: UICollectionViewCell {
var closure:(()->())?
var img:UIImage?{
didSet{
if img == nil{
imgView.image = UIImage(named: "compose_pic_add")
imgView.highlightedImage = UIImage(named:"compose_pic_add_highlighted")
cancelBtn.isHidden = true
}else{
imgView.image = img
imgView.highlightedImage = nil
cancelBtn.isHidden = false
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI()
{
contentView.addSubview(imgView)
contentView.addSubview(cancelBtn)
imgView.snp.makeConstraints { (make) in
make.edges.equalTo(self.contentView)
}
cancelBtn.snp.makeConstraints { (make) in
make.top.trailing.equalTo(imgView)
}
}
private lazy var imgView:UIImageView = UIImageView()
fileprivate lazy var cancelBtn: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named:"compose_photo_close"), for: .normal)
btn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
btn.isHidden = false
btn.sizeToFit()
return btn
}()
}
extension EPMComposeCollectionView{
@objc fileprivate func cancelBtnClick(){
closure?()
}
}
| mit | abc4d8279f95d6718a202c5015be8d97 | 30.523438 | 127 | 0.608426 | 4.95092 | false | false | false | false |
google/JacquardSDKiOS | Example/JacquardSDK/GestureView/GestureBlurEffectView.swift | 1 | 2486 | // Copyright 2021 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 UIKit
final class GestureBlurEffectView: UIView {
private var blurEffectView: UIVisualEffectView?
override init(frame: CGRect) {
let blurEffect = UIBlurEffect(style: .extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.alpha = 0.8
blurEffectView.frame = frame
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.blurEffectView = blurEffectView
super.init(frame: frame)
addSubview(blurEffectView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configureUI(image: UIImage, gestureName: String) {
guard let blurEffectView = blurEffectView else { return }
let imageView = UIImageView()
imageView.image = image
imageView.frame = CGRect(x: 0, y: 0, width: 120, height: 120)
imageView.center = blurEffectView.contentView.center
blurEffectView.contentView.addSubview(imageView)
let gestureLabel = UILabel()
gestureLabel.text = gestureName
gestureLabel.frame = CGRect(
x: 0, y: blurEffectView.frame.size.height / 2 + 70,
width: blurEffectView.frame.size.width,
height: 40)
gestureLabel.textAlignment = .center
blurEffectView.contentView.addSubview(gestureLabel)
gestureLabel.layer.zPosition = 1
self.bringSubviewToFront(gestureLabel)
}
}
extension UIView {
func showBlurView(image: UIImage, gestureName: String) {
removeBlurView()
let blurView = GestureBlurEffectView(frame: frame)
blurView.configureUI(image: image, gestureName: gestureName)
self.addSubview(blurView)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.removeBlurView()
}
}
private func removeBlurView() {
if let blurView = subviews.first(where: { $0 is GestureBlurEffectView }) {
blurView.removeFromSuperview()
}
}
}
| apache-2.0 | 62bae940a8f285200870ab403e5158a6 | 32.146667 | 78 | 0.727273 | 4.439286 | false | false | false | false |
parkera/swift-corelibs-foundation | Foundation/NumberFormatter.swift | 1 | 31595 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016, 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
extension NumberFormatter {
public enum Style : UInt {
case none = 0
case decimal = 1
case currency = 2
case percent = 3
case scientific = 4
case spellOut = 5
case ordinal = 6
case currencyISOCode = 8 // 7 is not used
case currencyPlural = 9
case currencyAccounting = 10
}
public enum PadPosition : UInt {
case beforePrefix
case afterPrefix
case beforeSuffix
case afterSuffix
}
public enum RoundingMode : UInt {
case ceiling
case floor
case down
case up
case halfEven
case halfDown
case halfUp
}
}
open class NumberFormatter : Formatter {
typealias CFType = CFNumberFormatter
private var _currentCfFormatter: CFType?
private var _cfFormatter: CFType {
if let obj = _currentCfFormatter {
return obj
} else {
#if os(macOS) || os(iOS)
let numberStyle = CFNumberFormatterStyle(rawValue: CFIndex(self.numberStyle.rawValue))!
#else
let numberStyle = CFNumberFormatterStyle(self.numberStyle.rawValue)
#endif
let obj = CFNumberFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, numberStyle)!
_setFormatterAttributes(obj)
if _positiveFormat != nil || _negativeFormat != nil {
var format = _positiveFormat ?? "#"
if let negative = _negativeFormat {
format.append(";")
format.append(negative)
}
CFNumberFormatterSetFormat(obj, format._cfObject)
}
_currentCfFormatter = obj
return obj
}
}
// this is for NSUnitFormatter
open var formattingContext: Context = .unknown // default is NSFormattingContextUnknown
// Report the used range of the string and an NSError, in addition to the usual stuff from Formatter
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func objectValue(_ string: String, range: inout NSRange) throws -> Any? { NSUnimplemented() }
open override func string(for obj: Any) -> String? {
//we need to allow Swift's numeric types here - Int, Double et al.
guard let number = __SwiftValue.store(obj) as? NSNumber else { return nil }
return string(from: number)
}
// Even though NumberFormatter responds to the usual Formatter methods,
// here are some convenience methods which are a little more obvious.
open func string(from number: NSNumber) -> String? {
return CFNumberFormatterCreateStringWithNumber(kCFAllocatorSystemDefault, _cfFormatter, number._cfObject)._swiftObject
}
open func number(from string: String) -> NSNumber? {
var range = CFRange(location: 0, length: string.length)
let number = withUnsafeMutablePointer(to: &range) { (rangePointer: UnsafeMutablePointer<CFRange>) -> NSNumber? in
#if os(macOS) || os(iOS)
let parseOption = allowsFloats ? 0 : CFNumberFormatterOptionFlags.parseIntegersOnly.rawValue
#else
let parseOption = allowsFloats ? 0 : CFOptionFlags(kCFNumberFormatterParseIntegersOnly)
#endif
let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, parseOption)
return result?._nsObject
}
return number
}
open class func localizedString(from num: NSNumber, number nstyle: Style) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = nstyle
return numberFormatter.string(for: num)!
}
private func _reset() {
_currentCfFormatter = nil
}
private func _setFormatterAttributes(_ formatter: CFNumberFormatter) {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyCode, value: _currencyCode?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterDecimalSeparator, value: _decimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyDecimalSeparator, value: _currencyDecimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterAlwaysShowDecimalSeparator, value: _alwaysShowsDecimalSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSeparator, value: _groupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseGroupingSeparator, value: _usesGroupingSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPercentSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterZeroSymbol, value: _zeroSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNaNSymbol, value: _notANumberSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInfinitySymbol, value: _positiveInfinitySymbol._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinusSign, value: _minusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPlusSign, value: _plusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencySymbol, value: _currencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterExponentSymbol, value: _exponentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinIntegerDigits, value: minimumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxIntegerDigits, value: _maximumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinFractionDigits, value: _minimumFractionDigits._bridgeToObjectiveC()._cfObject)
if _minimumFractionDigits <= 0 {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxFractionDigits, value: _maximumFractionDigits._bridgeToObjectiveC()._cfObject)
}
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSize, value: _groupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterSecondaryGroupingSize, value: _secondaryGroupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingMode, value: _roundingMode.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingIncrement, value: _roundingIncrement?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterFormatWidth, value: _formatWidth._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingCharacter, value: _paddingCharacter?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingPosition, value: _paddingPosition.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMultiplier, value: _multiplier?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositivePrefix, value: _positivePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositiveSuffix, value: _positiveSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativePrefix, value: _negativePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativeSuffix, value: _negativeSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPerMillSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInternationalCurrencySymbol, value: _internationalCurrencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyGroupingSeparator, value: _currencyGroupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterIsLenient, value: _lenient._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseSignificantDigits, value: _usesSignificantDigits._cfObject)
if _usesSignificantDigits {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinSignificantDigits, value: _minimumSignificantDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxSignificantDigits, value: _maximumSignificantDigits._bridgeToObjectiveC()._cfObject)
}
}
private func _setFormatterAttribute(_ formatter: CFNumberFormatter, attributeName: CFString, value: AnyObject?) {
if let value = value {
CFNumberFormatterSetProperty(formatter, attributeName, value)
}
}
private func _getFormatterAttribute(_ formatter: CFNumberFormatter, attributeName: CFString) -> String? {
return CFNumberFormatterCopyProperty(formatter, attributeName) as? String
}
// Attributes of a NumberFormatter
private var _numberStyle: Style = .none
open var numberStyle: Style {
get {
return _numberStyle
}
set {
switch newValue {
case .none, .ordinal, .spellOut:
_usesSignificantDigits = false
case .currency, .currencyISOCode, .currencyAccounting:
_usesSignificantDigits = false
_usesGroupingSeparator = true
if _minimumIntegerDigits == nil {
_minimumIntegerDigits = 1
}
if _groupingSize == 0 {
_groupingSize = 3
}
_minimumFractionDigits = 2
case .currencyPlural:
_usesSignificantDigits = false
_usesGroupingSeparator = true
if _minimumIntegerDigits == nil {
_minimumIntegerDigits = 0
}
_minimumFractionDigits = 2
case .decimal:
_usesGroupingSeparator = true
_maximumFractionDigits = 3
if _minimumIntegerDigits == nil {
_minimumIntegerDigits = 1
}
if _groupingSize == 0 {
_groupingSize = 3
}
case .percent:
_usesSignificantDigits = false
_usesGroupingSeparator = true
if _minimumIntegerDigits == nil {
_minimumIntegerDigits = 1
}
if _groupingSize == 0 {
_groupingSize = 3
}
_minimumFractionDigits = 0
_maximumFractionDigits = 0
case .scientific:
_usesSignificantDigits = false
_usesGroupingSeparator = false
if _minimumIntegerDigits == nil {
_minimumIntegerDigits = 0
}
}
_reset()
_numberStyle = newValue
}
}
private var _locale: Locale = Locale.current
/*@NSCopying*/ open var locale: Locale! {
get {
return _locale
}
set {
_reset()
_locale = newValue
}
}
private var _generatesDecimalNumbers: Bool = false
open var generatesDecimalNumbers: Bool {
get {
return _generatesDecimalNumbers
}
set {
_reset()
_generatesDecimalNumbers = newValue
}
}
private var _textAttributesForNegativeValues: [String : Any]?
open var textAttributesForNegativeValues: [String : Any]? {
get {
return _textAttributesForNegativeValues
}
set {
_reset()
_textAttributesForNegativeValues = newValue
}
}
private var _textAttributesForPositiveValues: [String : Any]?
open var textAttributesForPositiveValues: [String : Any]? {
get {
return _textAttributesForPositiveValues
}
set {
_reset()
_textAttributesForPositiveValues = newValue
}
}
private var _allowsFloats: Bool = true
open var allowsFloats: Bool {
get {
return _allowsFloats
}
set {
_reset()
_allowsFloats = newValue
}
}
private var _decimalSeparator: String!
open var decimalSeparator: String! {
get {
return _decimalSeparator ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterDecimalSeparator)
}
set {
_reset()
_decimalSeparator = newValue
}
}
private var _alwaysShowsDecimalSeparator: Bool = false
open var alwaysShowsDecimalSeparator: Bool {
get {
return _alwaysShowsDecimalSeparator
}
set {
_reset()
_alwaysShowsDecimalSeparator = newValue
}
}
private var _currencyDecimalSeparator: String!
open var currencyDecimalSeparator: String! {
get {
return _currencyDecimalSeparator ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterCurrencyDecimalSeparator)
}
set {
_reset()
_currencyDecimalSeparator = newValue
}
}
private var _usesGroupingSeparator: Bool = false
open var usesGroupingSeparator: Bool {
get {
return _usesGroupingSeparator
}
set {
_reset()
_usesGroupingSeparator = newValue
}
}
private var _groupingSeparator: String!
open var groupingSeparator: String! {
get {
return _groupingSeparator ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterGroupingSeparator)
}
set {
_reset()
_groupingSeparator = newValue
}
}
private var _zeroSymbol: String?
open var zeroSymbol: String? {
get {
return _zeroSymbol
}
set {
_reset()
_zeroSymbol = newValue
}
}
private var _textAttributesForZero: [String : Any]?
open var textAttributesForZero: [String : Any]? {
get {
return _textAttributesForZero
}
set {
_reset()
_textAttributesForZero = newValue
}
}
private var _nilSymbol: String = ""
open var nilSymbol: String {
get {
return _nilSymbol
}
set {
_reset()
_nilSymbol = newValue
}
}
private var _textAttributesForNil: [String : Any]?
open var textAttributesForNil: [String : Any]? {
get {
return _textAttributesForNil
}
set {
_reset()
_textAttributesForNil = newValue
}
}
private var _notANumberSymbol: String!
open var notANumberSymbol: String! {
get {
return _notANumberSymbol ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterNaNSymbol)
}
set {
_reset()
_notANumberSymbol = newValue
}
}
private var _textAttributesForNotANumber: [String : Any]?
open var textAttributesForNotANumber: [String : Any]? {
get {
return _textAttributesForNotANumber
}
set {
_reset()
_textAttributesForNotANumber = newValue
}
}
private var _positiveInfinitySymbol: String = "+∞"
open var positiveInfinitySymbol: String {
get {
return _positiveInfinitySymbol
}
set {
_reset()
_positiveInfinitySymbol = newValue
}
}
private var _textAttributesForPositiveInfinity: [String : Any]?
open var textAttributesForPositiveInfinity: [String : Any]? {
get {
return _textAttributesForPositiveInfinity
}
set {
_reset()
_textAttributesForPositiveInfinity = newValue
}
}
private var _negativeInfinitySymbol: String = "-∞"
open var negativeInfinitySymbol: String {
get {
return _negativeInfinitySymbol
}
set {
_reset()
_negativeInfinitySymbol = newValue
}
}
private var _textAttributesForNegativeInfinity: [String : Any]?
open var textAttributesForNegativeInfinity: [String : Any]? {
get {
return _textAttributesForNegativeInfinity
}
set {
_reset()
_textAttributesForNegativeInfinity = newValue
}
}
private var _positivePrefix: String!
open var positivePrefix: String! {
get {
return _positivePrefix ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterPositivePrefix)
}
set {
_reset()
_positivePrefix = newValue
}
}
private var _positiveSuffix: String!
open var positiveSuffix: String! {
get {
return _positiveSuffix ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterPositiveSuffix)
}
set {
_reset()
_positiveSuffix = newValue
}
}
private var _negativePrefix: String!
open var negativePrefix: String! {
get {
return _negativePrefix ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterNegativePrefix)
}
set {
_reset()
_negativePrefix = newValue
}
}
private var _negativeSuffix: String!
open var negativeSuffix: String! {
get {
return _negativeSuffix ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterNegativeSuffix)
}
set {
_reset()
_negativeSuffix = newValue
}
}
private var _currencyCode: String!
open var currencyCode: String! {
get {
return _currencyCode ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterCurrencyCode)
}
set {
_reset()
_currencyCode = newValue
}
}
private var _currencySymbol: String!
open var currencySymbol: String! {
get {
return _currencySymbol ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterCurrencySymbol)
}
set {
_reset()
_currencySymbol = newValue
}
}
private var _internationalCurrencySymbol: String!
open var internationalCurrencySymbol: String! {
get {
return _internationalCurrencySymbol ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterInternationalCurrencySymbol)
}
set {
_reset()
_internationalCurrencySymbol = newValue
}
}
private var _percentSymbol: String!
open var percentSymbol: String! {
get {
return _percentSymbol ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterPercentSymbol) ?? "%"
}
set {
_reset()
_percentSymbol = newValue
}
}
private var _perMillSymbol: String!
open var perMillSymbol: String! {
get {
return _perMillSymbol ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterPerMillSymbol)
}
set {
_reset()
_perMillSymbol = newValue
}
}
private var _minusSign: String!
open var minusSign: String! {
get {
return _minusSign ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterMinusSign)
}
set {
_reset()
_minusSign = newValue
}
}
private var _plusSign: String!
open var plusSign: String! {
get {
return _plusSign ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterPlusSign)
}
set {
_reset()
_plusSign = newValue
}
}
private var _exponentSymbol: String!
open var exponentSymbol: String! {
get {
return _exponentSymbol ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterExponentSymbol)
}
set {
_reset()
_exponentSymbol = newValue
}
}
private var _groupingSize: Int = 0
open var groupingSize: Int {
get {
return _groupingSize
}
set {
_reset()
_groupingSize = newValue
}
}
private var _secondaryGroupingSize: Int = 0
open var secondaryGroupingSize: Int {
get {
return _secondaryGroupingSize
}
set {
_reset()
_secondaryGroupingSize = newValue
}
}
private var _multiplier: NSNumber?
/*@NSCopying*/ open var multiplier: NSNumber? {
get {
return _multiplier
}
set {
_reset()
_multiplier = newValue
}
}
private var _formatWidth: Int = 0
open var formatWidth: Int {
get {
return _formatWidth
}
set {
_reset()
_formatWidth = newValue
}
}
private var _paddingCharacter: String!
open var paddingCharacter: String! {
get {
return _paddingCharacter ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterPaddingCharacter)
}
set {
_reset()
_paddingCharacter = newValue
}
}
private var _paddingPosition: PadPosition = .beforePrefix
open var paddingPosition: PadPosition {
get {
return _paddingPosition
}
set {
_reset()
_paddingPosition = newValue
}
}
private var _roundingMode: RoundingMode = .halfEven
open var roundingMode: RoundingMode {
get {
return _roundingMode
}
set {
_reset()
_roundingMode = newValue
}
}
private var _roundingIncrement: NSNumber! = 0
/*@NSCopying*/ open var roundingIncrement: NSNumber! {
get {
return _roundingIncrement
}
set {
_reset()
_roundingIncrement = newValue
}
}
// Use an optional for _minimumIntegerDigits to track if the value is
// set BEFORE the .numberStyle is changed. This allows preserving a setting
// of 0.
private var _minimumIntegerDigits: Int?
open var minimumIntegerDigits: Int {
get {
return _minimumIntegerDigits ?? 0
}
set {
_reset()
_minimumIntegerDigits = newValue
}
}
private var _maximumIntegerDigits: Int = 42
open var maximumIntegerDigits: Int {
get {
return _maximumIntegerDigits
}
set {
_reset()
_maximumIntegerDigits = newValue
}
}
private var _minimumFractionDigits: Int = 0
open var minimumFractionDigits: Int {
get {
return _minimumFractionDigits
}
set {
_reset()
_minimumFractionDigits = newValue
}
}
private var _maximumFractionDigits: Int = 0
open var maximumFractionDigits: Int {
get {
return _maximumFractionDigits
}
set {
_reset()
_maximumFractionDigits = newValue
}
}
private var _minimum: NSNumber?
/*@NSCopying*/ open var minimum: NSNumber? {
get {
return _minimum
}
set {
_reset()
_minimum = newValue
}
}
private var _maximum: NSNumber?
/*@NSCopying*/ open var maximum: NSNumber? {
get {
return _maximum
}
set {
_reset()
_maximum = newValue
}
}
private var _currencyGroupingSeparator: String!
open var currencyGroupingSeparator: String! {
get {
return _currencyGroupingSeparator ?? _getFormatterAttribute(_cfFormatter, attributeName: kCFNumberFormatterCurrencyGroupingSeparator)
}
set {
_reset()
_currencyGroupingSeparator = newValue
}
}
private var _lenient: Bool = false
open var isLenient: Bool {
get {
return _lenient
}
set {
_reset()
_lenient = newValue
}
}
private var _usesSignificantDigits: Bool = false
open var usesSignificantDigits: Bool {
get {
return _usesSignificantDigits
}
set {
_reset()
_usesSignificantDigits = newValue
}
}
private var _minimumSignificantDigits: Int = 1
open var minimumSignificantDigits: Int {
get {
return _minimumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_minimumSignificantDigits = newValue
}
}
private var _maximumSignificantDigits: Int = 6
open var maximumSignificantDigits: Int {
get {
return _maximumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_maximumSignificantDigits = newValue
}
}
private var _partialStringValidationEnabled: Bool = false
open var isPartialStringValidationEnabled: Bool {
get {
return _partialStringValidationEnabled
}
set {
_reset()
_partialStringValidationEnabled = newValue
}
}
private var _hasThousandSeparators: Bool = false
open var hasThousandSeparators: Bool {
get {
return _hasThousandSeparators
}
set {
_reset()
_hasThousandSeparators = newValue
}
}
private var _thousandSeparator: String!
open var thousandSeparator: String! {
get {
return _thousandSeparator
}
set {
_reset()
_thousandSeparator = newValue
}
}
private var _localizesFormat: Bool = true
open var localizesFormat: Bool {
get {
return _localizesFormat
}
set {
_reset()
_localizesFormat = newValue
}
}
private func getFormatterComponents() -> (String, String) {
let format = CFNumberFormatterGetFormat(_cfFormatter)._swiftObject
let components = format.components(separatedBy: ";")
let positive = _positiveFormat ?? components.first ?? "#"
let negative = _negativeFormat ?? components.last ?? "#"
return (positive, negative)
}
private func getZeroFormat() -> String {
return string(from: 0) ?? "0"
}
open var format: String {
get {
let (p, n) = getFormatterComponents()
let z = _zeroSymbol ?? getZeroFormat()
return "\(p);\(z);\(n)"
}
set {
// Special case empty string
if newValue == "" {
_positiveFormat = ""
_negativeFormat = "-"
_zeroSymbol = "0"
_reset()
} else {
let components = newValue.components(separatedBy: ";")
let count = components.count
guard count <= 3 else { return }
_reset()
_positiveFormat = components.first ?? ""
if count == 1 {
_negativeFormat = "-\(_positiveFormat ?? "")"
}
else if count == 2 {
_negativeFormat = components[1]
_zeroSymbol = getZeroFormat()
}
else if count == 3 {
_zeroSymbol = components[1]
_negativeFormat = components[2]
}
if _negativeFormat == nil {
_negativeFormat = getFormatterComponents().1
}
if _zeroSymbol == nil {
_zeroSymbol = getZeroFormat()
}
}
}
}
private var _positiveFormat: String!
open var positiveFormat: String! {
get {
return getFormatterComponents().0
}
set {
_reset()
_positiveFormat = newValue
}
}
private var _negativeFormat: String!
open var negativeFormat: String! {
get {
return getFormatterComponents().1
}
set {
_reset()
_negativeFormat = newValue
}
}
private var _attributedStringForZero: NSAttributedString = NSAttributedString(string: "0")
/*@NSCopying*/ open var attributedStringForZero: NSAttributedString {
get {
return _attributedStringForZero
}
set {
_reset()
_attributedStringForZero = newValue
}
}
private var _attributedStringForNil: NSAttributedString = NSAttributedString(string: "")
/*@NSCopying*/ open var attributedStringForNil: NSAttributedString {
get {
return _attributedStringForNil
}
set {
_reset()
_attributedStringForNil = newValue
}
}
private var _attributedStringForNotANumber: NSAttributedString = NSAttributedString(string: "NaN")
/*@NSCopying*/ open var attributedStringForNotANumber: NSAttributedString {
get {
return _attributedStringForNotANumber
}
set {
_reset()
_attributedStringForNotANumber = newValue
}
}
private var _roundingBehavior: NSDecimalNumberHandler = NSDecimalNumberHandler.default
/*@NSCopying*/ open var roundingBehavior: NSDecimalNumberHandler {
get {
return _roundingBehavior
}
set {
_reset()
_roundingBehavior = newValue
}
}
}
| apache-2.0 | 334a321b5721787b606ff263db5f02ac | 31.534501 | 166 | 0.596087 | 5.883963 | false | false | false | false |
filograno/Moya | Demo/Tests/MoyaProviderIntegrationTests.swift | 1 | 11659 | import Quick
import Moya
import Nimble
import OHHTTPStubs
import Alamofire
func beIdenticalToResponse(_ expectedValue: Moya.Response) -> MatcherFunc<Moya.Response> {
return MatcherFunc { actualExpression, failureMessage in
do {
let instance = try actualExpression.evaluate()
return instance === expectedValue
} catch {
return false
}
}
}
class MoyaProviderIntegrationTests: QuickSpec {
override func spec() {
let userMessage = String(data: GitHub.userProfile("ashfurrow").sampleData, encoding: .utf8)
let zenMessage = String(data: GitHub.zen.sampleData, encoding: .utf8)
beforeEach {
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}) { _ in
return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil)
}
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/users/ashfurrow"}) { _ in
return OHHTTPStubsResponse(data: GitHub.userProfile("ashfurrow").sampleData, statusCode: 200, headers: nil)
}
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/basic-auth/user/passwd"}) { _ in
return OHHTTPStubsResponse(data: HTTPBin.basicAuth.sampleData, statusCode: 200, headers: nil)
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
describe("valid endpoints") {
describe("with live data") {
describe("a provider") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>()
}
it("returns real data for zen request") {
var message: String?
waitUntil { done in
_ = provider.request(.zen) { result in
if case let .success(response) = result {
message = String(data: response.data, encoding: .utf8)
}
done()
}
}
expect(message) == zenMessage
}
it("returns real data for user profile request") {
var message: String?
waitUntil { done in
let target: GitHub = .userProfile("ashfurrow")
_ = provider.request(target) { result in
if case let .success(response) = result {
message = String(data: response.data, encoding: .utf8)
}
done()
}
}
expect(message) == userMessage
}
it("uses a custom Alamofire.Manager request generation") {
let manager = StubManager()
let provider = MoyaProvider<GitHub>(manager: manager)
waitUntil { done in
_ = provider.request(GitHub.zen) { _ in done() }
}
expect(manager.called) == true
}
it("uses other background queue") {
var isMainThread: Bool?
let queue = DispatchQueue(label: "background_queue", attributes: .concurrent)
let target: GitHub = .zen
waitUntil { done in
_ = provider.request(target, queue:queue) { _ in
isMainThread = Thread.isMainThread
done()
}
}
expect(isMainThread) == false
}
it("uses main queue") {
var isMainThread: Bool?
let target: GitHub = .zen
waitUntil { done in
_ = provider.request(target) { _ in
isMainThread = Thread.isMainThread
done()
}
}
expect(isMainThread) == true
}
}
describe("a provider with credential plugin") {
it("credential closure returns nil") {
var called = false
let plugin = CredentialsPlugin { _ in
called = true
return nil
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
expect(provider.plugins.count).to(equal(1))
waitUntil { done in
_ = provider.request(.basicAuth) { _ in done() }
}
expect(called) == true
}
it("credential closure returns valid username and password") {
var called = false
var returnedData: Data?
let plugin = CredentialsPlugin { _ in
called = true
return URLCredential(user: "user", password: "passwd", persistence: .none)
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
let target = HTTPBin.basicAuth
waitUntil { done in
_ = provider.request(target) { result in
if case let .success(response) = result {
returnedData = response.data
}
done()
}
}
expect(called) == true
expect(returnedData) == target.sampleData
}
}
describe("a provider with network activity plugin") {
it("notifies at the beginning of network requests") {
var called = false
let plugin = NetworkActivityPlugin { change in
if change == .began {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
_ = provider.request(.zen) { _ in done() }
}
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
let plugin = NetworkActivityPlugin { change in
if change == .ended {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
_ = provider.request(.zen) { _ in done() }
}
expect(called) == true
}
}
describe("a provider with network logger plugin") {
var log = ""
var plugin: NetworkLoggerPlugin!
beforeEach {
log = ""
plugin = NetworkLoggerPlugin(verbose: true, output: { printing in
//mapping the Any... from items to a string that can be compared
let stringArray: [String] = printing.2.map { $0 as? String }.flatMap { $0 }
let string: String = stringArray.reduce("") { $0 + $1 + " " }
log += string
})
}
it("logs the request") {
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
_ = provider.request(GitHub.zen) { _ in done() }
}
expect(log).to( contain("Request:") )
expect(log).to( contain("{ URL: https://api.github.com/zen }") )
expect(log).to( contain("Request Headers: [:]") )
expect(log).to( contain("HTTP Request Method: GET") )
expect(log).to( contain("Response:") )
expect(log).to( contain("{ URL: https://api.github.com/zen } { status code: 200, headers") )
expect(log).to( contain("\"Content-Length\" = 43;") )
}
}
}
describe("a reactive provider with SignalProducer") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>()
}
it("returns some data for zen request") {
var message: String?
waitUntil { done in
provider.request(token: .zen).startWithResult { result in
if case .success(let response) = result {
message = String(data: response.data, encoding: String.Encoding.utf8)
done()
}
}
}
expect(message) == zenMessage
}
it("returns some data for user profile request") {
var message: String?
waitUntil { done in
let target: GitHub = .userProfile("ashfurrow")
provider.request(token: target).startWithResult { result in
if case .success(let response) = result {
message = String(data: response.data, encoding: String.Encoding.utf8)
done()
}
}
}
expect(message) == userMessage
}
}
}
}
}
class StubManager: Manager {
var called = false
override func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
called = true
return super.request(urlRequest)
}
}
| mit | 54d7a77e1d2b88227a42dd8072052677 | 40.78853 | 123 | 0.387169 | 6.882527 | false | false | false | false |
tkremenek/swift | stdlib/private/OSLog/OSLogStringTypes.swift | 7 | 7015 | //===----------------- OSLogStringTypes.swift -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file defines extensions for interpolating strings into an OSLogMesage.
// It defines `appendInterpolation` function for String type. It also defines
// extensions for serializing strings into the argument buffer passed to
// os_log ABIs. Note that os_log requires passing a stable pointer to an
// interpolated string.
//
// The `appendInterpolation` function defined in this file accept privacy and
// alignment options along with the interpolated expression as shown below:
//
// 1. "\(x, privacy: .private, align: .right\)"
// 2. "\(x, align: .right(columns: 10)\)"
extension OSLogInterpolation {
/// Defines interpolation for expressions of type String.
///
/// Do not call this function directly. It will be called automatically when interpolating
/// a value of type `String` in the string interpolations passed to the log APIs.
///
/// - Parameters:
/// - argumentString: The interpolated expression of type String, which is autoclosured.
/// - align: Left or right alignment with the minimum number of columns as
/// defined by the type `OSLogStringAlignment`.
/// - privacy: A privacy qualifier which is either private or public.
/// It is auto-inferred by default.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
@_semantics("oslog.requires_constant_arguments")
public mutating func appendInterpolation(
_ argumentString: @autoclosure @escaping () -> String,
align: OSLogStringAlignment = .none,
privacy: OSLogPrivacy = .auto
) {
guard argumentCount < maxOSLogArgumentCount else { return }
formatString += getStringFormatSpecifier(align, privacy)
// If minimum column width is specified, append this value first. Note that the
// format specifier would use a '*' for width e.g. %*s.
if let minColumns = align.minimumColumnWidth {
appendAlignmentArgument(minColumns)
}
// If the privacy has a mask, append the mask argument, which is a constant payload.
// Note that this should come after the width but before the precision.
if privacy.hasMask {
appendMaskArgument(privacy)
}
// Append the string argument.
addStringHeaders(privacy)
arguments.append(argumentString)
argumentCount += 1
stringArgumentCount += 1
}
/// Update preamble and append argument headers based on the parameters of
/// the interpolation.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal mutating func addStringHeaders(_ privacy: OSLogPrivacy) {
// Append argument header.
let header = getArgumentHeader(privacy: privacy, type: .string)
arguments.append(header)
// Append number of bytes needed to serialize the argument.
let byteCount = pointerSizeInBytes()
arguments.append(UInt8(byteCount))
// Increment total byte size by the number of bytes needed for this
// argument, which is the sum of the byte size of the argument and
// two bytes needed for the headers.
totalBytesForSerializingArguments += byteCount + 2
preamble = getUpdatedPreamble(privacy: privacy, isScalar: false)
}
/// Construct an os_log format specifier from the given parameters.
/// This function must be constant evaluable and all its arguments
/// must be known at compile time.
@inlinable
@_semantics("constant_evaluable")
@_effects(readonly)
@_optimize(none)
internal func getStringFormatSpecifier(
_ align: OSLogStringAlignment,
_ privacy: OSLogPrivacy
) -> String {
var specifier = "%"
if let privacySpecifier = privacy.privacySpecifier {
specifier += "{"
specifier += privacySpecifier
specifier += "}"
}
if case .start = align.anchor {
specifier += "-"
}
if let _ = align.minimumColumnWidth {
specifier += "*"
}
specifier += "s"
return specifier
}
}
extension OSLogArguments {
/// Append an (autoclosured) interpolated expression of String type, passed to
/// `OSLogMessage.appendInterpolation`, to the array of closures tracked
/// by this instance.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal mutating func append(_ value: @escaping () -> String) {
argumentClosures.append({ (position, _, stringArgumentOwners) in
serialize(
value(),
at: &position,
storingStringOwnersIn: &stringArgumentOwners)
})
}
}
/// Return the byte size of a pointer as strings are passed to the C os_log ABIs by
/// a stable pointer to its UTF8 bytes. Since pointers do not have a public
/// bitWidth property, and since MemoryLayout is not supported by the constant
/// evaluator, this function returns the byte size of Int, which must equal the
/// word length of the target architecture and hence the pointer size.
/// This function must be constant evaluable. Note that it is marked transparent
/// instead of @inline(__always) as it is used in optimize(none) functions.
@_transparent
@_alwaysEmitIntoClient
internal func pointerSizeInBytes() -> Int {
return Int.bitWidth &>> logBitsPerByte
}
/// Serialize a stable pointer to the string `stringValue` at the buffer location
/// pointed to by `bufferPosition`.
@_alwaysEmitIntoClient
@inline(__always)
internal func serialize(
_ stringValue: String,
at bufferPosition: inout UnsafeMutablePointer<UInt8>,
storingStringOwnersIn stringArgumentOwners: inout ObjectStorage<Any>
) {
let stringPointer =
getNullTerminatedUTF8Pointer(
stringValue,
storingStringOwnersIn: &stringArgumentOwners)
let byteCount = pointerSizeInBytes()
let dest =
UnsafeMutableRawBufferPointer(start: bufferPosition, count: byteCount)
withUnsafeBytes(of: stringPointer) { dest.copyMemory(from: $0) }
bufferPosition += byteCount
}
/// Return a pointer that points to a contiguous sequence of null-terminated,
/// UTF8 charcters. If necessary, extends the lifetime of `stringValue` by
/// using `stringArgumentOwners`.
@_alwaysEmitIntoClient
@inline(never)
internal func getNullTerminatedUTF8Pointer(
_ stringValue: String,
storingStringOwnersIn stringArgumentOwners: inout ObjectStorage<Any>
) -> UnsafeRawPointer {
let (optStorage, bytePointer, _, _, _):
(AnyObject?, UnsafeRawPointer, Int, Bool, Bool) =
stringValue._deconstructUTF8(scratch: nil)
if let storage = optStorage {
initializeAndAdvance(&stringArgumentOwners, to: storage)
} else {
initializeAndAdvance(&stringArgumentOwners, to: stringValue._guts)
}
return bytePointer
}
| apache-2.0 | 33bb9d4772dd9eb28b1b083eab2985db | 36.116402 | 92 | 0.707056 | 4.584967 | false | false | false | false |
EnjoySR/ESRefreshControl | ESRefreshDemo/ESRefreshDemo/RrefeshControl/ESSinaRefreshControl.swift | 1 | 7478 | //
// SinaRefreshControl.swift
// ESRefreshDemo
//
// Created by EnjoySR on 15/11/22.
// Copyright © 2015年 EnjoySR. All rights reserved.
//
import UIKit
// 默认高度
private let SinaRefreshControlHeight: CGFloat = 44
enum SinaRefreshState: Int {
case Normal = 0 // 默认状态
case Pulling = 1 // 松手就可以刷新的状态
case Refreshing = 2 // 正在刷新的状态
}
class ESSinaRefreshControl: UIControl {
// 定义 scrollView,用于记录当前控件添加到哪一个 View 上
var scrollView: UIScrollView?
// 旧状态
var oldState: SinaRefreshState?
// 定义当前控件的刷新状态
var refreshState: SinaRefreshState = .Normal {
didSet{
switch refreshState {
case .Pulling: // 松手就可以刷新的状态
self.arrowIcon.transform = CGAffineTransformMakeRotation(-0.01)
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
})
messageLabel.text = "释放更新"
case .Normal: // 置为默认的状态的效果
self.arrowIcon.transform = CGAffineTransformIdentity
messageLabel.text = "下拉刷新"
arrowIcon.hidden = false
indecator.stopAnimating()
// 如果之前状态是刷新状态,需要递减 contentInset.top
if oldState == .Refreshing {
// 重置contentInsetTop
UIView.animateWithDuration(0.25, animations: { () -> Void in
var contentInset = self.scrollView!.contentInset
contentInset.top -= self.es_height
self.scrollView?.contentInset = contentInset
})
}
case .Refreshing: // 显示刷新的效果
// 添加顶部可以多滑动的距离
UIView.animateWithDuration(0.25, animations: { () -> Void in
var contentInset = self.scrollView!.contentInset
contentInset.top += self.es_height
self.scrollView?.contentInset = contentInset
})
// 隐藏箭头
arrowIcon.hidden = true
// 开始菊花转
indecator.startAnimating()
// 显示 `加载中…`
messageLabel.text = "加载中…"
// 调用刷新的方法
sendActionsForControlEvents(.ValueChanged)
}
oldState = refreshState
}
}
// MARK: - 提供给外界的方法
/// 结束刷新
func endRefreshing(){
self.refreshState = .Normal
}
// MARK: - 初始化控件
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
private func setupUI(){
es_height = SinaRefreshControlHeight;
es_y = -SinaRefreshControlHeight
// 添加控件
addSubview(arrowIcon)
addSubview(messageLabel)
addSubview(indecator)
// 添加约束
arrowIcon.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: arrowIcon, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -30))
addConstraint(NSLayoutConstraint(item: arrowIcon, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
messageLabel.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: arrowIcon, attribute: .Trailing, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: arrowIcon, attribute: .CenterY, multiplier: 1, constant: 0))
indecator.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: indecator, attribute: .CenterX, relatedBy: .Equal, toItem: arrowIcon, attribute: .CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: indecator, attribute: .CenterY, relatedBy: .Equal, toItem: arrowIcon, attribute: .CenterY, multiplier: 1, constant: 0))
}
// MARK: - 初始拖动相关逻辑
/// 当前 view 的父视图即将改变的时候会调用,可以在这个方法里面拿到父控件
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
// 如果父控件不为空,并且父控件是UIScrollView
if let scrollView = newSuperview where scrollView.isKindOfClass(NSClassFromString("UIScrollView")!) {
scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
// 记录当前 scrollView,以便在 `deinit` 方法里面移除监听
self.scrollView = scrollView as? UIScrollView
self.es_width = scrollView.es_width
}
}
/// 当值改变之后回调的方法
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
// 取到顶部增加的可滑动的距离
let contentInsetTop = self.scrollView!.contentInset.top
// 取到当前 scrollView 的偏移 Y
let contentOffsetY = self.scrollView!.contentOffset.y
// 临界值
let criticalValue = -contentInsetTop - self.es_height
// 在用户拖动的时候去判断临界值
if scrollView!.dragging {
if refreshState == .Normal && contentOffsetY < criticalValue {
// 完全显示出来
self.refreshState = .Pulling
}else if refreshState == .Pulling && contentOffsetY >= criticalValue {
// 没有完全显示出来/没有显示出来
self.refreshState = .Normal
}
}else{
// 判断如果用户已经松手,并且当前状态是.Pulling,那么进入到 .Refreshing 状态
if self.refreshState == .Pulling {
self.refreshState = .Refreshing
}
}
}
deinit{
// 移除监听
if let scrollView = self.scrollView {
scrollView.removeObserver(self, forKeyPath: "contentOffset")
}
}
// MARK: - 懒加载控件
// 箭头图标
private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
// 显示文字的label
private lazy var messageLabel: UILabel = {
let label = UILabel()
label.text = "下拉刷新"
label.textColor = UIColor.grayColor()
label.font = UIFont.systemFontOfSize(12)
return label
}()
// 菊花转
private lazy var indecator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
}
| mit | 054d57fbb527f2bfdf3d559dd4aa1dc0 | 36.298343 | 170 | 0.595319 | 4.993343 | false | false | false | false |
TribeMedia/Dynamo | Dynamo/Connection.swift | 1 | 15717 | //
// Connection.swift
// Dynamo
//
// Created by John Holdsworth on 22/06/2015.
// Copyright (c) 2015 John Holdsworth. All rights reserved.
//
// $Id: //depot/Dynamo/Dynamo/Connection.swift#52 $
//
// Repo: https://github.com/johnno1962/Dynamo
//
import Foundation
// MARK: HTTP request parser
let dummyBase = NSURL( string: "http://nohost" )!
private var dynamoRelayThreads = 0
/**
HTTP return status mapping
*/
public var dynamoStatusText = [
200: "OK",
304: "Redirect",
400: "Invalid request",
404: "File not found",
500: "Server error"
]
var webDateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
return formatter
}()
/**
Class representing a request from a client web browser. This is the request part
of DynamoHTTPConnection though in practice they are the same instance.
*/
public class DynamoHTTPRequest: NSObject {
let clientSocket: Int32
/** reeust method received frmo browser */
public var method = "GET"
/** path to document requests */
public var path = "/"
/** HTTP version from browser */
public var version = "HTTP/1.1"
/** request parsed as NSURL */
public var url = dummyBase
/** HTTP request headers received */
public var requestHeaders = [String:String]()
/** status to be returned in response */
public var status = 200
// response ivars need to be here...
private var responseHeaders = ""
private var sentResponseHeaders = false
/** "deflate" respose when possible - less bandwidth but slow */
public var compressResponse = false
/** whether Content-Length has been supplied */
var knowsResponseLength = false
// read buffering
let readBuffer = NSMutableData()
var readTotal = 0
var label = ""
/** initialise connection to browser with socket */
public init?( clientSocket: Int32 ) {
self.clientSocket = clientSocket
super.init()
if clientSocket >= 0 {
var yes: u_int = 1, yeslen = socklen_t(sizeof(yes.dynamicType))
if setsockopt( clientSocket, SOL_SOCKET, SO_NOSIGPIPE, &yes, yeslen ) < 0 {
dynamoStrerror( "Could not set SO_NOSIGPIPE" )
return nil
}
}
}
/** initialise connection to reote host/port specified in URL */
public convenience init?( url: NSURL ) {
if let host = url.host {
let port = UInt16(url.port?.intValue ?? 80)
if var addr = addressForHost( host, port ) {
let remoteSocket = socket( Int32(addr.sa_family), SOCK_STREAM, 0 )
if remoteSocket < 0 {
dynamoStrerror( "Could not obtain remote socket" )
}
else if connect( remoteSocket, &addr, socklen_t(addr.sa_len) ) < 0 {
dynamoStrerror( "Could not connect to: \(host):\(port)" )
}
else {
self.init( clientSocket: remoteSocket )
return
}
}
}
self.init( clientSocket: -1 )
return nil
}
/** reports to IP address of remote user (if not proxied */
public var remoteAddr: String {
var addr = sockaddr()
var addrLen = socklen_t(sizeof(addr.dynamicType))
if getpeername( clientSocket, &addr, &addrLen ) == 0 {
if addr.sa_family == sa_family_t(AF_INET) {
return String( UTF8String: inet_ntoa( sockaddr_in_cast(&addr).memory.sin_addr ) )!
}
}
return "address unknown"
}
/** raw read from browser/remote connection */
func _read( buffer: UnsafeMutablePointer<Void>, count: Int ) -> Int {
return recv( clientSocket, buffer, count, 0 )
}
/** read the requested number of bytes */
public func read( buffer: UnsafeMutablePointer<Void>, count: Int ) -> Int {
var pos = min( readBuffer.length, count )
if pos != 0 {
memcpy( buffer, readBuffer.bytes, pos )
readBuffer.replaceBytesInRange( NSMakeRange( 0, pos ), withBytes: nil, length: 0 )
}
while pos < count {
let bytesRead = _read( buffer+pos, count: count-pos )
if bytesRead <= 0 {
break
}
pos += bytesRead
}
return pos
}
/** add a HTTP header value to the response */
public func addResponseHeader( name: String, value: String ) {
responseHeaders += "\(name): \(value)\r\n"
}
/** getter(request)/setter(response) for content mime type */
public var contentType: String {
get {
return requestHeaders["Content-Type"] ?? requestHeaders["Content-type"] ?? "text/plain"
}
set {
addResponseHeader( "Content-Type", value: newValue )
}
}
/** getter(rquest)/setter(response) for content length */
public var contentLength: Int? {
get {
return (requestHeaders["Content-Length"] ?? requestHeaders["Content-length"])?.toInt()
}
set {
addResponseHeader( "Content-Length", value: String( newValue ?? 0 ) )
knowsResponseLength = true
}
}
/** read/parse standard HTTP headers from browser */
func readHeaders() -> Bool {
if let request = readLine() {
let components = request.componentsSeparatedByString( " " )
if components.count == 3 {
method = components[0]
path = components[1]
version = components[2]
url = NSURL( string: path, relativeToURL: dummyBase ) ?? dummyBase
requestHeaders = [String: String]()
responseHeaders = ""
sentResponseHeaders = false
knowsResponseLength = false
compressResponse = false
status = 200
while let line = readLine() {
if let divider = line.rangeOfString( ": " )?.startIndex {
requestHeaders[line.substringToIndex( divider )] = line.substringFromIndex( advance( divider, 2 ) )
}
else {
return true
}
}
}
}
return false
}
var buffer = [Int8](count: 8192, repeatedValue: 0), newlineChar = Int32(10)
func readLine() -> String? {
while true {
let endOfLine = memchr( readBuffer.bytes, newlineChar, readBuffer.length )
if endOfLine != nil {
UnsafeMutablePointer<Int8>(endOfLine).memory = 0
let line = String( UTF8String: UnsafePointer<Int8>(readBuffer.bytes) )?
.stringByTrimmingCharactersInSet( NSCharacterSet.whitespaceAndNewlineCharacterSet() )
readBuffer.replaceBytesInRange( NSMakeRange( 0, endOfLine+1-readBuffer.bytes ), withBytes:nil, length:0 )
return line
}
let bytesRead = _read( UnsafeMutablePointer<Void>(buffer), count: buffer.count )
if bytesRead <= 0 {
break ///
}
readBuffer.appendBytes( buffer, length: bytesRead )
}
return nil
}
/** POST data as String */
public func postString() -> String? {
if let postLength = contentLength {
var buffer = [Int8](count: postLength+1, repeatedValue: 0)
if read( &buffer, count: postLength ) == postLength {
return String( UTF8String: buffer )
}
}
return nil
}
/** POST data as NSData */
public func postData() -> NSData? {
if let postLength = contentLength, data = NSMutableData( length: postLength )
where read( UnsafeMutablePointer<Void>(data.bytes), count: postLength ) == postLength {
return data
}
return nil
}
/** POST data as JSON object */
public func postJSON() -> AnyObject? {
if let data = postData() {
var error: NSError?
if let json: AnyObject = NSJSONSerialization.JSONObjectWithData( data, options: nil, error: &error ) {
return json
}
else {
dynamoLog( "JSON parse error:: \(error)" )
}
}
return nil
}
}
/**
Class representing a connection to a client web browser. One is created each time a browser
connects to read the standard HTTP headers ready to present to each of the swiftlets of the server.
*/
public class DynamoHTTPConnection: DynamoHTTPRequest {
/** raw write to browser/remote connection */
func _write( buffer: UnsafePointer<Void>, count: Int ) -> Int {
return send( clientSocket, buffer, count, 0 )
}
/** write the requested number of bytes */
public func write( buffer: UnsafePointer<Void>, count: Int ) -> Int {
var pos = 0
while pos < count {
let bytesWritten = _write( buffer+pos, count: count-pos )
if bytesWritten <= 0 {
break
}
pos += bytesWritten
}
return pos
}
/** flush any buffered print() output to browser */
public func flush() {
// writes not buffered currently
}
/** have browser set cookie for this session/domain/path */
public func setCookie( name: String, value: String, domain: String? = nil, path: String? = nil, expires: Int? = nil ) {
if !sentResponseHeaders {
var value = "\(name)=\(value.stringByAddingPercentEscapesUsingEncoding( NSUTF8StringEncoding )!)"
if domain != nil {
value += "; Domain="+domain!
}
if path != nil {
value += "; Path="+path!
}
if expires != nil {
let cookieDateFormatter = NSDateFormatter()
cookieDateFormatter.dateFormat = "EEE, dd-MMM-yyyy HH:mm:ss zzz"
let expires = NSDate().dateByAddingTimeInterval( NSTimeInterval(expires!) )
value += "; Expires=" + cookieDateFormatter.stringFromDate( expires )
}
addResponseHeader( "Set-Cookie", value: value )
}
else {
dynamoLog( "Cookies must be set before the first HTML content is sent" )
}
}
private func sendResponseHeaders() {
if responseHeaders == "" {
contentType = dynamoHtmlMimeType
}
addResponseHeader( "Date", value: webDateFormatter.stringFromDate( NSDate() ) )
addResponseHeader( "Server", value: "Dynamo" )
let statusText = dynamoStatusText[status] ?? "Unknown Status"
rawPrint( "\(version) \(status) \(statusText)\r\n\(responseHeaders)\r\n" )
sentResponseHeaders = true
}
/** print a sring directly to browser */
public func rawPrint( output: String ) {
if let bytes = output.cStringUsingEncoding( NSUTF8StringEncoding ) {
write( bytes, count: Int(strlen(bytes)) )
}
else {
dynamoLog( "Could not encode: \(output)" )
}
}
/** print a string, sending HTTP headers if not already sent */
public func print( output: String ) {
if !sentResponseHeaders {
sendResponseHeaders()
}
rawPrint( output )
}
/** set response as a whole from a String */
public func response( output: String ) {
if var bytes = output.cStringUsingEncoding( NSUTF8StringEncoding ) {
responseData( NSData( bytesNoCopy: &bytes, length: Int(strlen(bytes)), freeWhenDone: false ) )
}
else {
dynamoLog( "Could not encode: \(output)" )
}
}
/** set response as a whole from JSON object */
public func responseJSON( object: AnyObject ) {
var error: NSError?
if NSJSONSerialization.isValidJSONObject( object ) {
if let json = NSJSONSerialization.dataWithJSONObject( object,
options: NSJSONWritingOptions.PrettyPrinted, error: &error ) {
contentType = dynamoMimeTypeMapping["json"] ?? "application/json"
responseData( json )
return
}
}
dynamoLog( "Could not encode: \(object) \(error)" )
}
/** set response as a whole from NSData */
public func responseData( data: NSData ) {
var dout = data
#if os(OSX)
if compressResponse && requestHeaders["Accept-Encoding"] == "gzip, deflate" {
if let deflated = dout.deflate() {
dout = deflated
addResponseHeader( "Content-Encoding", value: "deflate" )
}
}
#endif
contentLength = dout.length
sendResponseHeaders()
write( dout.bytes, count: dout.length )
}
// for DynamoSelector used by proxies
var hasBytesAvailable: Bool {
return false
}
func receive( buffer: UnsafeMutablePointer<Void>, count: Int ) -> Int? {
return _read( buffer, count: count )
}
func forward( buffer: UnsafePointer<Void>, count: Int ) -> Int? {
return _write( buffer, count: count )
}
deinit {
flush()
close( clientSocket )
}
}
// MARK: Cached gethostbyname()
private var hostAddressCache = [String:UnsafeMutablePointer<sockaddr>]()
/**
Caching version of gethostbyname() returning a struct sockaddr for use in a connect() call
*/
public func addressForHost( hostname: String, port: UInt16 ) -> sockaddr? {
var addr: UnsafeMutablePointer<hostent> = nil
var sockaddrTmp = hostAddressCache[hostname]?.memory
if sockaddrTmp == nil {
if let hostString = hostname.cStringUsingEncoding( NSUTF8StringEncoding ) {
addr = gethostbyname( hostString )
}
if addr == nil {
dynamoLog( "Could not resolve \(hostname) - "+String( UTF8String: hstrerror(h_errno) )! )
return nil
}
}
if sockaddrTmp == nil {
let sockaddrPtr = UnsafeMutablePointer<sockaddr>(malloc(sizeof(sockaddr.self)))
switch addr.memory.h_addrtype {
case AF_INET:
let addr0 = UnsafePointer<in_addr>(addr.memory.h_addr_list.memory)
var ip4addr = sockaddr_in(sin_len: UInt8(sizeof(sockaddr_in)),
sin_family: sa_family_t(addr.memory.h_addrtype),
sin_port: htons( port ), sin_addr: addr0.memory,
sin_zero: (Int8(0),Int8(0),Int8(0),Int8(0),Int8(0),Int8(0),Int8(0),Int8(0)))
sockaddrPtr.memory = sockaddr_cast(&ip4addr).memory
case AF_INET6: // TODO... completely untested
let addr0 = UnsafePointer<in6_addr>(addr.memory.h_addr_list.memory)
var ip6addr = sockaddr_in6(sin6_len: UInt8(sizeof(sockaddr_in6)),
sin6_family: sa_family_t(addr.memory.h_addrtype),
sin6_port: htons( port ), sin6_flowinfo: 0, sin6_addr: addr0.memory,
sin6_scope_id: 0)
sockaddrPtr.memory = sockaddr_cast(&ip6addr).memory
default:
dynamoLog( "Unknown address family: \(addr.memory.h_addrtype)" )
return nil
}
hostAddressCache[hostname] = sockaddrPtr
sockaddrTmp = sockaddrPtr.memory
}
else {
sockaddr_in_cast( &(sockaddrTmp!) ).memory.sin_port = htons( port )
}
return sockaddrTmp
}
extension NSData {
/**
Swizzled/overridden by NSData+deflate.m
*/
func deflate() -> NSData? {
return nil
}
}
| mit | 384d900774b374b1c7bc5a42dd77e322 | 31.339506 | 123 | 0.573137 | 4.551694 | false | false | false | false |
kyouko-taiga/anzen | Sources/Parser/Parser+Type.swift | 1 | 11025 | import AST
extension Parser {
/// Parses a qualified type signature.
func parseQualSign() -> Result<QualTypeSign?> {
// If the first token is a left parenthesis, attempt first to parse a function signature, as
// it is more likely than an enclosed signature.
if peek().kind == .leftParen {
let backtrackPosition = streamPosition
let functionSignatureParseResult = parseFunSign()
// If we failed to parse a function signature, attempt to parse an enclosed signature.
guard let signature = functionSignatureParseResult.value else {
rewind(to: backtrackPosition)
let start = consume(.leftParen)!.range.start
consumeNewlines()
let enclosedParseResult = parseQualSign()
if let enclosed = enclosedParseResult.value {
// Commit to this path if an enclosed signature could be parsed.
guard let delimiter = consume(.rightParen, afterMany: .newline) else {
defer { consumeUpToNextStatementDelimiter() }
return Result(
value: nil,
errors: enclosedParseResult.errors + [unexpectedToken(expected: "')'")])
}
enclosed.range = SourceRange(from: start, to: delimiter.range.end)
return Result(value: enclosed, errors: enclosedParseResult.errors)
} else {
// If we couldn't parse an enclosed signature, assume the error occured while parsing a
// function signature.
consumeUpToNextStatementDelimiter()
return Result(value: nil, errors: functionSignatureParseResult.errors)
}
}
// If we succeeded to parse a function signature, we return it without qualifier.
return Result(
value: QualTypeSign(
qualifiers: [],
signature: signature,
module: module,
range: signature.range),
errors: functionSignatureParseResult.errors)
}
var errors: [ParseError] = []
// Parse the qualifiers (if any).
var qualifiers: [(value: TypeQualifier, range: SourceRange)] = []
while let qualifier = consume(.qualifier) {
switch qualifier.value! {
case "cst": qualifiers.append((.cst, qualifier.range))
case "mut": qualifiers.append((.mut, qualifier.range))
default:
errors.append(parseFailure(.invalidQualifier(value: qualifier.value!)))
}
// Skip trailing new lines.
consumeNewlines()
}
// Parse the unqualified type signature.
let backtrackPosition = streamPosition
let signatureParseResult = parseTypeSign()
guard let signature = signatureParseResult.value else {
// If the signature could not be parsed, make sure at least one qualifier could.
guard !qualifiers.isEmpty else {
return Result(value: nil, errors: errors + signatureParseResult.errors)
}
// If there is at least one qualifier, we can ignore the signature's parsing failure, rewind
// the token stream and return a signature without explicit unqualified signature.
rewind(to: backtrackPosition)
return Result(
value: QualTypeSign(
qualifiers: Set(qualifiers.map({ $0.value })),
signature: nil, module: module,
range: SourceRange(from: qualifiers.first!.range.start, to: qualifiers.last!.range.end)),
errors: errors)
}
errors.append(contentsOf: signatureParseResult.errors)
let range = qualifiers.isEmpty
? signature.range
: SourceRange(from: qualifiers.first!.range.start, to: signature.range.end)
return Result(
value: QualTypeSign(
qualifiers: Set(qualifiers.map({ $0.value })),
signature: signature,
module: module,
range: range),
errors: errors)
}
/// Parses an unqualified type signature.
func parseTypeSign() -> Result<TypeSign?> {
switch peek().kind {
case .identifier:
let parseResult = parseTypeIdentifier()
return Result(value: parseResult.value, errors: parseResult.errors)
case .leftParen:
// First, attempt to parse a function signature.
let backtrackPosition = streamPosition
let functionSignatureParseResult = parseFunSign()
// If we failed to parse a function signature, attempt to parse an enclosed signature.
guard let signature = functionSignatureParseResult.value else {
rewind(to: backtrackPosition)
let start = consume(.leftParen)!.range.start
consumeNewlines()
let enclosedParseResult = parseTypeSign()
if let enclosed = enclosedParseResult.value {
// Commit to this path if an enclosed signature could be parsed.
guard let delimiter = consume(.rightParen, afterMany: .newline) else {
defer { consumeUpToNextStatementDelimiter() }
return Result(
value: nil,
errors: enclosedParseResult.errors + [unexpectedToken(expected: "')'")])
}
enclosed.range = SourceRange(from: start, to: delimiter.range.end)
return Result(value: enclosed, errors: enclosedParseResult.errors)
} else {
// If we couldn't parse an enclosed signature, assume the error occured while parsing a
// function signature.
consumeUpToNextStatementDelimiter()
return Result(value: nil, errors: functionSignatureParseResult.errors)
}
}
return Result(value: signature, errors: functionSignatureParseResult.errors)
default:
defer { consume() }
return Result(value: nil, errors: [unexpectedToken(expected: "type signature")])
}
}
/// Parses a type identifier.
func parseTypeIdentifier() -> Result<TypeIdent?> {
// The first token should be an identifier.
guard let token = consume(.identifier) else {
defer { consume() }
return Result(value: nil, errors: [unexpectedToken(expected: "identifier")])
}
let identifier = TypeIdent(name: token.value!, module: module, range: token.range)
var errors: [ParseError] = []
// Attempt to parse a specialization list.
let backtrackPosition = streamPosition
consumeNewlines()
if peek().kind == .lt, let specializationsParseResult = attempt(parseSpecializationList) {
errors.append(contentsOf: specializationsParseResult.errors)
for (token, value) in specializationsParseResult.value {
// Make sure there are no duplicate keys.
guard identifier.specializations[token.value!] == nil else {
errors.append(ParseError(.duplicateKey(key: token.value!), range: token.range))
continue
}
identifier.specializations[token.value!] = value
}
} else {
rewind(to: backtrackPosition)
}
return Result(value: identifier, errors: errors)
}
/// Parses a specialization list.
func parseSpecializationList() -> Result<[(Token, QualTypeSign)]?> {
// The first token should be a left angle bracket.
guard consume(.lt) != nil else {
defer { consume() }
return Result(value: nil, errors: [unexpectedToken(expected: "unary operator")])
}
var errors: [ParseError] = []
// Parse the specialization arguments.
let argumentsParseResult = parseList(delimitedBy: .gt, parsingElementWith: parseSpecArg)
errors.append(contentsOf: argumentsParseResult.errors)
guard consume(.gt) != nil else {
defer { consumeUpToNextStatementDelimiter() }
return Result(value: nil, errors: errors + [unexpectedToken(expected: "'>'")])
}
return Result(value: argumentsParseResult.value, errors: errors)
}
/// Parses a specialization argument.
func parseSpecArg() -> Result<(Token, QualTypeSign)?> {
// Parse the name of the placeholder.
guard let name = consume(.identifier) else {
defer { consume() }
return Result(value: nil, errors: [unexpectedToken(expected: "identifier")])
}
var errors: [ParseError] = []
// Parse the signature to which it should map.
guard consume(.assign, afterMany: .newline) != nil else {
defer { consumeUpToNextStatementDelimiter() }
return Result(value: nil, errors: [unexpectedToken(expected: "'='")])
}
consumeNewlines()
let signatureParseResult = parseQualSign()
errors.append(contentsOf: signatureParseResult.errors)
guard let signature = signatureParseResult.value else {
return Result(value: nil, errors: errors)
}
return Result(value: (name, signature), errors: errors)
}
/// Parses a function type signature.
func parseFunSign() -> Result<FunSign?> {
// The first token should be left parenthesis.
guard let startToken = consume(.leftParen) else {
defer { consume() }
return Result(value: nil, errors: [unexpectedToken(expected: "'('")])
}
var errors: [ParseError] = []
// Parse the parameter list.
let parametersParseResult = parseList(
delimitedBy: .rightParen,
parsingElementWith: parseParamSign)
errors.append(contentsOf: parametersParseResult.errors)
guard consume(.rightParen) != nil else {
defer { consumeUpToNextStatementDelimiter() }
return Result(value: nil, errors: errors + [unexpectedToken(expected: "')'")])
}
// Parse the codomain.
guard consume(.arrow, afterMany: .newline) != nil else {
defer { consumeUpToNextStatementDelimiter() }
return Result(value: nil, errors: errors + [unexpectedToken(expected: "'->'")])
}
consumeNewlines()
let codomainParseResult = parseQualSign()
errors.append(contentsOf: codomainParseResult.errors)
guard let codomain = codomainParseResult.value else {
return Result(value: nil, errors: errors)
}
return Result(
value: FunSign(
parameters: parametersParseResult.value,
codomain: codomain,
module: module,
range: SourceRange(from: startToken.range.start, to: codomain.range.end)),
errors: errors)
}
/// Parses a function parameter signature.
func parseParamSign() -> Result<ParamSign?> {
// Parse the label of the parameter.
guard let label = consume([.identifier, .underscore]) else {
defer { consume() }
return Result(value: nil, errors: [unexpectedToken(expected: "identifier")])
}
var errors: [ParseError] = []
// Parse the qualified signature of the parameter.
guard consume(.colon, afterMany: .newline) != nil else {
defer { consumeUpToNextStatementDelimiter() }
return Result(value: nil, errors: [unexpectedToken(expected: "':'")])
}
consumeNewlines()
let signatureParseResult = parseQualSign()
errors.append(contentsOf: signatureParseResult.errors)
guard let signature = signatureParseResult.value else {
return Result(value: nil, errors: errors)
}
return Result(
value: ParamSign(
label: label.value,
typeAnnotation: signature,
module: module,
range: SourceRange(from: label.range.start, to: signature.range.end)),
errors: errors)
}
}
| apache-2.0 | 8dc022d7972168ecc5a828ad86a28fd8 | 35.627907 | 99 | 0.663583 | 4.683517 | false | false | false | false |
qutheory/vapor | Tests/VaporTests/UtilityTests.swift | 1 | 1410 | import XCTVapor
final class UtilityTests: XCTestCase {
func testHexEncoding() throws {
let bytes: [UInt8] = [1, 42, 128, 240]
XCTAssertEqual(bytes.hex, "012a80f0")
XCTAssertEqual(bytes.hexEncodedString(), "012a80f0")
XCTAssertEqual(bytes.hexEncodedString(uppercase: true), "012A80F0")
}
func testHexEncodingSequence() throws {
let bytes: AnySequence<UInt8> = AnySequence([1, 42, 128, 240])
XCTAssertEqual(bytes.hex, "012a80f0")
XCTAssertEqual(bytes.hexEncodedString(), "012a80f0")
XCTAssertEqual(bytes.hexEncodedString(uppercase: true), "012A80F0")
}
func testBase32() throws {
let data = Data([1, 2, 3, 4])
XCTAssertEqual(data.base32EncodedString(), "AEBAGBA")
XCTAssertEqual(Data(base32Encoded: "AEBAGBA"), data)
}
func testByteCount() throws {
let twoKbUpper: ByteCount = "2 KB"
XCTAssertEqual(twoKbUpper.value, 2_048)
let twoKb: ByteCount = "2kb"
XCTAssertEqual(twoKb.value, 2_048)
let oneMb: ByteCount = "1mb"
XCTAssertEqual(oneMb.value, 1_048_576)
let oneGb: ByteCount = "1gb"
XCTAssertEqual(oneGb.value, 1_073_741_824)
let oneTb: ByteCount = "1tb"
XCTAssertEqual(oneTb.value, 1_099_511_627_776)
let intBytes: ByteCount = 1_000_000
XCTAssertEqual(intBytes.value, 1_000_000)
}
}
| mit | b9559f8b186513b8f0068dbd265bd745 | 31.045455 | 75 | 0.639007 | 3.624679 | false | true | false | false |
zybug/firefox-ios | Client/Frontend/Browser/OpenSearch.swift | 18 | 8375 | /* 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 UIKit
import SWXMLHash
private let TypeSearch = "text/html"
private let TypeSuggest = "application/x-suggestions+json"
private let SearchTermsAllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*-_."
extension NSCharacterSet {
class func URLAllowedCharacterSet() -> NSCharacterSet {
let characterSet = NSMutableCharacterSet()
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLUserAllowedCharacterSet())
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLPathAllowedCharacterSet())
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLPasswordAllowedCharacterSet())
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLHostAllowedCharacterSet())
characterSet.formUnionWithCharacterSet(NSCharacterSet.URLFragmentAllowedCharacterSet())
return characterSet
}
}
class OpenSearchEngine {
static let PreferredIconSize = 30
let shortName: String
let description: String?
let image: UIImage?
private let searchTemplate: String
private let suggestTemplate: String?
init(shortName: String, description: String?, image: UIImage?, searchTemplate: String, suggestTemplate: String?) {
self.shortName = shortName
self.description = description
self.image = image
self.searchTemplate = searchTemplate
self.suggestTemplate = suggestTemplate
}
/**
* Returns the search URL for the given query.
*/
func searchURLForQuery(query: String) -> NSURL? {
return getURLFromTemplate(searchTemplate, query: query)
}
/**
* Returns the search suggestion URL for the given query.
*/
func suggestURLForQuery(query: String) -> NSURL? {
if let suggestTemplate = suggestTemplate {
return getURLFromTemplate(suggestTemplate, query: query)
}
return nil
}
private func getURLFromTemplate(searchTemplate: String, query: String) -> NSURL? {
let allowedCharacters = NSCharacterSet(charactersInString: SearchTermsAllowedCharacters)
if let escapedQuery = query.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters) {
// Escape the search template as well in case it contains not-safe characters like symbols
let templateAllowedSet = NSMutableCharacterSet()
templateAllowedSet.formUnionWithCharacterSet(NSCharacterSet.URLAllowedCharacterSet())
// Allow brackets since we use them in our template as our insertion point
templateAllowedSet.formUnionWithCharacterSet(NSCharacterSet(charactersInString: "{}"))
if let encodedSearchTemplate = searchTemplate.stringByAddingPercentEncodingWithAllowedCharacters(templateAllowedSet) {
let urlString = encodedSearchTemplate.stringByReplacingOccurrencesOfString("{searchTerms}", withString: escapedQuery, options: NSStringCompareOptions.LiteralSearch, range: nil)
return NSURL(string: urlString)
}
}
return nil
}
}
/**
* OpenSearch XML parser.
*
* This parser accepts standards-compliant OpenSearch 1.1 XML documents in addition to
* the Firefox-specific search plugin format.
*
* OpenSearch spec: http://www.opensearch.org/Specifications/OpenSearch/1.1
*/
class OpenSearchParser {
private let pluginMode: Bool
init(pluginMode: Bool) {
self.pluginMode = pluginMode
}
func parse(file: String) -> OpenSearchEngine? {
let data = NSData(contentsOfFile: file)
if data == nil {
print("Invalid search file")
return nil
}
let rootName = pluginMode ? "SearchPlugin" : "OpenSearchDescription"
let docIndexer: XMLIndexer! = SWXMLHash.parse(data!)[rootName][0]
if docIndexer.element == nil {
print("Invalid XML document")
return nil
}
let shortNameIndexer = docIndexer["ShortName"]
if shortNameIndexer.all.count != 1 {
print("ShortName must appear exactly once")
return nil
}
let shortName = shortNameIndexer.element?.text
if shortName == nil {
print("ShortName must contain text")
return nil
}
let descriptionIndexer = docIndexer["Description"]
if !pluginMode && descriptionIndexer.all.count != 1 {
print("Description must appear exactly once")
return nil
}
let description = descriptionIndexer.element?.text
let urlIndexers = docIndexer["Url"].all
if urlIndexers.isEmpty {
print("Url must appear at least once")
return nil
}
var searchTemplate: String!
var suggestTemplate: String?
for urlIndexer in urlIndexers {
let type = urlIndexer.element?.attributes["type"]
if type == nil {
print("Url element requires a type attribute", terminator: "\n")
return nil
}
if type != TypeSearch && type != TypeSuggest {
// Not a supported search type.
continue
}
var template = urlIndexer.element?.attributes["template"]
if template == nil {
print("Url element requires a template attribute", terminator: "\n")
return nil
}
if pluginMode {
let paramIndexers = urlIndexer["Param"].all
if !paramIndexers.isEmpty {
template! += "?"
var firstAdded = false
for paramIndexer in paramIndexers {
if firstAdded {
template! += "&"
} else {
firstAdded = true
}
let name = paramIndexer.element?.attributes["name"]
let value = paramIndexer.element?.attributes["value"]
if name == nil || value == nil {
print("Param element must have name and value attributes", terminator: "\n")
return nil
}
template! += name! + "=" + value!
}
}
}
if type == TypeSearch {
searchTemplate = template
} else {
suggestTemplate = template
}
}
if searchTemplate == nil {
print("Search engine must have a text/html type")
return nil
}
let imageIndexers = docIndexer["Image"].all
var largestImage = 0
var largestImageElement: XMLElement?
// TODO: For now, just use the largest icon.
for imageIndexer in imageIndexers {
let imageWidth = Int(imageIndexer.element?.attributes["width"] ?? "")
let imageHeight = Int(imageIndexer.element?.attributes["height"] ?? "")
// Only accept square images.
if imageWidth != imageHeight {
continue
}
if let imageWidth = imageWidth {
if imageWidth > largestImage {
if imageIndexer.element?.text != nil {
largestImage = imageWidth
largestImageElement = imageIndexer.element
}
}
}
}
var uiImage: UIImage?
if let imageElement = largestImageElement,
imageURL = NSURL(string: imageElement.text!),
imageData = NSData(contentsOfURL: imageURL),
image = UIImage(data: imageData) {
uiImage = image
} else {
print("Error: Invalid search image data")
}
return OpenSearchEngine(shortName: shortName!, description: description, image: uiImage, searchTemplate: searchTemplate, suggestTemplate: suggestTemplate)
}
} | mpl-2.0 | c648332c749900cd5f40099b2afaf476 | 35.417391 | 192 | 0.606925 | 5.795848 | false | false | false | false |
balitm/Sherpany | Sherpany/AppDelegate.swift | 1 | 3170 | //
// AppDelegate.swift
// Sherpany
//
// Created by Balázs Kilvády on 3/3/16.
// Copyright © 2016 kil-dev. All rights reserved.
//
import UIKit
import DATAStack
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// Model object of the application.
var _model: Model! = nil
override init() {
super.init()
let config = Config()
_model = Model(config: config, dataStack: self.dataStack)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if let navController = window?.rootViewController as? UINavigationController {
let usersController = navController.topViewController as? UsersTableViewController
// Set the network event indicator delegate of the model.
_model.indicatorDelegate = self
// Set the model for the "main"/users controller.
usersController?.model = _model
usersController?.dataStack = dataStack
}
UINavigationBar.appearance().barTintColor = UIColor(red: 75.0/255.0, green: 195.0/255.0, blue: 123.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
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) {
self.dataStack.persistWithCompletion(nil)
}
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) {
self.dataStack.persistWithCompletion(nil)
}
// MARK: - DATA stack
lazy var dataStack: DATAStack = {
let dataStack = DATAStack(modelName: "Sherpany")
return dataStack
}()
}
// MARK: - ModelNetworkIndicatorDelegate extension.
extension AppDelegate: ModelNetworkIndicatorDelegate {
func show() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
func hide() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
} | mit | a66305fa0740155d1b6e88d03948f08e | 36.270588 | 285 | 0.711399 | 5.260797 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/common/UIButtonCommon.swift | 1 | 1253 | //
// UIButtonCommon.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/21.
// Copyright © 2016年 suning. All rights reserved.
//
import Foundation
import UIKit
extension UIButton
{
class func createButton(title:String?, bgImgName:String?, highlightImgName:String?, selectImgName:String?, target:AnyObject?, action:Selector) ->UIButton
{
let button = UIButton(type: .Custom)
if let tmpTitle = title
{
button.setTitle(tmpTitle, forState: .Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
if let tmpBgImgName = bgImgName
{
button.setBackgroundImage(UIImage(named: tmpBgImgName), forState: .Normal)
}
if let tmpHighlightImgName = highlightImgName
{
button.setBackgroundImage(UIImage(named: tmpHighlightImgName), forState: .Highlighted)
}
if let tmpSelectImgName = selectImgName
{
button.setBackgroundImage(UIImage(named: tmpSelectImgName), forState: .Selected)
}
if target != nil && action != nil
{
button.addTarget(target, action: action, forControlEvents: .TouchUpInside)
}
return button
}
} | mit | df577aba3053b0399a6398e4e2d846e6 | 28.690476 | 157 | 0.628411 | 4.580882 | false | false | false | false |
Kiandr/CrackingCodingInterview | Swift/Ch 2. Linked Lists/Ch 2. Linked Lists.playground/Sources/RandomIntegerExtensions.swift | 1 | 1593 | //
// RandomIntegerExtensions.swift
//
// Created by Matthew Carroll on 8/17/16.
// Copyright © 2016 Matthew Carroll. All rights reserved.
//
import Foundation
public extension FixedWidthInteger where Stride: SignedInteger {
func arc4random_uniform() -> Self {
precondition(self > 0 && self <= UInt32.max, "\(self) must be in 0..< \(UInt32.max)")
let selfAsStride = -distance(to: 0)
let random = Darwin.arc4random_uniform(numericCast(selfAsStride))
let zero = self - self
let randomAsStride: Stride = numericCast(random)
return zero.advanced(by: randomAsStride)
}
static func arc4random_uniform(upperBound: Self) -> Self {
return upperBound.arc4random_uniform()
}
}
public extension Array where Element: FixedWidthInteger {
init(randomIntUpperBound bound: UInt32, randomIntCount: Int) {
let upperBound = Int(bound)
self = []
let zero: Element = 0
for _ in 0..<randomIntCount {
let randomInt = upperBound.arc4random_uniform()
let element = zero.advanced(by: numericCast(randomInt))
append(element)
}
}
}
public extension String {
init(randomLettersOfCount count: Int) {
let firstAsciiValue = 97
let maxOffset = 5
let range = 0..<count
let characters = range.map { _ -> Character in
let codeUnit = UInt8(maxOffset.arc4random_uniform() + firstAsciiValue)
return Character(UnicodeScalar(codeUnit))
}
self = String(characters)
}
}
| mit | 3419d2b39305750bb10396a1766b8f88 | 27.945455 | 93 | 0.628141 | 4.27957 | false | false | false | false |
CYXiang/CYXSwiftDemo | CYXSwiftDemo/CYXSwiftDemo/Classes/Main/MainAD.swift | 1 | 1089 | //
// MainAD.swift
// CYXSwiftDemo
//
// Created by apple开发 on 16/5/5.
// Copyright © 2016年 cyx. All rights reserved.
//
import UIKit
class MainAD: NSObject, DictModelProtocol {
var code: Int = -1
var msg: String?
var data : AD?
class func loadADData(completion:(data: MainAD?, error: NSError?) -> Void) {
let path = NSBundle.mainBundle().pathForResource("AD", ofType: nil)
let data = NSData(contentsOfFile: path!)
if data != nil {
let dict: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as! NSDictionary
let modelTool = DictModelManager.sharedManager
let data = modelTool.objectWithDictionary(dict, cls: MainAD.self) as? MainAD
completion(data: data, error: nil)
}
}
static func customClassMapping() -> [String : String]? {
return ["data" : "\(AD.self)"]
}
}
/// 模型
class AD: NSObject {
var title: String?
var img_name: String?
var starttime: String?
var endtime: String?
}
| apache-2.0 | 7edbf644a80634d3fe4fb791cb4db274 | 25.95 | 132 | 0.618738 | 3.934307 | false | false | false | false |
SwiftKitz/Datez | Sources/Datez/Services/DiscreteTimer.swift | 1 | 2318 | //
// DiscreteTimer.swift
// Datez
//
// Created by Mazyad Alabduljaleel on 11/30/18.
// Copyright © 2018 kitz. All rights reserved.
//
import Foundation
/** Encapsulates a Timer instance, and only notifies the caller of
changes in the required unit. It also provides the callback with a
date instance that is truncated to only contain the required unit
and greater units. This is to allow equality checks with the
caller's date instances in case they need to be checked against.
e.g.
*/
public final class DiscreteTimer {
// MARK: - nested types
public enum TimeUnit: TimeInterval {
case second = 1
case minute = 60
case hour = 3_600
}
public typealias Callback = (Date) -> ()
// MARK: - properties
private let timeUnit: TimeUnit
private let dateProvider: () -> (Date)
private let callback: Callback
// MARK: - init & deinit
public init(timeUnit: TimeUnit,
dateProvider: @escaping () -> (Date) = Date.init,
callback: @escaping Callback) {
self.timeUnit = timeUnit
self.dateProvider = dateProvider
self.callback = callback
scheduleNextUpdate()
}
@discardableResult
private func scheduleNextUpdate() -> (Date, Int) {
let date = dateProvider()
let timeInterval = date.timeIntervalSince1970
let intervalDelay = timeUnit.rawValue - timeInterval.truncatingRemainder(dividingBy: timeUnit.rawValue)
let currentUnit = Int(timeInterval / timeUnit.rawValue)
DispatchQueue.main.asyncAfter(deadline: .now() + intervalDelay) { [weak self] in
guard let `self` = self else { return }
let (date, nextUnit) = self.scheduleNextUpdate()
guard currentUnit != nextUnit else {
return
}
let dateView: DateView
let now = date.gregorian
switch self.timeUnit {
case .second:
dateView = now.beginningOfSecond
case .minute:
dateView = now.beginningOfMinute
case .hour:
dateView = now.beginningOfHour
}
self.callback(dateView.date)
}
return (date, currentUnit)
}
}
| mit | 33a52069e91b961ca7156eff697ac2ae | 27.604938 | 111 | 0.603366 | 4.827083 | false | false | false | false |
fe9lix/Protium | iOS/Protium/src/gifs/GifGateway.swift | 1 | 3654 | import Foundation
import RxSwift
import RxCocoa
import JASON
typealias GifPage = (offset: Int, limit: Int)
typealias GifList = (items: [Gif], totalCount: Int)
// Protocol that is also implemented by GifStubGateway (see Tests).
// Each methods returns an Observable, which allows for chaining calls, mapping results etc.
protocol GifGate {
func searchGifs(query: String, page: GifPage) -> Observable<GifList>
func fetchTrendingGifs(limit: Int) -> Observable<GifList>
}
enum GifGateError: Error {
case parsingFailed
}
// This Gateway simply uses URLSession and its Rx extension.
// You might want to use your favorite networking stack here...
final class GifGateway: GifGate {
private let reachabilityService: ReachabilityService
private let session: URLSession
private let urlComponents: URLComponents
init(reachabilityService: ReachabilityService) {
self.reachabilityService = reachabilityService
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10.0
session = URLSession(configuration: configuration)
// Base URLs, API Keys etc. would normally be passed in via initialized parameters
// but are hard-coded here for demo purposes.
var urlComponents = URLComponents(string: "https://api.giphy.com/v1/gifs")!
urlComponents.queryItems = [URLQueryItem(name: "api_key", value: "dc6zaTOxFJmzC")]
self.urlComponents = urlComponents
}
// MARK: - Public API
func searchGifs(query: String, page: GifPage) -> Observable<GifList> {
return fetchGifs(path: "/search", params: ["q": query], page: page)
}
func fetchTrendingGifs(limit: Int) -> Observable<GifList> {
return fetchGifs(path: "/trending", params: [:], page: (offset: 0, limit: limit))
}
// MARK: - Private Methods
// Fetches a page of gifs. The JSON response is parsed into Model objects and wrapped in an Observable.
private func fetchGifs(path: String, params: [String: String], page: GifPage) -> Observable<GifList> {
var urlParams = params
urlParams["offset"] = String(page.offset)
urlParams["limit"] = String(page.limit)
return json(url(path: path, params: urlParams)) { json in
let items = json["data"].map(Gif.init)
let pagination = json["pagination"]
let totalCount = (pagination["total_count"].int ?? pagination["count"].int) ?? items.count
return (items, totalCount)
}
}
// Performs the actual call on URLSession, retries on failure and performs the parsing on a background queue.
private func json<T>(_ url: URL, parse: @escaping (JSON) -> T?) -> Observable<T> {
return session.rx
.json(url: url)
.retry(1)
.retryOnBecomesReachable(url, reachabilityService: reachabilityService)
.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.map { result in
guard let model = parse(JSON(result)) else { throw GifGateError.parsingFailed }
return model
}
}
// Constructs the complete URL based on the base url components, the path, and params for the query string.
private func url(path: String, params: [String: String]) -> URL {
var components = urlComponents
components.path += path
let queryItems = params.map { keyValue in URLQueryItem(name: keyValue.0, value: keyValue.1) }
components.queryItems = queryItems + components.queryItems!
return components.url!
}
}
| mit | 7c0ba6b6117ec9466f62cc7bf584733a | 40.522727 | 113 | 0.664477 | 4.561798 | false | true | false | false |
meteochu/Alamofire | Source/Validation.swift | 1 | 8579 | //
// Validation.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Request {
/**
Used to represent whether validation was successful or encountered an error resulting in a failure.
- Success: The validation was successful.
- Failure: The validation failed encountering the provided error.
*/
public enum ValidationResult {
case Success
case Failure(NSError)
}
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the
request was valid.
*/
public typealias Validation = (URLRequest?, HTTPURLResponse) -> ValidationResult
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter validation: A closure to validate the request.
- returns: The request.
*/
public func validate(validation: Validation) -> Self {
delegate.queue.addOperation {
if let
response = self.response where self.delegate.error == nil,
case let .Failure(error) = validation(self.request, response)
{
self.delegate.error = error
}
}
return self
}
// MARK: - Status Code
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter range: The range of acceptable status codes.
- returns: The request.
*/
public func validate<S: Sequence where S.Iterator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
return validate { _, response in
if acceptableStatusCode.contains(response.statusCode) {
return .Success
} else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
let error = NSError(
domain: Error.Domain,
code: Error.Code.StatusCodeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.StatusCode: response.statusCode
]
)
return .Failure(error)
}
}
}
public func validate(statusCode acceptableStatusCode: Range<Int>) -> Self {
return validate { _, response in
if acceptableStatusCode.contains(response.statusCode) {
return .Success
} else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
let error = NSError(
domain: Error.Domain,
code: Error.Code.StatusCodeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.StatusCode: response.statusCode
]
)
return .Failure(error)
}
}
}
// MARK: - Content-Type
private struct MIMEType {
let type: String
let subtype: String
init?(_ string: String) {
let components: [String] = {
let stripped = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
return split.components(separatedBy: "/")
}()
if let
type = components.first,
subtype = components.last
{
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
return true
default:
return false
}
}
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
- returns: The request.
*/
public func validate<S : Sequence where S.Iterator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
guard let validData = self.delegate.data where validData.count > 0 else { return .Success }
if let
responseContentType = response.mimeType,
responseMIMEType = MIMEType(responseContentType)
{
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(MIME: responseMIMEType) {
return .Success
}
}
} else {
for contentType in acceptableContentTypes {
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
return .Success
}
}
}
let contentType: String
let failureReason: String
if let responseContentType = response.mimeType {
contentType = responseContentType
failureReason = (
"Response content type \"\(responseContentType)\" does not match any acceptable " +
"content types: \(acceptableContentTypes)"
)
} else {
contentType = ""
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
}
let error = NSError(
domain: Error.Domain,
code: Error.Code.ContentTypeValidationFailed.rawValue,
userInfo: [
NSLocalizedFailureReasonErrorKey: failureReason,
Error.UserInfoKeys.ContentType: contentType
]
)
return .Failure(error)
}
}
// MARK: - Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content
type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
- returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = request?.value(forHTTPHeaderField: "Accept") {
return accept.components(separatedBy: ",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
| mit | 01f1e20e346aecd317efe901d90020b2 | 35.506383 | 128 | 0.584217 | 5.677697 | false | false | false | false |
HwwDaDa/WeiBo_swift | WeiBo/WeiBo/Classes/View/Home/HWBHomeViewController.swift | 1 | 2418 | //
// HWBHomeViewController.swift
// WeiBo
//
// Created by Admin on 2017/6/15.
// Copyright © 2017年 Admin. All rights reserved.
//
import UIKit
//定义全局的敞亮,不然到处可以访问
private let cellId = "cellId"
private var statusList = [String]()
class HWBHomeViewController: HWBBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// 加载数据
override func loadData() {
// 在swift中GCD有了很大的变化,这个变化就是我们需要用队列调用,在尾随闭包回调的时候必须用self
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
for i in 0..<15 {
if self.isPullup{
statusList.append("上啦 \(i)")
}else{
//每次将数据插入到顶部
statusList.insert(i.description, at: 0)
}
}
self.refreshControl?.endRefreshing()
// 完事后恢复上拉刷新
self.isPullup = false
// 刷新tableView
self.tableView?.reloadData()
}
}
/// 显示好友
func showFriend() {
print("好友")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// 表格数据源方法
extension HWBHomeViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statusList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//取cell
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
cell.textLabel?.text = statusList[indexPath.row]
return cell
}
}
extension HWBHomeViewController{
//重写父类的方法
override func setupUI() {
super.setupUI()
//导航栏的设置
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriend))
tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
}
| mit | a974778aff12b293e499de73ac101ff0 | 21.608247 | 130 | 0.54902 | 4.84106 | false | false | false | false |
mactive/rw-courses-note | AdvancedSwift3/SwiftAlgorithm.playground/Contents.swift | 1 | 2591 | //: Playground - noun: a place where people can play
import UIKit
import Foundation
var str = "Hello, playground"
class Node<T> {
var value: T
var children: [Node] = [] // add the children property
weak var parent: Node? // add parent property
init(value: T) {
self.value = value
}
func add(child: Node) {
children.append(child)
child.parent = self
}
}
extension Node: CustomStringConvertible {
var description: String {
var text = "\(value)"
if !children.isEmpty {
text += " { \n" + children.map{$0.description}.joined(separator: ", \n") + "\n} "
}
return text
}
}
extension Node where T: Equatable {
// 1
func search(value: T) -> Node? {
// 2
if value == self.value {
return self
}
// 3
for child in children {
if let found = child.search(value: value) {
return found
}
}
// 4
return nil
}
}
extension Node {
var depth: Int {
get {
var level: Int = 1
for child in children {
if !child.children.isEmpty {
level += child.depth
}
}
return level
}
}
var leafCount: Int {
var _count = 0
for child in children {
if !child.children.isEmpty {
_count += child.leafCount
} else {
_count += 1
}
}
return _count
}
var nodeCount: Int {
var _count = 0
for child in children {
if !child.children.isEmpty {
_count += child.nodeCount
}
_count += 1
}
return _count
}
}
let beverages = Node(value: "beverages")
let hotBeverage = Node(value: "hot")
let coldBeverage = Node(value: "cold")
let tea = Node(value: "tea")
let coffee = Node(value: "coffee")
let cocoa = Node(value: "cocoa")
let blackTea = Node(value: "black")
let greenTea = Node(value: "green")
let chaiTea = Node(value: "chai")
let soda = Node(value: "soda")
let milk = Node(value: "milk")
let gingerAle = Node(value: "ginger ale")
let bitterLemon = Node(value: "bitter lemon")
beverages.add(child: hotBeverage)
beverages.add(child: coldBeverage)
hotBeverage.add(child: tea)
hotBeverage.add(child: coffee)
hotBeverage.add(child: cocoa)
coldBeverage.add(child: soda)
coldBeverage.add(child: milk)
tea.add(child: blackTea)
tea.add(child: greenTea)
tea.add(child: chaiTea)
soda.add(child: gingerAle)
soda.add(child: bitterLemon)
print(beverages)
let found = beverages.search(value: "ginger ale")!
print(found)
print(beverages.leafCount,beverages.nodeCount)
print(coldBeverage.leafCount,coldBeverage.nodeCount)
| mit | 7910864b23a274f3bd3313d65c0c39a9 | 18.192593 | 87 | 0.615978 | 3.23875 | false | false | false | false |
Davidde94/StemCode_iOS | StemCode/StemCode/Code/View Controllers/Setup/SetupNameViewController.swift | 1 | 3246 | //
// SetupNameViewController.swift
// StemCode
//
// Created by David Evans on 07/06/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import UIKit
import StemKit
class SetupNameViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var nameTextField: UITextField!
@IBOutlet var finishedButton: UIButton!
@IBOutlet var finishBottomConstraint: NSLayoutConstraint!
var keyboardObserver: NSObjectProtocol?
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupKeyboardManagement()
}
deinit {
NotificationCenter.default.removeObserver(keyboardObserver as Any)
}
@IBAction func finish() {
guard let nameText = nameTextField.text, isNameTextValid(nameText) else {
return
}
AppState.shared.userInfo.name = nameText
AppState.shared.setupVersion = 1
AppState.shared.saveToDefaults()
dismiss()
}
func isNameTextValid(_ text: String) -> Bool {
let regex = try! NSRegularExpression(pattern: "([a-zA-Z0-9]+[a-zA-Z0-9 ]*[a-zA-Z0-9]+)", options: .init(rawValue: 0))
let matches = regex.matches(in: text, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: text.count))
return matches.count > 0
}
// MARK: -
@IBAction func textFieldChangedText(_ sender: UITextField) {
let text = sender.text ?? ""
if text.count > 0 {
sender.textAlignment = .center
} else {
sender.textAlignment = .left
}
finishedButton.isEnabled = isNameTextValid(text)
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
finish()
return true
}
// MARK: - Keyboard management
func setupKeyboardManagement() {
keyboardObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: nil) { (notification) in
self.keyboardWillChangeFrame(notification: notification)
}
}
func keyboardWillChangeFrame(notification: Notification) {
guard
let userInfo = notification.userInfo,
let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
let rawAnimationCurve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt,
let animationTime = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double,
let window = UIApplication.shared.keyWindow else {
return
}
let convertedFrame = view.convert(frame, from: window.coordinateSpace)
let yValue = view.frame.size.height - convertedFrame.origin.y
finishBottomConstraint.constant = yValue + 20.0
let animationCurve = UIView.AnimationOptions(rawValue: rawAnimationCurve)
UIView.animate(withDuration: animationTime, delay: 0, options: [.beginFromCurrentState, animationCurve], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
| mit | 4c11c2144b2d3e06de5650917cadebbd | 31.128713 | 168 | 0.670878 | 4.931611 | false | false | false | false |
jjatie/Charts | Source/Charts/Formatters/DefaultAxisValueFormatter.swift | 1 | 2029 | //
// DefaultAxisValueFormatter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class DefaultAxisValueFormatter: AxisValueFormatter {
public typealias Block = (
_ value: Double,
_ axis: AxisBase?
) -> String
open var block: Block?
open var hasAutoDecimals: Bool = false
private var _formatter: NumberFormatter?
open var formatter: NumberFormatter? {
get { return _formatter }
set {
hasAutoDecimals = false
_formatter = newValue
}
}
// TODO: Documentation. Especially the nil case
private var _decimals: Int?
open var decimals: Int? {
get { return _decimals }
set {
_decimals = newValue
if let digits = newValue {
formatter?.minimumFractionDigits = digits
formatter?.maximumFractionDigits = digits
formatter?.usesGroupingSeparator = true
}
}
}
public init() {
formatter = NumberFormatter()
hasAutoDecimals = true
}
public init(formatter: NumberFormatter) {
self.formatter = formatter
}
public init(decimals: Int) {
formatter = NumberFormatter()
formatter?.usesGroupingSeparator = true
self.decimals = decimals
hasAutoDecimals = true
}
public init(block: @escaping Block) {
self.block = block
}
public static func with(block: @escaping Block) -> DefaultAxisValueFormatter? {
return DefaultAxisValueFormatter(block: block)
}
open func stringForValue(_ value: Double,
axis: AxisBase?) -> String
{
if let block = block {
return block(value, axis)
} else {
return formatter?.string(from: NSNumber(floatLiteral: value)) ?? ""
}
}
}
| apache-2.0 | 7a09926914b3134ecd3c5ca646897322 | 24.049383 | 83 | 0.59241 | 5.0725 | false | false | false | false |
knutigro/AppReviews | AppReviewsTests/ItunesUrlHandlerTest.swift | 1 | 2251 | //
// ItunesUrlHandlerTest.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-05-15.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import Foundation
import Cocoa
import XCTest
import SwiftyJSON
class ItunesUrlHandlerTest: XCTestCase {
var urlHandler: ItunesUrlHandler!
let kInitialUrl = "https://itunes.apple.com/rss/customerreviews/id=123/json"
var reviewJSON: JSON?
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
urlHandler = ItunesUrlHandler(apId: "123", storeId: nil)
if let path = NSBundle(forClass: ItunesUrlHandlerTest.self).pathForResource("reviews", ofType: "json") {
do {
let string = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
if let dataFromString = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
reviewJSON = JSON(data: dataFromString)
}
} catch {
XCTFail("contentsOfFile did fail")
}
}
XCTAssertNotNil(reviewJSON)
}
func testIfFeedExist() {
guard let reviewJSON = self.reviewJSON else {
return
}
XCTAssertNotNil(reviewJSON.itunesFeed)
}
func testIfReviewsExist() {
guard let reviewJSON = self.reviewJSON else {
return
}
XCTAssertNotNil(reviewJSON.itunesReviews)
XCTAssertGreaterThan(reviewJSON.itunesReviews.count, 0)
}
func testIfLinkExist() {
guard let reviewJSON = self.reviewJSON else {
return
}
XCTAssertGreaterThan(reviewJSON.itunesFeedLinks.count, 0)
}
func testInitialUrl() {
// pages.append(ItunesPage(url: initialUrl, page: 0))
XCTAssertEqual(urlHandler.initialUrl, kInitialUrl, "There should be inital url")
}
func testPrecedingUrlUrl() {
// if let json = json {
// urlHandler.updateWithJSON(json["feed"]["link"].arrayValue)
// } else {
// }
print("nextUrl \(urlHandler.nextUrl)")
}
}
| gpl-3.0 | 876e71096c4fc0f8058dac89f762d949 | 27.858974 | 117 | 0.611284 | 4.603272 | false | true | false | false |
wscqs/FMDemo- | FMDemo/Classes/Common/View/BorderTextView.swift | 1 | 3608 | //
// QSTextView.swift
// ban
//
// Created by mba on 16/7/22.
// Copyright © 2016年 mbalib. All rights reserved.
//
//编辑页与用户提问页的TextView
import UIKit
import Foundation
//http://www.cnblogs.com/xiaofeixiang/p/4509665.html?utm_source=tuicool&utm_medium=referral oc 版
let padding: CGFloat = 8
class BorderTextView: UITextView {
func setPlaceholder(_ placeholder: String, maxTip: Int) {
text = ""
placeholderLabel.text = placeholder
maxTipLength = maxTip
textChanged()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setUI()
}
required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
setUI()
}
override func awakeFromNib() {
super.awakeFromNib()
setUI()
}
func setUI() {
setParam()
addSubview(placeholderLabel)
// addSubview(tipLabel)
font = UIFont.systemFont(ofSize: 14)
NotificationCenter.default.addObserver(self, selector: #selector(BorderTextView.textChanged), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
let tipLabelW: CGFloat = 40
tipLabel.frame = CGRect(x: self.width - tipLabelW, y: self.height - 20 , width: tipLabelW, height: 10)
placeholderLabel.frame = CGRect(x: padding + 1, y: padding, width: self.width - padding * 2, height: self.height)
placeholderLabel.sizeToFit()
}
func setParam() {
textContainerInset = UIEdgeInsets(top: padding , left: padding, bottom: 0, right: padding-2)
text = ""
layer.cornerRadius = 10
layer.masksToBounds = true
layer.borderWidth = 1
layer.borderColor = UIColor.colorWithHexString("e2e5e8").cgColor
// backgroundColor = UIColor.colorWithHexString("f3f5fa")
}
override var text: String!{
didSet{
textChanged()
}
}
fileprivate lazy var placeholderLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = UIColor.colorWithHexString("a8a7a7")
label.numberOfLines = 0
return label
}()
fileprivate lazy var tipLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 10)
label.textColor = UIColor.lightGray
label.text = "\(self.maxTipLength)/\(self.maxTipLength)"
label.sizeToFit()
return label
}()
var maxTipLength = 10
@objc fileprivate func textChanged() {
placeholderLabel.isHidden = self.hasText
// 当前已经输入的内容长度
let count = self.text.characters.count
let res = maxTipLength - count
if res >= 0 {
tipLabel.textColor = UIColor.lightGray
tipLabel.text = "\(res)/\(maxTipLength)"
}else {
text = (text as NSString).substring(to: maxTipLength)
tipLabel.text = "0/\(maxTipLength)"
// tipLabel.textColor = UIColor.redColor()
}
}
var clearBorder: Bool? {
didSet{
if clearBorder ?? false {
layer.borderWidth = 0
layer.borderColor = UIColor.clear.cgColor
}
}
}
}
| apache-2.0 | 9c43bcaeaacc7b8f1c36ee0c3a92b4ba | 26.820313 | 165 | 0.589722 | 4.530534 | false | false | false | false |
eonil/prototype-signet.swift | Sources/Relay.swift | 1 | 1369 | //
// Relay.swift
// TransmitterExperiment1
//
// Created by Hoon H. on 2017/05/28.
// Copyright © 2017 Eonil. All rights reserved.
//
///
/// State-less signal delivery.
///
public class Relay<T> {
public var delegate: ((T) -> Void)?
private var receptors = [ObjectIdentifier: (T) -> Void]()
private var unwatchImpl: (() -> Void)?
public init() {}
deinit {
unwatchImpl?()
}
public func cast(_ signal: T) {
delegate?(signal)
for receptor in receptors.values {
receptor(signal)
}
}
public func watch(_ source: Relay<T>) {
watch(source) { $0 }
}
public func watch<S>(_ source: Relay<S>, with map: @escaping (S) -> T) {
let selfID = ObjectIdentifier(self)
weak var ss = self
source.registerReceptor(selfID) { s in
guard let ss = ss else { return }
ss.cast(map(s))
}
unwatchImpl = { [weak source] in
guard let source = source else { return }
source.deregisterReceptor(selfID)
}
}
public func unwatch() {
unwatchImpl?()
}
private func registerReceptor(_ id: ObjectIdentifier, _ function: @escaping (T) -> Void) {
receptors[id] = function
}
private func deregisterReceptor(_ id: ObjectIdentifier) {
receptors[id] = nil
}
}
| mit | 79a9150158f2e50623387c7aef87c78b | 25.307692 | 94 | 0.561404 | 3.737705 | false | false | false | false |
corin8823/SwiftyExtensions | SwiftyExtensions/NSMutableAttributedString+Addtions.swift | 1 | 1002 | //
// NSMutableAttributedString+Addtions.swift
// SwiftyExtensions
//
// Created by yusuke takahashi on 8/2/15.
// Copyright (c) 2015 yusuke takahashi. All rights reserved.
//
import UIKit
extension NSMutableAttributedString {
public convenience init(string: String, image: UIImage?, point: CGPoint = CGPointZero, index: Int = 0) {
self.init(string: string)
if let image = image {
let textAttachment = NSTextAttachment()
textAttachment.image = image
textAttachment.bounds = CGRect(origin: point, size: image.size)
let ns = NSAttributedString(attachment: textAttachment)
self.insertAttributedString(ns, atIndex: index)
}
}
public convenience init(string: String, lineHeight: CGFloat) {
self.init(string: string)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.maximumLineHeight = lineHeight
self.addAttribute(NSParagraphStyleAttributeName,
value: paragraphStyle,
range: NSMakeRange(0, self.length))
}
}
| mit | dec3f6c64623f1d4982bd047e1378f47 | 30.3125 | 106 | 0.721557 | 4.533937 | false | false | false | false |
frtlupsvn/Vietnam-To-Go | Pods/Former/Former/Cells/FormTextFieldCell.swift | 1 | 3128 | //
// FormTextFieldCell.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/25/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public class FormTextFieldCell: FormCell, TextFieldFormableRow {
// MARK: Public
public private(set) weak var textField: UITextField!
public private(set) weak var titleLabel: UILabel!
public func formTextField() -> UITextField {
return textField
}
public func formTitleLabel() -> UILabel? {
return titleLabel
}
public override func updateWithRowFormer(rowFormer: RowFormer) {
super.updateWithRowFormer(rowFormer)
leftConst.constant = titleLabel.text?.isEmpty ?? true ? 5 : 15
rightConst.constant = (textField.textAlignment == .Right) ? -15 : 0
}
public override func setup() {
super.setup()
let titleLabel = UILabel()
titleLabel.setContentHuggingPriority(500, forAxis: UILayoutConstraintAxis.Horizontal)
titleLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(titleLabel, atIndex: 0)
self.titleLabel = titleLabel
let textField = UITextField()
textField.backgroundColor = .clearColor()
textField.clearButtonMode = .WhileEditing
textField.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(textField, atIndex: 0)
self.textField = textField
let constraints = [
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[label]-0-|",
options: [],
metrics: nil,
views: ["label": titleLabel]
),
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[field]-0-|",
options: [],
metrics: nil,
views: ["field": textField]
),
NSLayoutConstraint.constraintsWithVisualFormat(
"H:[label]-10-[field]",
options: [],
metrics: nil,
views: ["label": titleLabel, "field": textField]
)
].flatMap { $0 }
let leftConst = NSLayoutConstraint(
item: titleLabel,
attribute: .Leading,
relatedBy: .Equal,
toItem: contentView,
attribute: .Leading,
multiplier: 1,
constant: 15
)
let rightConst = NSLayoutConstraint(
item: textField,
attribute: .Trailing,
relatedBy: .Equal,
toItem: contentView,
attribute: .Trailing,
multiplier: 1,
constant: 0
)
contentView.addConstraints(constraints + [leftConst, rightConst])
self.leftConst = leftConst
self.rightConst = rightConst
}
// MARK: Private
private weak var leftConst: NSLayoutConstraint!
private weak var rightConst: NSLayoutConstraint!
} | mit | 4fbb142e2272800c00e14d9c8ce26e18 | 31.247423 | 93 | 0.584586 | 5.644404 | false | false | false | false |
UsrNameu1/VIPER-SWIFT | VIPER-SWIFT/Classes/Modules/List/User Interface/Presenter/UpcomingDisplaySection.swift | 1 | 756 |
//
// UpcomingDisplaySection.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/5/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
struct UpcomingDisplaySection : Equatable {
let name : String = ""
let imageName : String = ""
var items : [UpcomingDisplayItem] = []
init(name: String, imageName: String, items: [UpcomingDisplayItem]?) {
self.name = name
self.imageName = imageName
if items != nil {
self.items = items!
}
}
}
func == (leftSide: UpcomingDisplaySection, rightSide: UpcomingDisplaySection) -> Bool {
var hasEqualSections = false
hasEqualSections = rightSide.items == leftSide.items
return hasEqualSections
} | mit | 03dc3705df398f44fa32e05c5fe737da | 23.419355 | 87 | 0.642857 | 4.271186 | false | false | false | false |
m0rb1u5/iOS_10_1 | iOS_10_1/TipoQuesoController.swift | 1 | 933 | //
// TipoQuesoController.swift
// iOS_10_1
//
// Created by Juan Carlos Carbajal Ipenza on 5/04/16.
// Copyright © 2016 Juan Carlos Carbajal Ipenza. All rights reserved.
//
import UIKit
class TipoQuesoController: UIViewController {
var tamanoPizza: String? = nil
var tipoMasa: String? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.title="Tipo de Queso"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let boton = sender as! UIButton
let resultado: String = boton.titleLabel!.text!
print(resultado)
let sigVista = segue.destinationViewController as! IngredientesController
sigVista.tamanoPizza = self.tamanoPizza
sigVista.tipoMasa = self.tipoMasa
sigVista.tipoQueso = resultado
}
}
| gpl-3.0 | d31d691bcbe46ab834f928231243058e | 29.064516 | 81 | 0.678112 | 4.017241 | false | false | false | false |
huonw/swift | test/IRGen/generic_vtable.swift | 1 | 5738 | // RUN: %empty-directory(%t)
// RUN: %{python} %utils/chex.py < %s > %t/generic_vtable.swift
// RUN: %target-swift-frontend %t/generic_vtable.swift -emit-ir | %FileCheck %t/generic_vtable.swift --check-prefix=CHECK
// REQUIRES: CPU=x86_64
public class Base {
public func m1() {}
public func m2() {}
}
public class Derived<T> : Base {
public override func m2() {}
public func m3() {}
}
public class Concrete : Derived<Int> {
public override func m3() {}
public func m4() {}
}
//// Nominal type descriptor for 'Base' does not have any method descriptors.
// CHECK-LABEL: @"$S14generic_vtable4BaseCMn" = {{(dllexport )?}}{{(protected )?}}constant
// -- flags: has vtable, reflectable, is class, is unique
// CHECK-SAME: <i32 0x8004_0050>,
// -- vtable offset
// CHECK-SAME: i32 10,
// -- vtable size
// CHECK-SAME: i32 3
// -- no method descriptors -- class is fully concrete
// CHECK-SAME: section "{{.*}}", align 4
//// Type metadata for 'Base' has a static vtable.
// CHECK-LABEL: @"$S14generic_vtable4BaseCMf" = internal global
// -- vtable entry for 'm1()'
// CHECK-SAME: void (%T14generic_vtable4BaseC*)* @"$S14generic_vtable4BaseC2m1yyF"
// -- vtable entry for 'm2()'
// CHECK-SAME: void (%T14generic_vtable4BaseC*)* @"$S14generic_vtable4BaseC2m2yyF"
// -- vtable entry for 'init()'
// CHECK-SAME: %T14generic_vtable4BaseC* (%T14generic_vtable4BaseC*)* @"$S14generic_vtable4BaseCACycfc"
// --
// CHECK-SAME: , align 8
//// Nominal type descriptor for 'Derived' has method descriptors.
// CHECK-LABEL: @"$S14generic_vtable7DerivedCMn" = {{(dllexport )?}}{{(protected )?}}constant
// -- flags: has vtable, reflectable, is class, is unique, is generic
// CHECK-SAME: <i32 0x8004_00D0>,
// -- vtable offset
// CHECK-SAME: i32 14,
// -- vtable size
// CHECK-SAME: i32 1,
// -- vtable entry for m3()
// CHECK-SAME: void (%T14generic_vtable7DerivedC*)* @"$S14generic_vtable7DerivedC2m3yyF"
// --
// CHECK-SAME: section "{{.*}}", align 4
//// Type metadata pattern for 'Derived' has an empty vtable, filled in at
//// instantiation time.
// CHECK-LABEL: @"$S14generic_vtable7DerivedCMP" = internal constant <{{.*}}> <{
// -- ivar destroyer
// CHECK-SAME: i32 0
// --
// CHECK-SAME: }>, align 8
//// Nominal type descriptor for 'Concrete' has method descriptors.
// CHECK-LABEL: @"$S14generic_vtable8ConcreteCMn" = {{(dllexport )?}}{{(protected )?}}constant
// -- flags: has vtable, reflectable, is class, is unique
// CHECK-SAME: <i32 0x8004_0050>,
// -- vtable offset
// CHECK-SAME: i32 15,
// -- vtable size
// CHECK-SAME: i32 1,
// -- vtable entry for m4()
// CHECK-SAME: void (%T14generic_vtable8ConcreteC*)* @"$S14generic_vtable8ConcreteC2m4yyF"
// --
// CHECK-SAME: section "{{.*}}", align 4
//// Type metadata for 'Concrete' does not have any vtable entries; the vtable is
//// filled in at initialization time.
// CHECK-LABEL: @"$S14generic_vtable8ConcreteCMf" = internal global <{{.*}}> <{
// -- nominal type descriptor
// CHECK-SAME: @"$S14generic_vtable8ConcreteCMn",
// -- ivar destroyer
// CHECK-SAME: i8* null
// --
// CHECK-SAME: }>, align 8
//// Metadata initialization function for 'Derived' copies superclass vtable
//// and installs overrides for 'm2()' and 'init()'.
// CHECK-LABEL: define internal %swift.type* @"$S14generic_vtable7DerivedCMi"(%swift.type_descriptor*, i8**, i8**)
// - 2 immediate members:
// - type metadata for generic parameter T,
// - and vtable entry for 'm3()'
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8** %2)
// CHECK: ret %swift.type* [[METADATA]]
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$S14generic_vtable7DerivedCMr"
// CHECK-SAME: (%swift.type* [[METADATA:%.*]], i8*, i8**) {{.*}} {
// CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], i64 0, {{.*}})
// -- method override for 'm2()'
// CHECK: [[WORDS:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[VTABLE0:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i64 11
// CHECK: store i8* bitcast (void (%T14generic_vtable7DerivedC*)* @"$S14generic_vtable7DerivedC2m2yyF" to i8*), i8** [[VTABLE0]], align 8
// -- method override for 'init()'
// CHECK: [[WORDS:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[VTABLE1:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i64 12
// CHECK: store i8* bitcast (%T14generic_vtable7DerivedC* (%T14generic_vtable7DerivedC*)* @"$S14generic_vtable7DerivedCACyxGycfc" to i8*), i8** [[VTABLE1]], align 8
// CHECK: ret %swift.metadata_response
//// Metadata initialization function for 'Concrete' copies superclass vtable
//// and installs overrides for 'init()' and 'm3()'.
// CHECK-LABEL: define private void @initialize_metadata_Concrete(i8*)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S14generic_vtable7DerivedCySiGMa"(i64 1)
// CHECK: [[SUPERCLASS:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: store %swift.type* [[SUPERCLASS]], %swift.type** getelementptr inbounds {{.*}} @"$S14generic_vtable8ConcreteCMf"
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, i64 96, i64 1)
// CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], i64 0, {{.*}})
// -- method override for 'init()'
// CHECK: store i8* bitcast (%T14generic_vtable8ConcreteC* (%T14generic_vtable8ConcreteC*)* @"$S14generic_vtable8ConcreteCACycfc" to i8*), i8**
// -- method override for 'm3()'
// CHECK: store i8* bitcast (void (%T14generic_vtable8ConcreteC*)* @"$S14generic_vtable8ConcreteC2m3yyF" to i8*), i8**
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @"$S14generic_vtable8ConcreteCML" release, align 8
// CHECK: ret void
| apache-2.0 | ef97e47bb9c8e7118cac21ed3e5a349a | 39.125874 | 164 | 0.669223 | 3.353594 | false | false | false | false |
ludoded/ReceiptBot | Pods/Material/Sources/iOS/FABMenu.swift | 2 | 16605 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(FABMenuDirection)
public enum FABMenuDirection: Int {
case up
case down
case left
case right
}
open class FABMenuItem: View {
/// A reference to the titleLabel.
open let titleLabel = UILabel()
/// A reference to the fabButton.
open let fabButton = FABButton()
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
backgroundColor = nil
prepareFABButton()
prepareTitleLabel()
}
/// A reference to the titleLabel text.
open var title: String? {
get {
return titleLabel.text
}
set(value) {
titleLabel.text = value
layoutSubviews()
}
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let t = title, 0 < t.utf16.count else {
titleLabel.removeFromSuperview()
return
}
if nil == titleLabel.superview {
addSubview(titleLabel)
}
}
}
extension FABMenuItem {
/// Shows the titleLabel.
open func showTitleLabel() {
let interimSpace = InterimSpacePresetToValue(preset: .interimSpace6)
titleLabel.sizeToFit()
titleLabel.width += 1.5 * interimSpace
titleLabel.height += interimSpace / 2
titleLabel.y = (height - titleLabel.height) / 2
titleLabel.x = -titleLabel.width - interimSpace
titleLabel.alpha = 0
titleLabel.isHidden = false
UIView.animate(withDuration: 0.25, animations: { [weak self] in
guard let s = self else {
return
}
s.titleLabel.alpha = 1
})
}
/// Hides the titleLabel.
open func hideTitleLabel() {
titleLabel.isHidden = true
}
}
extension FABMenuItem {
/// Prepares the fabButton.
fileprivate func prepareFABButton() {
layout(fabButton).edges()
}
/// Prepares the titleLabel.
fileprivate func prepareTitleLabel() {
titleLabel.font = RobotoFont.regular(with: 14)
titleLabel.textAlignment = .center
titleLabel.backgroundColor = .white
titleLabel.depthPreset = fabButton.depthPreset
titleLabel.cornerRadiusPreset = .cornerRadius1
}
}
@objc(FABMenuDelegate)
public protocol FABMenuDelegate {
/**
A delegation method that is execited when the fabMenu will open.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuWillOpen(fabMenu: FABMenu)
/**
A delegation method that is execited when the fabMenu did open.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuDidOpen(fabMenu: FABMenu)
/**
A delegation method that is execited when the fabMenu will close.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuWillClose(fabMenu: FABMenu)
/**
A delegation method that is execited when the fabMenu did close.
- Parameter fabMenu: A FABMenu.
*/
@objc
optional func fabMenuDidClose(fabMenu: FABMenu)
/**
A delegation method that is executed when the user taps while
the menu is opened.
- Parameter fabMenu: A FABMenu.
- Parameter tappedAt point: A CGPoint.
- Parameter isOutside: A boolean indicating whether the tap
was outside the menu button area.
*/
@objc
optional func fabMenu(fabMenu: FABMenu, tappedAt point: CGPoint, isOutside: Bool)
}
@objc(FABMenu)
open class FABMenu: View {
/// A reference to the SpringAnimation object.
internal let spring = SpringAnimation()
open var fabMenuDirection: FABMenuDirection {
get {
switch spring.springDirection {
case .up:
return .up
case .down:
return .down
case .left:
return .left
case .right:
return .right
}
}
set(value) {
switch value {
case .up:
spring.springDirection = .up
case .down:
spring.springDirection = .down
case .left:
spring.springDirection = .left
case .right:
spring.springDirection = .right
}
layoutSubviews()
}
}
/// A reference to the base FABButton.
open var fabButton: FABButton? {
didSet {
oldValue?.removeFromSuperview()
guard let v = fabButton else {
return
}
addSubview(v)
v.addTarget(self, action: #selector(handleFABButton(button:)), for: .touchUpInside)
}
}
/// An internal handler for the FABButton.
internal var handleFABButtonCallback: ((UIButton) -> Void)?
/// An internal handler for the open function.
internal var handleOpenCallback: (() -> Void)?
/// An internal handler for the close function.
internal var handleCloseCallback: (() -> Void)?
/// An internal handler for the completion function.
internal var handleCompletionCallback: ((UIView) -> Void)?
/// Size of FABMenuItems.
open var fabMenuItemSize: CGSize {
get {
return spring.itemSize
}
set(value) {
spring.itemSize = value
}
}
/// A preset wrapper around interimSpace.
open var interimSpacePreset: InterimSpacePreset {
get {
return spring.interimSpacePreset
}
set(value) {
spring.interimSpacePreset = value
}
}
/// The space between views.
open var interimSpace: InterimSpace {
get {
return spring.interimSpace
}
set(value) {
spring.interimSpace = value
}
}
/// A boolean indicating if the menu is open or not.
open var isOpened: Bool {
get {
return spring.isOpened
}
set(value) {
spring.isOpened = value
}
}
/// A boolean indicating if the menu is enabled.
open var isEnabled: Bool {
get {
return spring.isEnabled
}
set(value) {
spring.isEnabled = value
}
}
/// An optional delegation handler.
open weak var delegate: FABMenuDelegate?
/// A reference to the FABMenuItems
open var fabMenuItems: [FABMenuItem] {
get {
return spring.views as! [FABMenuItem]
}
set(value) {
for v in spring.views {
v.removeFromSuperview()
}
for v in value {
addSubview(v)
}
spring.views = value
}
}
open override func layoutSubviews() {
super.layoutSubviews()
fabButton?.frame.size = bounds.size
spring.baseSize = bounds.size
}
open override func prepare() {
super.prepare()
backgroundColor = nil
interimSpacePreset = .interimSpace6
}
}
extension FABMenu {
/**
Open the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
open func open(duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
open(isTriggeredByUserInteraction: false, duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
/**
Open the Menu component with animation options.
- Parameter isTriggeredByUserInteraction: A boolean indicating whether the
state was changed by a user interaction, true if yes, false otherwise.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
internal func open(isTriggeredByUserInteraction: Bool, duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
handleOpenCallback?()
if isTriggeredByUserInteraction {
delegate?.fabMenuWillOpen?(fabMenu: self)
}
spring.expand(duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations) { [weak self, isTriggeredByUserInteraction = isTriggeredByUserInteraction, completion = completion] (view) in
guard let s = self else {
return
}
(view as? FABMenuItem)?.showTitleLabel()
if isTriggeredByUserInteraction && view == s.fabMenuItems.last {
s.delegate?.fabMenuDidOpen?(fabMenu: s)
}
completion?(view)
s.handleCompletionCallback?(view)
}
}
/**
Close the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
open func close(duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
close(isTriggeredByUserInteraction: false, duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
/**
Close the Menu component with animation options.
- Parameter isTriggeredByUserInteraction: A boolean indicating whether the
state was changed by a user interaction, true if yes, false otherwise.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
internal func close(isTriggeredByUserInteraction: Bool, duration: TimeInterval = 0.15, delay: TimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
handleCloseCallback?()
if isTriggeredByUserInteraction {
delegate?.fabMenuWillClose?(fabMenu: self)
}
spring.contract(duration: duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations) { [weak self, isTriggeredByUserInteraction = isTriggeredByUserInteraction, completion = completion] (view) in
guard let s = self else {
return
}
(view as? FABMenuItem)?.hideTitleLabel()
if isTriggeredByUserInteraction && view == s.fabMenuItems.last {
s.delegate?.fabMenuDidClose?(fabMenu: s)
}
completion?(view)
s.handleCompletionCallback?(view)
}
}
}
extension FABMenu {
/**
Handles the hit test for the Menu and views outside of the Menu bounds.
- Parameter _ point: A CGPoint.
- Parameter with event: An optional UIEvent.
- Returns: An optional UIView.
*/
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard isOpened, isEnabled else {
return super.hitTest(point, with: event)
}
for v in subviews {
let p = v.convert(point, from: self)
if v.bounds.contains(p) {
delegate?.fabMenu?(fabMenu: self, tappedAt: point, isOutside: false)
return v.hitTest(p, with: event)
}
}
delegate?.fabMenu?(fabMenu: self, tappedAt: point, isOutside: true)
close(isTriggeredByUserInteraction: true)
return super.hitTest(point, with: event)
}
}
extension FABMenu {
/**
Handler to toggle the FABMenu opened or closed.
- Parameter button: A UIButton.
*/
@objc
fileprivate func handleFABButton(button: UIButton) {
guard nil == handleFABButtonCallback else {
handleFABButtonCallback?(button)
return
}
guard isOpened else {
open(isTriggeredByUserInteraction: true)
return
}
close(isTriggeredByUserInteraction: true)
}
}
| lgpl-3.0 | de463dbf3d786888299cdf4bd4e022ed | 34.786638 | 308 | 0.632159 | 5.109231 | false | false | false | false |
Jnosh/swift | test/expr/delayed-ident/static_func.swift | 66 | 906 | // RUN: %target-typecheck-verify-swift
// Simple struct types
struct X1 {
static func create(_ i: Int) -> X1 { }
static func createGeneric<T>(_ d: T) -> X1 { }
static func createMaybe(_ i : Int) -> X1! { }
static func notAFactory(_ i: Int) -> Int { }
}
// Static methods
var x1: X1 = .create(5)
x1 = .createGeneric(3.14159)
// Non-matching data members
x1 = .notAFactory(5) // expected-error{{member 'notAFactory' in 'X1' produces result of type 'Int', but context expects 'X1'}}
// Static methods returning unchecked-optional types
x1 = .createMaybe(5)
// Generic struct types
struct X2<T> {
static func create(_ t: T) -> X2 { }
static func createGeneric<U>(_ t: T, u:U) -> X2 { }
static func createMaybe(_ i : T) -> X2! { }
}
// Static methods
var x2a: X2 = .create(5)
x2a = .createGeneric(5, u: 3.14159)
var x2b: X2 = .createGeneric(5, u: 3.14159)
var x2c: X2 = .createMaybe(5)
| apache-2.0 | 7075e210d394c645d50ff932f67c03dc | 26.454545 | 126 | 0.640177 | 2.796296 | false | false | false | false |
lizhenning87/SwiftZhiHu | SwiftZhiHu/SwiftZhiHu/Haneke/DiskCache.swift | 1 | 7846 | //
// DiskCache.swift
// Haneke
//
// Created by Hermes Pique on 8/10/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import Foundation
public class DiskCache {
public class func basePath() -> String {
let cachesPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
let hanekePathComponent = Haneke.Domain
let basePath = cachesPath.stringByAppendingPathComponent(hanekePathComponent)
// TODO: Do not recaculate basePath value
return basePath
}
public let path : String
public var size : UInt64 = 0
public var capacity : UInt64 = 0 {
didSet {
dispatch_async(self.cacheQueue, {
self.controlCapacity()
})
}
}
public lazy var cacheQueue : dispatch_queue_t = {
let queueName = Haneke.Domain + "." + self.path.lastPathComponent
let cacheQueue = dispatch_queue_create(queueName, nil)
return cacheQueue
}()
public init(path : String, capacity : UInt64 = UINT64_MAX) {
self.path = path
self.capacity = capacity
dispatch_async(self.cacheQueue, {
self.calculateSize()
self.controlCapacity()
})
}
public func setData(getData : @autoclosure () -> NSData?, key : String) {
dispatch_async(cacheQueue, {
self.setDataSync(getData, key: key)
})
}
public func fetchData(key : String, failure fail : ((NSError?) -> ())? = nil, success succeed : (NSData) -> ()) {
dispatch_async(cacheQueue, {
let path = self.pathForKey(key)
var error: NSError? = nil
if let data = NSData(contentsOfFile: path, options: NSDataReadingOptions.allZeros, error: &error) {
dispatch_async(dispatch_get_main_queue(), {
succeed(data)
})
self.updateDiskAccessDateAtPath(path)
} else if let block = fail {
dispatch_async(dispatch_get_main_queue(), {
block(error)
})
}
})
}
public func removeData(key : String) {
dispatch_async(cacheQueue, {
let fileManager = NSFileManager.defaultManager()
let path = self.pathForKey(key)
let attributesOpt : NSDictionary? = fileManager.attributesOfItemAtPath(path, error: nil)
var error: NSError? = nil
let success = fileManager.removeItemAtPath(path, error:&error)
if (success) {
if let attributes = attributesOpt {
self.size -= attributes.fileSize()
}
} else {
NSLog("Failed to remove key \(key) with error \(error!)")
}
})
}
public func removeAllData() {
let fileManager = NSFileManager.defaultManager()
let cachePath = self.path
dispatch_async(cacheQueue, {
var error: NSError? = nil
if let contents = fileManager.contentsOfDirectoryAtPath(cachePath, error: &error) as? [String] {
for pathComponent in contents {
let path = cachePath.stringByAppendingPathComponent(pathComponent)
if !fileManager.removeItemAtPath(path, error: &error) {
NSLog("Failed to remove path \(path) with error \(error!)")
}
}
self.calculateSize()
} else {
NSLog("Failed to list directory with error \(error!)")
}
})
}
public func updateAccessDate(getData : @autoclosure () -> NSData?, key : String) {
dispatch_async(cacheQueue, {
let path = self.pathForKey(key)
let fileManager = NSFileManager.defaultManager()
if (!self.updateDiskAccessDateAtPath(path) && !fileManager.fileExistsAtPath(path)){
let data = getData()
self.setDataSync(data, key: key)
}
})
}
public func pathForKey(key : String) -> String {
var escapedFilename = key.escapedFilename()
let filename = countElements(escapedFilename) < Int(NAME_MAX) ? escapedFilename : key.MD5Filename()
let keyPath = self.path.stringByAppendingPathComponent(filename)
return keyPath
}
// MARK: Private
private func calculateSize() {
let fileManager = NSFileManager.defaultManager()
size = 0
let cachePath = self.path
var error : NSError?
if let contents = fileManager.contentsOfDirectoryAtPath(cachePath, error: &error) as? [String] {
for pathComponent in contents {
let path = cachePath.stringByAppendingPathComponent(pathComponent)
if let attributes : NSDictionary = fileManager.attributesOfItemAtPath(path, error: &error) {
size += attributes.fileSize()
} else {
NSLog("Failed to read file size of \(path) with error \(error!)")
}
}
} else {
NSLog("Failed to list directory with error \(error!)")
}
}
private func controlCapacity() {
if self.size <= self.capacity { return }
let fileManager = NSFileManager.defaultManager()
let cachePath = self.path
fileManager.enumerateContentsOfDirectoryAtPath(cachePath, orderedByProperty: NSURLContentModificationDateKey, ascending: true) { (URL : NSURL, _, inout stop : Bool) -> Void in
if let path = URL.path {
self.removeFileAtPath(path)
stop = self.size <= self.capacity
}
}
}
private func setDataSync(getData : @autoclosure () -> NSData?, key : String) {
let path = self.pathForKey(key)
var error: NSError? = nil
if let data = getData() {
let fileManager = NSFileManager.defaultManager()
let previousAttributes : NSDictionary? = fileManager.attributesOfItemAtPath(path, error: nil)
let success = data.writeToFile(path, options: NSDataWritingOptions.AtomicWrite, error:&error)
if (!success) {
NSLog("Failed to write key \(key) with error \(error!)")
}
if let attributes = previousAttributes {
self.size -= attributes.fileSize()
}
self.size += data.length
self.controlCapacity()
} else {
NSLog("Failed to get data for key \(key)")
}
}
private func updateDiskAccessDateAtPath(path : String) -> Bool {
let fileManager = NSFileManager.defaultManager()
let now = NSDate()
var error : NSError?
let success = fileManager.setAttributes([NSFileModificationDate : now], ofItemAtPath: path, error: &error)
if !success {
NSLog("Failed to update access date with error \(error!)")
}
return success
}
private func removeFileAtPath(path:String) {
var error : NSError?
let fileManager = NSFileManager.defaultManager()
if let attributes : NSDictionary = fileManager.attributesOfItemAtPath(path, error: &error) {
let modificationDate = attributes.fileModificationDate()
NSLog("%@", modificationDate!)
let fileSize = attributes.fileSize()
if fileManager.removeItemAtPath(path, error: &error) {
self.size -= fileSize
} else {
NSLog("Failed to remove file with error \(error)")
}
} else {
NSLog("Failed to remove file with error \(error)")
}
}
}
| apache-2.0 | 204eee6c73fe80f4ab97da5232870bf8 | 36.721154 | 183 | 0.573286 | 5.216755 | false | false | false | false |
wuzer/douyuTV | douyuTV/douyuTV/Class/TabbarViewController/Base/BaseViewController.swift | 1 | 1700 | //
// BaseViewController.swift
// douyuTV
//
// Created by Jefferson on 2016/11/5.
// Copyright © 2016年 Jefferson. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var contentView: UIView?
fileprivate var lastContentOffset: CGFloat = 0
fileprivate lazy var animationImageView: UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage.init(named: "img_loading_1"))
imageView.center = self.view.center
imageView.animationImages = [UIImage.init(named: "img_loading_1")!, UIImage.init(named: "img_loading_2")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
extension BaseViewController {
func setupUI() {
contentView?.isHidden = true
view.addSubview(animationImageView)
animationImageView.startAnimating()
view.backgroundColor = UIColor.white
}
func showHaveDataView() {
animationImageView.stopAnimating()
animationImageView.isHidden = true
contentView?.isHidden = false
}
}
extension BaseViewController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
lastContentOffset = scrollView.contentOffset.y
}
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
}
}
| mit | 75a3104b088ab289e43423e8f740f8bd | 23.594203 | 114 | 0.651738 | 5.353312 | false | false | false | false |
nderkach/FlightKit | Example/Pods/SCLAlertView/SCLAlertView/SCLAlertView.swift | 1 | 35660 | //
// SCLAlertView.swift
// SCLAlertView Example
//
// Created by Viktor Radchenko on 6/5/14.
// Copyright (c) 2014 Viktor Radchenko. All rights reserved.
//
import Foundation
import UIKit
// Pop Up Styles
public enum SCLAlertViewStyle {
case Success, Error, Notice, Warning, Info, Edit, Wait
}
// Action Types
public enum SCLActionType {
case None, Selector, Closure
}
// Button sub-class
public class SCLButton: UIButton {
var actionType = SCLActionType.None
var target:AnyObject!
var selector:Selector!
var action:(()->Void)!
public init() {
super.init(frame: CGRectZero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override public init(frame:CGRect) {
super.init(frame:frame)
}
}
// Allow alerts to be closed/renamed in a chainable manner
// Example: SCLAlertView().showSuccess(self, title: "Test", subTitle: "Value").close()
public class SCLAlertViewResponder {
let alertview: SCLAlertView
// Initialisation and Title/Subtitle/Close functions
public init(alertview: SCLAlertView) {
self.alertview = alertview
}
public func setTitle(title: String) {
self.alertview.labelTitle.text = title
}
public func setSubTitle(subTitle: String) {
self.alertview.viewText.text = subTitle
}
public func close() {
self.alertview.hideView()
}
}
let kCircleHeightBackground: CGFloat = 62.0
// The Main Class
public class SCLAlertView: UIViewController {
let kDefaultShadowOpacity: CGFloat = 0.7
let kCircleTopPosition: CGFloat = -12.0
let kCircleBackgroundTopPosition: CGFloat = -15.0
let kCircleHeight: CGFloat = 56.0
let kCircleIconHeight: CGFloat = 20.0
let kTitleTop:CGFloat = 30.0
let kTitleHeight:CGFloat = 40.0
let kWindowWidth: CGFloat = 240.0
var kWindowHeight: CGFloat = 178.0
var kTextHeight: CGFloat = 90.0
let kTextFieldHeight: CGFloat = 45.0
let kButtonHeight: CGFloat = 45.0
// Font
let kDefaultFont = "HelveticaNeue"
let kButtonFont = "HelveticaNeue-Bold"
// UI Colour
var viewColor = UIColor()
var pressBrightnessFactor = 0.85
// UI Options
public var showCloseButton = true
// Members declaration
var baseView = UIView()
var labelTitle = UILabel()
var viewText = UITextView()
var contentView = UIView()
var circleBG = UIView(frame:CGRect(x:0, y:0, width:kCircleHeightBackground, height:kCircleHeightBackground))
var circleView = UIView()
var circleIconView : UIView?
var durationTimer: NSTimer!
private var inputs = [UITextField]()
private var buttons = [SCLButton]()
private var selfReference: SCLAlertView?
required public init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
required public init() {
super.init(nibName:nil, bundle:nil)
// Set up main view
view.frame = UIScreen.mainScreen().bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kDefaultShadowOpacity)
view.addSubview(baseView)
// Base View
baseView.frame = view.frame
baseView.addSubview(contentView)
// Content View
contentView.backgroundColor = UIColor(white:1, alpha:1)
contentView.layer.cornerRadius = 5
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 0.5
contentView.addSubview(labelTitle)
contentView.addSubview(viewText)
// Circle View
circleBG.backgroundColor = UIColor.whiteColor()
circleBG.layer.cornerRadius = circleBG.frame.size.height / 2
baseView.addSubview(circleBG)
circleBG.addSubview(circleView)
let x = (kCircleHeightBackground - kCircleHeight) / 2
circleView.frame = CGRect(x:x, y:x, width:kCircleHeight, height:kCircleHeight)
circleView.layer.cornerRadius = circleView.frame.size.height / 2
// Title
labelTitle.numberOfLines = 1
labelTitle.textAlignment = .Center
labelTitle.font = UIFont(name: kDefaultFont, size:20)
labelTitle.frame = CGRect(x:12, y:kTitleTop, width: kWindowWidth - 24, height:kTitleHeight)
// View text
viewText.editable = false
viewText.textAlignment = .Center
viewText.textContainerInset = UIEdgeInsetsZero
viewText.textContainer.lineFragmentPadding = 0;
viewText.font = UIFont(name: kDefaultFont, size:14)
// Colours
contentView.backgroundColor = UIColorFromRGB(0xFFFFFF)
labelTitle.textColor = UIColorFromRGB(0x4D4D4D)
viewText.textColor = UIColorFromRGB(0x4D4D4D)
contentView.layer.borderColor = UIColorFromRGB(0xCCCCCC).CGColor
//Gesture Recognizer for tapping outside the textinput
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard"))
tapGesture.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tapGesture)
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let rv = UIApplication.sharedApplication().keyWindow! as UIWindow
let sz = rv.frame.size
// Set background frame
view.frame.size = sz
// computing the right size to use for the textView
let maxHeight = sz.height - 100 // max overall height
var consumedHeight = CGFloat(0)
consumedHeight += kTitleTop + kTitleHeight
consumedHeight += 14
consumedHeight += kButtonHeight * CGFloat(buttons.count)
consumedHeight += kTextFieldHeight * CGFloat(inputs.count)
let maxViewTextHeight = maxHeight - consumedHeight
let viewTextWidth = kWindowWidth - 24
let suggestedViewTextSize = viewText.sizeThatFits(CGSizeMake(viewTextWidth, CGFloat.max))
let viewTextHeight = min(suggestedViewTextSize.height, maxViewTextHeight)
// scroll management
if (suggestedViewTextSize.height > maxViewTextHeight) {
viewText.scrollEnabled = true
} else {
viewText.scrollEnabled = false
}
let windowHeight = consumedHeight + viewTextHeight
// Set frames
var x = (sz.width - kWindowWidth) / 2
var y = (sz.height - windowHeight - (kCircleHeight / 8)) / 2
contentView.frame = CGRect(x:x, y:y, width:kWindowWidth, height:windowHeight)
y -= kCircleHeightBackground * 0.6
x = (sz.width - kCircleHeightBackground) / 2
circleBG.frame = CGRect(x:x, y:y+6, width:kCircleHeightBackground, height:kCircleHeightBackground)
// Subtitle
y = kTitleTop + kTitleHeight
viewText.frame = CGRect(x:12, y:y, width: kWindowWidth - 24, height:kTextHeight)
viewText.frame = CGRect(x:12, y:y, width: viewTextWidth, height:viewTextHeight)
// Text fields
y += viewTextHeight + 14.0
for txt in inputs {
txt.frame = CGRect(x:12, y:y, width:kWindowWidth - 24, height:30)
txt.layer.cornerRadius = 3
y += kTextFieldHeight
}
// Buttons
for btn in buttons {
btn.frame = CGRect(x:12, y:y, width:kWindowWidth - 24, height:35)
btn.layer.cornerRadius = 3
y += kButtonHeight
}
}
override public func touchesEnded(touches:Set<UITouch>, withEvent event:UIEvent?) {
if event?.touchesForView(view)?.count > 0 {
view.endEditing(true)
}
}
public func addTextField(title:String?=nil)->UITextField {
// Update view height
kWindowHeight += kTextFieldHeight
// Add text field
let txt = UITextField()
txt.borderStyle = UITextBorderStyle.RoundedRect
txt.font = UIFont(name:kDefaultFont, size: 14)
txt.autocapitalizationType = UITextAutocapitalizationType.Words
txt.clearButtonMode = UITextFieldViewMode.WhileEditing
txt.layer.masksToBounds = true
txt.layer.borderWidth = 1.0
if title != nil {
txt.placeholder = title!
}
contentView.addSubview(txt)
inputs.append(txt)
return txt
}
public func addButton(title:String, action:()->Void)->SCLButton {
let btn = addButton(title)
btn.actionType = SCLActionType.Closure
btn.action = action
btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside)
btn.addTarget(self, action:Selector("buttonTapDown:"), forControlEvents:[.TouchDown, .TouchDragEnter])
btn.addTarget(self, action:Selector("buttonRelease:"), forControlEvents:[.TouchUpInside, .TouchUpOutside, .TouchCancel, .TouchDragOutside] )
return btn
}
public func addButton(title:String, target:AnyObject, selector:Selector)->SCLButton {
let btn = addButton(title)
btn.actionType = SCLActionType.Selector
btn.target = target
btn.selector = selector
btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside)
btn.addTarget(self, action:Selector("buttonTapDown:"), forControlEvents:[.TouchDown, .TouchDragEnter])
btn.addTarget(self, action:Selector("buttonRelease:"), forControlEvents:[.TouchUpInside, .TouchUpOutside, .TouchCancel, .TouchDragOutside] )
return btn
}
private func addButton(title:String)->SCLButton {
// Update view height
kWindowHeight += kButtonHeight
// Add button
let btn = SCLButton()
btn.layer.masksToBounds = true
btn.setTitle(title, forState: .Normal)
btn.titleLabel?.font = UIFont(name:kButtonFont, size: 14)
contentView.addSubview(btn)
buttons.append(btn)
return btn
}
func buttonTapped(btn:SCLButton) {
if btn.actionType == SCLActionType.Closure {
btn.action()
} else if btn.actionType == SCLActionType.Selector {
let ctrl = UIControl()
ctrl.sendAction(btn.selector, to:btn.target, forEvent:nil)
return
} else {
print("Unknow action type for button")
}
hideView()
}
func buttonTapDown(btn:SCLButton) {
var hue : CGFloat = 0
var saturation : CGFloat = 0
var brightness : CGFloat = 0
var alpha : CGFloat = 0
btn.backgroundColor?.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
//brightness = brightness * CGFloat(pressBrightness)
btn.backgroundColor = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
func buttonRelease(btn:SCLButton) {
btn.backgroundColor = viewColor
}
//Dismiss keyboard when tapped outside textfield
func dismissKeyboard(){
self.view.endEditing(true)
}
// showSuccess(view, title, subTitle)
public func showSuccess(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt=0x22B573, colorTextButton: UInt=0xFFFFFF) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .Success, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
// showError(view, title, subTitle)
public func showError(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt=0xC1272D, colorTextButton: UInt=0xFFFFFF) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .Error, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
// showNotice(view, title, subTitle)
public func showNotice(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt=0x727375, colorTextButton: UInt=0xFFFFFF) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .Notice, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
// showWarning(view, title, subTitle)
public func showWarning(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt=0xFFD110, colorTextButton: UInt=0x000000) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .Warning, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
// showInfo(view, title, subTitle)
public func showInfo(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt=0x2866BF, colorTextButton: UInt=0xFFFFFF) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .Info, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
// showWait(view, title, subTitle)
public func showWait(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt?=0xD62DA5, colorTextButton: UInt=0xFFFFFF) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .Wait, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
public func showEdit(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt=0xA429FF, colorTextButton: UInt=0xFFFFFF) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .Edit, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
// showTitle(view, title, subTitle, style)
public func showTitle(title: String, subTitle: String, style: SCLAlertViewStyle, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0, colorStyle: UInt?, colorTextButton: UInt=0xFFFFFF) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, duration:duration, completeText:closeButtonTitle, style: style, colorStyle: colorStyle, colorTextButton: colorTextButton)
}
// showTitle(view, title, subTitle, duration, style)
public func showTitle(title: String, subTitle: String, duration: NSTimeInterval?, completeText: String?, style: SCLAlertViewStyle, colorStyle: UInt?, colorTextButton: UInt?) -> SCLAlertViewResponder {
selfReference = self
view.alpha = 0
let rv = UIApplication.sharedApplication().keyWindow! as UIWindow
rv.addSubview(view)
view.frame = rv.bounds
baseView.frame = rv.bounds
// Alert colour/icon
viewColor = UIColor()
var iconImage: UIImage?
// Icon style
switch style {
case .Success:
viewColor = UIColorFromRGB(colorStyle!)
iconImage = SCLAlertViewStyleKit.imageOfCheckmark
case .Error:
viewColor = UIColorFromRGB(colorStyle!)
iconImage = SCLAlertViewStyleKit.imageOfCross
case .Notice:
viewColor = UIColorFromRGB(colorStyle!)
iconImage = SCLAlertViewStyleKit.imageOfNotice
case .Warning:
viewColor = UIColorFromRGB(colorStyle!)
iconImage = SCLAlertViewStyleKit.imageOfWarning
case .Info:
viewColor = UIColorFromRGB(colorStyle!)
iconImage = SCLAlertViewStyleKit.imageOfInfo
case .Edit:
viewColor = UIColorFromRGB(colorStyle!)
iconImage = SCLAlertViewStyleKit.imageOfEdit
case .Wait:
viewColor = UIColorFromRGB(colorStyle!)
}
// Title
if !title.isEmpty {
self.labelTitle.text = title
}
// Subtitle
if !subTitle.isEmpty {
viewText.text = subTitle
// Adjust text view size, if necessary
let str = subTitle as NSString
let attr = [NSFontAttributeName:viewText.font ?? UIFont()]
let sz = CGSize(width: kWindowWidth - 24, height:90)
let r = str.boundingRectWithSize(sz, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:attr, context:nil)
let ht = ceil(r.size.height)
if ht < kTextHeight {
kWindowHeight -= (kTextHeight - ht)
kTextHeight = ht
}
}
// Done button
if showCloseButton {
let txt = completeText != nil ? completeText! : "Done"
addButton(txt, target:self, selector:Selector("hideView"))
}
// Alert view colour and images
circleView.backgroundColor = viewColor
// Spinner / icon
if style == .Wait {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
indicator.startAnimating()
circleIconView = indicator
}
else {
circleIconView = UIImageView(image: iconImage!)
}
circleView.addSubview(circleIconView!)
let x = (kCircleHeight - kCircleIconHeight) / 2
circleIconView!.frame = CGRectMake( x, x, kCircleIconHeight, kCircleIconHeight)
for txt in inputs {
txt.layer.borderColor = viewColor.CGColor
}
for btn in buttons {
btn.backgroundColor = viewColor
btn.setTitleColor(UIColorFromRGB(colorTextButton!), forState:UIControlState.Normal)
}
// Adding duration
if duration > 0 {
durationTimer?.invalidate()
durationTimer = NSTimer.scheduledTimerWithTimeInterval(duration!, target: self, selector: Selector("hideView"), userInfo: nil, repeats: false)
}
// Animate in the alert view
self.baseView.frame.origin.y = -400
UIView.animateWithDuration(0.2, animations: {
self.baseView.center.y = rv.center.y + 15
self.view.alpha = 1
}, completion: { finished in
UIView.animateWithDuration(0.2, animations: {
self.baseView.center = rv.center
})
})
// Chainable objects
return SCLAlertViewResponder(alertview: self)
}
// Close SCLAlertView
public func hideView() {
UIView.animateWithDuration(0.2, animations: {
self.view.alpha = 0
}, completion: { finished in
self.view.removeFromSuperview()
self.selfReference = nil
})
}
// Helper function to convert from RGB to UIColor
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
// ------------------------------------
// Icon drawing
// Code generated by PaintCode
// ------------------------------------
class SCLAlertViewStyleKit : NSObject {
// Cache
struct Cache {
static var imageOfCheckmark: UIImage?
static var checkmarkTargets: [AnyObject]?
static var imageOfCross: UIImage?
static var crossTargets: [AnyObject]?
static var imageOfNotice: UIImage?
static var noticeTargets: [AnyObject]?
static var imageOfWarning: UIImage?
static var warningTargets: [AnyObject]?
static var imageOfInfo: UIImage?
static var infoTargets: [AnyObject]?
static var imageOfEdit: UIImage?
static var editTargets: [AnyObject]?
}
// Initialization
/// swift 1.2 abolish func load
// override class func load() {
// }
// Drawing Methods
class func drawCheckmark() {
// Checkmark Shape Drawing
let checkmarkShapePath = UIBezierPath()
checkmarkShapePath.moveToPoint(CGPointMake(73.25, 14.05))
checkmarkShapePath.addCurveToPoint(CGPointMake(64.51, 13.86), controlPoint1: CGPointMake(70.98, 11.44), controlPoint2: CGPointMake(66.78, 11.26))
checkmarkShapePath.addLineToPoint(CGPointMake(27.46, 52))
checkmarkShapePath.addLineToPoint(CGPointMake(15.75, 39.54))
checkmarkShapePath.addCurveToPoint(CGPointMake(6.84, 39.54), controlPoint1: CGPointMake(13.48, 36.93), controlPoint2: CGPointMake(9.28, 36.93))
checkmarkShapePath.addCurveToPoint(CGPointMake(6.84, 49.02), controlPoint1: CGPointMake(4.39, 42.14), controlPoint2: CGPointMake(4.39, 46.42))
checkmarkShapePath.addLineToPoint(CGPointMake(22.91, 66.14))
checkmarkShapePath.addCurveToPoint(CGPointMake(27.28, 68), controlPoint1: CGPointMake(24.14, 67.44), controlPoint2: CGPointMake(25.71, 68))
checkmarkShapePath.addCurveToPoint(CGPointMake(31.65, 66.14), controlPoint1: CGPointMake(28.86, 68), controlPoint2: CGPointMake(30.43, 67.26))
checkmarkShapePath.addLineToPoint(CGPointMake(73.08, 23.35))
checkmarkShapePath.addCurveToPoint(CGPointMake(73.25, 14.05), controlPoint1: CGPointMake(75.52, 20.75), controlPoint2: CGPointMake(75.7, 16.65))
checkmarkShapePath.closePath()
checkmarkShapePath.miterLimit = 4;
UIColor.whiteColor().setFill()
checkmarkShapePath.fill()
}
class func drawCross() {
// Cross Shape Drawing
let crossShapePath = UIBezierPath()
crossShapePath.moveToPoint(CGPointMake(10, 70))
crossShapePath.addLineToPoint(CGPointMake(70, 10))
crossShapePath.moveToPoint(CGPointMake(10, 10))
crossShapePath.addLineToPoint(CGPointMake(70, 70))
crossShapePath.lineCapStyle = CGLineCap.Round;
crossShapePath.lineJoinStyle = CGLineJoin.Round;
UIColor.whiteColor().setStroke()
crossShapePath.lineWidth = 14
crossShapePath.stroke()
}
class func drawNotice() {
// Notice Shape Drawing
let noticeShapePath = UIBezierPath()
noticeShapePath.moveToPoint(CGPointMake(72, 48.54))
noticeShapePath.addLineToPoint(CGPointMake(72, 39.9))
noticeShapePath.addCurveToPoint(CGPointMake(66.38, 34.01), controlPoint1: CGPointMake(72, 36.76), controlPoint2: CGPointMake(69.48, 34.01))
noticeShapePath.addCurveToPoint(CGPointMake(61.53, 35.97), controlPoint1: CGPointMake(64.82, 34.01), controlPoint2: CGPointMake(62.69, 34.8))
noticeShapePath.addCurveToPoint(CGPointMake(60.36, 35.78), controlPoint1: CGPointMake(61.33, 35.97), controlPoint2: CGPointMake(62.3, 35.78))
noticeShapePath.addLineToPoint(CGPointMake(60.36, 33.22))
noticeShapePath.addCurveToPoint(CGPointMake(54.16, 26.16), controlPoint1: CGPointMake(60.36, 29.3), controlPoint2: CGPointMake(57.65, 26.16))
noticeShapePath.addCurveToPoint(CGPointMake(48.73, 29.89), controlPoint1: CGPointMake(51.64, 26.16), controlPoint2: CGPointMake(50.67, 27.73))
noticeShapePath.addLineToPoint(CGPointMake(48.73, 28.71))
noticeShapePath.addCurveToPoint(CGPointMake(43.49, 21.64), controlPoint1: CGPointMake(48.73, 24.78), controlPoint2: CGPointMake(46.98, 21.64))
noticeShapePath.addCurveToPoint(CGPointMake(39.03, 25.37), controlPoint1: CGPointMake(40.97, 21.64), controlPoint2: CGPointMake(39.03, 23.01))
noticeShapePath.addLineToPoint(CGPointMake(39.03, 9.07))
noticeShapePath.addCurveToPoint(CGPointMake(32.24, 2), controlPoint1: CGPointMake(39.03, 5.14), controlPoint2: CGPointMake(35.73, 2))
noticeShapePath.addCurveToPoint(CGPointMake(25.45, 9.07), controlPoint1: CGPointMake(28.56, 2), controlPoint2: CGPointMake(25.45, 5.14))
noticeShapePath.addLineToPoint(CGPointMake(25.45, 41.47))
noticeShapePath.addCurveToPoint(CGPointMake(24.29, 43.44), controlPoint1: CGPointMake(25.45, 42.45), controlPoint2: CGPointMake(24.68, 43.04))
noticeShapePath.addCurveToPoint(CGPointMake(9.55, 43.04), controlPoint1: CGPointMake(16.73, 40.88), controlPoint2: CGPointMake(11.88, 40.69))
noticeShapePath.addCurveToPoint(CGPointMake(8, 46.58), controlPoint1: CGPointMake(8.58, 43.83), controlPoint2: CGPointMake(8, 45.2))
noticeShapePath.addCurveToPoint(CGPointMake(14.4, 55.81), controlPoint1: CGPointMake(8.19, 50.31), controlPoint2: CGPointMake(12.07, 53.84))
noticeShapePath.addLineToPoint(CGPointMake(27.2, 69.56))
noticeShapePath.addCurveToPoint(CGPointMake(42.91, 77.8), controlPoint1: CGPointMake(30.5, 74.47), controlPoint2: CGPointMake(35.73, 77.21))
noticeShapePath.addCurveToPoint(CGPointMake(43.88, 77.8), controlPoint1: CGPointMake(43.3, 77.8), controlPoint2: CGPointMake(43.68, 77.8))
noticeShapePath.addCurveToPoint(CGPointMake(47.18, 78), controlPoint1: CGPointMake(45.04, 77.8), controlPoint2: CGPointMake(46.01, 78))
noticeShapePath.addLineToPoint(CGPointMake(48.34, 78))
noticeShapePath.addLineToPoint(CGPointMake(48.34, 78))
noticeShapePath.addCurveToPoint(CGPointMake(71.61, 52.08), controlPoint1: CGPointMake(56.48, 78), controlPoint2: CGPointMake(69.87, 75.05))
noticeShapePath.addCurveToPoint(CGPointMake(72, 48.54), controlPoint1: CGPointMake(71.81, 51.29), controlPoint2: CGPointMake(72, 49.72))
noticeShapePath.closePath()
noticeShapePath.miterLimit = 4;
UIColor.whiteColor().setFill()
noticeShapePath.fill()
}
class func drawWarning() {
// Color Declarations
let greyColor = UIColor(red: 0.236, green: 0.236, blue: 0.236, alpha: 1.000)
// Warning Group
// Warning Circle Drawing
let warningCirclePath = UIBezierPath()
warningCirclePath.moveToPoint(CGPointMake(40.94, 63.39))
warningCirclePath.addCurveToPoint(CGPointMake(36.03, 65.55), controlPoint1: CGPointMake(39.06, 63.39), controlPoint2: CGPointMake(37.36, 64.18))
warningCirclePath.addCurveToPoint(CGPointMake(34.14, 70.45), controlPoint1: CGPointMake(34.9, 66.92), controlPoint2: CGPointMake(34.14, 68.49))
warningCirclePath.addCurveToPoint(CGPointMake(36.22, 75.54), controlPoint1: CGPointMake(34.14, 72.41), controlPoint2: CGPointMake(34.9, 74.17))
warningCirclePath.addCurveToPoint(CGPointMake(40.94, 77.5), controlPoint1: CGPointMake(37.54, 76.91), controlPoint2: CGPointMake(39.06, 77.5))
warningCirclePath.addCurveToPoint(CGPointMake(45.86, 75.35), controlPoint1: CGPointMake(42.83, 77.5), controlPoint2: CGPointMake(44.53, 76.72))
warningCirclePath.addCurveToPoint(CGPointMake(47.93, 70.45), controlPoint1: CGPointMake(47.18, 74.17), controlPoint2: CGPointMake(47.93, 72.41))
warningCirclePath.addCurveToPoint(CGPointMake(45.86, 65.35), controlPoint1: CGPointMake(47.93, 68.49), controlPoint2: CGPointMake(47.18, 66.72))
warningCirclePath.addCurveToPoint(CGPointMake(40.94, 63.39), controlPoint1: CGPointMake(44.53, 64.18), controlPoint2: CGPointMake(42.83, 63.39))
warningCirclePath.closePath()
warningCirclePath.miterLimit = 4;
greyColor.setFill()
warningCirclePath.fill()
// Warning Shape Drawing
let warningShapePath = UIBezierPath()
warningShapePath.moveToPoint(CGPointMake(46.23, 4.26))
warningShapePath.addCurveToPoint(CGPointMake(40.94, 2.5), controlPoint1: CGPointMake(44.91, 3.09), controlPoint2: CGPointMake(43.02, 2.5))
warningShapePath.addCurveToPoint(CGPointMake(34.71, 4.26), controlPoint1: CGPointMake(38.68, 2.5), controlPoint2: CGPointMake(36.03, 3.09))
warningShapePath.addCurveToPoint(CGPointMake(31.5, 8.77), controlPoint1: CGPointMake(33.01, 5.44), controlPoint2: CGPointMake(31.5, 7.01))
warningShapePath.addLineToPoint(CGPointMake(31.5, 19.36))
warningShapePath.addLineToPoint(CGPointMake(34.71, 54.44))
warningShapePath.addCurveToPoint(CGPointMake(40.38, 58.16), controlPoint1: CGPointMake(34.9, 56.2), controlPoint2: CGPointMake(36.41, 58.16))
warningShapePath.addCurveToPoint(CGPointMake(45.67, 54.44), controlPoint1: CGPointMake(44.34, 58.16), controlPoint2: CGPointMake(45.67, 56.01))
warningShapePath.addLineToPoint(CGPointMake(48.5, 19.36))
warningShapePath.addLineToPoint(CGPointMake(48.5, 8.77))
warningShapePath.addCurveToPoint(CGPointMake(46.23, 4.26), controlPoint1: CGPointMake(48.5, 7.01), controlPoint2: CGPointMake(47.74, 5.44))
warningShapePath.closePath()
warningShapePath.miterLimit = 4;
greyColor.setFill()
warningShapePath.fill()
}
class func drawInfo() {
// Color Declarations
let color0 = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
// Info Shape Drawing
let infoShapePath = UIBezierPath()
infoShapePath.moveToPoint(CGPointMake(45.66, 15.96))
infoShapePath.addCurveToPoint(CGPointMake(45.66, 5.22), controlPoint1: CGPointMake(48.78, 12.99), controlPoint2: CGPointMake(48.78, 8.19))
infoShapePath.addCurveToPoint(CGPointMake(34.34, 5.22), controlPoint1: CGPointMake(42.53, 2.26), controlPoint2: CGPointMake(37.47, 2.26))
infoShapePath.addCurveToPoint(CGPointMake(34.34, 15.96), controlPoint1: CGPointMake(31.22, 8.19), controlPoint2: CGPointMake(31.22, 12.99))
infoShapePath.addCurveToPoint(CGPointMake(45.66, 15.96), controlPoint1: CGPointMake(37.47, 18.92), controlPoint2: CGPointMake(42.53, 18.92))
infoShapePath.closePath()
infoShapePath.moveToPoint(CGPointMake(48, 69.41))
infoShapePath.addCurveToPoint(CGPointMake(40, 77), controlPoint1: CGPointMake(48, 73.58), controlPoint2: CGPointMake(44.4, 77))
infoShapePath.addLineToPoint(CGPointMake(40, 77))
infoShapePath.addCurveToPoint(CGPointMake(32, 69.41), controlPoint1: CGPointMake(35.6, 77), controlPoint2: CGPointMake(32, 73.58))
infoShapePath.addLineToPoint(CGPointMake(32, 35.26))
infoShapePath.addCurveToPoint(CGPointMake(40, 27.67), controlPoint1: CGPointMake(32, 31.08), controlPoint2: CGPointMake(35.6, 27.67))
infoShapePath.addLineToPoint(CGPointMake(40, 27.67))
infoShapePath.addCurveToPoint(CGPointMake(48, 35.26), controlPoint1: CGPointMake(44.4, 27.67), controlPoint2: CGPointMake(48, 31.08))
infoShapePath.addLineToPoint(CGPointMake(48, 69.41))
infoShapePath.closePath()
color0.setFill()
infoShapePath.fill()
}
class func drawEdit() {
// Color Declarations
let color = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1.0)
// Edit shape Drawing
let editPathPath = UIBezierPath()
editPathPath.moveToPoint(CGPointMake(71, 2.7))
editPathPath.addCurveToPoint(CGPointMake(71.9, 15.2), controlPoint1: CGPointMake(74.7, 5.9), controlPoint2: CGPointMake(75.1, 11.6))
editPathPath.addLineToPoint(CGPointMake(64.5, 23.7))
editPathPath.addLineToPoint(CGPointMake(49.9, 11.1))
editPathPath.addLineToPoint(CGPointMake(57.3, 2.6))
editPathPath.addCurveToPoint(CGPointMake(69.7, 1.7), controlPoint1: CGPointMake(60.4, -1.1), controlPoint2: CGPointMake(66.1, -1.5))
editPathPath.addLineToPoint(CGPointMake(71, 2.7))
editPathPath.addLineToPoint(CGPointMake(71, 2.7))
editPathPath.closePath()
editPathPath.moveToPoint(CGPointMake(47.8, 13.5))
editPathPath.addLineToPoint(CGPointMake(13.4, 53.1))
editPathPath.addLineToPoint(CGPointMake(15.7, 55.1))
editPathPath.addLineToPoint(CGPointMake(50.1, 15.5))
editPathPath.addLineToPoint(CGPointMake(47.8, 13.5))
editPathPath.addLineToPoint(CGPointMake(47.8, 13.5))
editPathPath.closePath()
editPathPath.moveToPoint(CGPointMake(17.7, 56.7))
editPathPath.addLineToPoint(CGPointMake(23.8, 62.2))
editPathPath.addLineToPoint(CGPointMake(58.2, 22.6))
editPathPath.addLineToPoint(CGPointMake(52, 17.1))
editPathPath.addLineToPoint(CGPointMake(17.7, 56.7))
editPathPath.addLineToPoint(CGPointMake(17.7, 56.7))
editPathPath.closePath()
editPathPath.moveToPoint(CGPointMake(25.8, 63.8))
editPathPath.addLineToPoint(CGPointMake(60.1, 24.2))
editPathPath.addLineToPoint(CGPointMake(62.3, 26.1))
editPathPath.addLineToPoint(CGPointMake(28.1, 65.7))
editPathPath.addLineToPoint(CGPointMake(25.8, 63.8))
editPathPath.addLineToPoint(CGPointMake(25.8, 63.8))
editPathPath.closePath()
editPathPath.moveToPoint(CGPointMake(25.9, 68.1))
editPathPath.addLineToPoint(CGPointMake(4.2, 79.5))
editPathPath.addLineToPoint(CGPointMake(11.3, 55.5))
editPathPath.addLineToPoint(CGPointMake(25.9, 68.1))
editPathPath.closePath()
editPathPath.miterLimit = 4;
editPathPath.usesEvenOddFillRule = true;
color.setFill()
editPathPath.fill()
}
// Generated Images
class var imageOfCheckmark: UIImage {
if (Cache.imageOfCheckmark != nil) {
return Cache.imageOfCheckmark!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 80), false, 0)
SCLAlertViewStyleKit.drawCheckmark()
Cache.imageOfCheckmark = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfCheckmark!
}
class var imageOfCross: UIImage {
if (Cache.imageOfCross != nil) {
return Cache.imageOfCross!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 80), false, 0)
SCLAlertViewStyleKit.drawCross()
Cache.imageOfCross = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfCross!
}
class var imageOfNotice: UIImage {
if (Cache.imageOfNotice != nil) {
return Cache.imageOfNotice!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 80), false, 0)
SCLAlertViewStyleKit.drawNotice()
Cache.imageOfNotice = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfNotice!
}
class var imageOfWarning: UIImage {
if (Cache.imageOfWarning != nil) {
return Cache.imageOfWarning!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 80), false, 0)
SCLAlertViewStyleKit.drawWarning()
Cache.imageOfWarning = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfWarning!
}
class var imageOfInfo: UIImage {
if (Cache.imageOfInfo != nil) {
return Cache.imageOfInfo!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 80), false, 0)
SCLAlertViewStyleKit.drawInfo()
Cache.imageOfInfo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfInfo!
}
class var imageOfEdit: UIImage {
if (Cache.imageOfEdit != nil) {
return Cache.imageOfEdit!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 80), false, 0)
SCLAlertViewStyleKit.drawEdit()
Cache.imageOfEdit = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfEdit!
}
} | mit | cd1b850b67b54c331f0c8ba40f5a5c64 | 45.799213 | 221 | 0.679837 | 4.43422 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.