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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Raizlabs/SketchyCode
|
SketchyCode/Generation/Writer.swift
|
1
|
1079
|
//
// Writer.swift
// SketchyCode
//
// Created by Brian King on 10/3/17.
// Copyright © 2017 Brian King. All rights reserved.
//
import Foundation
// Writer is responsible for managing the structure of the generated output.
final class Writer {
static var indentation: String = " "
var content: String = ""
var level: Int = 0
func indent(work: () throws -> Void) throws {
level += 1
try work()
level -= 1
}
func block(appending: String = "", work: () throws -> Void) throws {
append(line: "{")
try indent(work: work)
append(line: "}\(appending)")
}
var addIndentation: Bool {
return content.count == 0 || content.last == "\n"
}
func append(line: String, addNewline: Bool = true) {
var value = ""
if addIndentation {
for _ in 0..<level {
value.append(Writer.indentation)
}
}
value.append(line)
if addNewline {
value.append("\n")
}
content.append(value)
}
}
|
mit
|
ab735ffa91db2b02460895f5d132f9a1
| 22.434783 | 76 | 0.540816 | 4.052632 | false | false | false | false |
gregomni/swift
|
test/Prototypes/BigInt.swift
|
3
|
54838
|
//===--- BigInt.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -swift-version 4 -o %t/a.out %s -Xfrontend -requirement-machine-inferred-signatures=on -Xfrontend -requirement-machine-abstract-signatures=on -Xfrontend -requirement-machine-protocol-signatures=on
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import StdlibUnittest
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import CRT
#else
#error("Unsupported platform")
#endif
extension FixedWidthInteger {
/// Returns the high and low parts of a potentially overflowing addition.
func addingFullWidth(_ other: Self) ->
(high: Self, low: Self) {
let sum = self.addingReportingOverflow(other)
return (sum.overflow ? 1 : 0, sum.partialValue)
}
/// Returns the high and low parts of two seqeuential potentially overflowing
/// additions.
static func addingFullWidth(_ x: Self, _ y: Self, _ z: Self) ->
(high: Self, low: Self) {
let xy = x.addingReportingOverflow(y)
let xyz = xy.partialValue.addingReportingOverflow(z)
let high: Self = (xy.overflow ? 1 : 0) +
(xyz.overflow ? 1 : 0)
return (high, xyz.partialValue)
}
/// Returns a tuple containing the value that would be borrowed from a higher
/// place and the partial difference of this value and `rhs`.
func subtractingWithBorrow(_ rhs: Self) ->
(borrow: Self, partialValue: Self) {
let difference = subtractingReportingOverflow(rhs)
return (difference.overflow ? 1 : 0, difference.partialValue)
}
/// Returns a tuple containing the value that would be borrowed from a higher
/// place and the partial value of `x` and `y` subtracted from this value.
func subtractingWithBorrow(_ x: Self, _ y: Self) ->
(borrow: Self, partialValue: Self) {
let firstDifference = subtractingReportingOverflow(x)
let secondDifference =
firstDifference.partialValue.subtractingReportingOverflow(y)
let borrow: Self = (firstDifference.overflow ? 1 : 0) +
(secondDifference.overflow ? 1 : 0)
return (borrow, secondDifference.partialValue)
}
}
//===--- BigInt -----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A dynamically-sized signed integer.
///
/// The `_BigInt` type is fully generic on the size of its "word" -- the
/// `BigInt` alias uses the system's word-sized `UInt` as its word type, but
/// any word size should work properly.
public struct _BigInt<Word: FixedWidthInteger & UnsignedInteger> :
BinaryInteger, SignedInteger, CustomStringConvertible,
CustomDebugStringConvertible
where Word.Magnitude == Word
{
/// The binary representation of the value's magnitude, with the least
/// significant word at index `0`.
///
/// - `_data` has no trailing zero elements
/// - If `self == 0`, then `isNegative == false` and `_data == []`
internal var _data: [Word] = []
/// A Boolean value indicating whether this instance is negative.
public private(set) var isNegative = false
/// A Boolean value indicating whether this instance is equal to zero.
public var isZero: Bool {
return _data.isEmpty
}
//===--- Numeric initializers -------------------------------------------===//
/// Creates a new instance equal to zero.
public init() { }
/// Creates a new instance using `_data` as the data collection.
init<C: Collection>(_ _data: C) where C.Iterator.Element == Word {
self._data = Array(_data)
_standardize()
}
public init(integerLiteral value: Int) {
self.init(value)
}
public init<T : BinaryInteger>(_ source: T) {
var source = source
if source < 0 as T {
if source.bitWidth <= UInt64.bitWidth {
let sourceMag = Int(truncatingIfNeeded: source).magnitude
self = _BigInt(sourceMag)
self.isNegative = true
return
} else {
// Have to kind of assume that we're working with another BigInt here
self.isNegative = true
source *= -1
}
}
// FIXME: This is broken on 32-bit arch w/ Word = UInt64
let wordRatio = UInt.bitWidth / Word.bitWidth
assert(wordRatio != 0)
for var sourceWord in source.words {
for _ in 0..<wordRatio {
_data.append(Word(truncatingIfNeeded: sourceWord))
sourceWord >>= Word.bitWidth
}
}
_standardize()
}
public init?<T : BinaryInteger>(exactly source: T) {
self.init(source)
}
public init<T : BinaryInteger>(truncatingIfNeeded source: T) {
self.init(source)
}
public init<T : BinaryInteger>(clamping source: T) {
self.init(source)
}
public init<T : BinaryFloatingPoint>(_ source: T) {
fatalError("Not implemented")
}
public init?<T : BinaryFloatingPoint>(exactly source: T) {
fatalError("Not implemented")
}
/// Returns a randomly-generated word.
static func _randomWord() -> Word {
// This handles up to a 64-bit word
if Word.bitWidth > UInt32.bitWidth {
return Word(UInt32.random(in: 0...UInt32.max)) << 32 | Word(UInt32.random(in: 0...UInt32.max))
} else {
return Word(truncatingIfNeeded: UInt32.random(in: 0...UInt32.max))
}
}
/// Creates a new instance whose magnitude has `randomBits` bits of random
/// data. The sign of the new value is randomly selected.
public init(randomBits: Int) {
let (words, extraBits) =
randomBits.quotientAndRemainder(dividingBy: Word.bitWidth)
// Get the bits for any full words.
self._data = (0..<words).map({ _ in _BigInt._randomWord() })
// Get another random number - the highest bit will determine the sign,
// while the lower `Word.bitWidth - 1` bits are available for any leftover
// bits in `randomBits`.
let word = _BigInt._randomWord()
if extraBits != 0 {
let mask = ~((~0 as Word) << Word(extraBits))
_data.append(word & mask)
}
isNegative = word & ~(~0 >> 1) == 0
_standardize()
}
//===--- Private methods ------------------------------------------------===//
/// Standardizes this instance after mutation, removing trailing zeros
/// and making sure zero is nonnegative. Calling this method satisfies the
/// two invariants.
mutating func _standardize(source: String = #function) {
defer { _checkInvariants(source: source + " >> _standardize()") }
while _data.last == 0 {
_data.removeLast()
}
// Zero is never negative.
isNegative = isNegative && _data.count != 0
}
/// Checks and asserts on invariants -- all invariants must be satisfied
/// at the end of every mutating method.
///
/// - `_data` has no trailing zero elements
/// - If `self == 0`, then `isNegative == false`
func _checkInvariants(source: String = #function) {
if _data.isEmpty {
assert(isNegative == false,
"\(source): isNegative with zero length _data")
}
assert(_data.last != 0, "\(source): extra zeroes on _data")
}
//===--- Word-based arithmetic ------------------------------------------===//
mutating func _unsignedAdd(_ rhs: Word) {
defer { _standardize() }
// Quick return if `rhs == 0`
guard rhs != 0 else { return }
// Quick return if `self == 0`
if isZero {
_data.append(rhs)
return
}
// Add `rhs` to the first word, catching any carry.
var carry: Word
(carry, _data[0]) = _data[0].addingFullWidth(rhs)
// Handle any additional carries
for i in 1..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].addingFullWidth(carry)
}
// If there's any carry left, add it now
if carry != 0 {
_data.append(1)
}
}
/// Subtracts `rhs` from this instance, ignoring the sign.
///
/// - Precondition: `rhs <= self.magnitude`
mutating func _unsignedSubtract(_ rhs: Word) {
precondition(_data.count > 1 || _data[0] > rhs)
// Quick return if `rhs == 0`
guard rhs != 0 else { return }
// If `isZero == true`, then `rhs` must also be zero.
precondition(!isZero)
var carry: Word
(carry, _data[0]) = _data[0].subtractingWithBorrow(rhs)
for i in 1..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].subtractingWithBorrow(carry)
}
assert(carry == 0)
_standardize()
}
/// Adds `rhs` to this instance.
mutating func add(_ rhs: Word) {
if isNegative {
// If _data only contains one word and `rhs` is greater, swap them,
// make self positive and continue with unsigned subtraction.
var rhs = rhs
if _data.count == 1 && _data[0] < rhs {
swap(&rhs, &_data[0])
isNegative = false
}
_unsignedSubtract(rhs)
} else { // positive or zero
_unsignedAdd(rhs)
}
}
/// Subtracts `rhs` from this instance.
mutating func subtract(_ rhs: Word) {
guard rhs != 0 else { return }
if isNegative {
_unsignedAdd(rhs)
} else if isZero {
isNegative = true
_data.append(rhs)
} else {
var rhs = rhs
if _data.count == 1 && _data[0] < rhs {
swap(&rhs, &_data[0])
isNegative = true
}
_unsignedSubtract(rhs)
}
}
/// Multiplies this instance by `rhs`.
mutating func multiply(by rhs: Word) {
// If either `self` or `rhs` is zero, the result is zero.
guard !isZero && rhs != 0 else {
self = 0
return
}
// If `rhs` is a power of two, can just left shift `self`.
let rhsLSB = rhs.trailingZeroBitCount
if rhs >> rhsLSB == 1 {
self <<= rhsLSB
return
}
var carry: Word = 0
for i in 0..<_data.count {
let product = _data[i].multipliedFullWidth(by: rhs)
(carry, _data[i]) = product.low.addingFullWidth(carry)
carry = carry &+ product.high
}
// Add the leftover carry
if carry != 0 {
_data.append(carry)
}
_standardize()
}
/// Divides this instance by `rhs`, returning the remainder.
@discardableResult
mutating func divide(by rhs: Word) -> Word {
precondition(rhs != 0, "divide by zero")
// No-op if `rhs == 1` or `self == 0`.
if rhs == 1 || isZero {
return 0
}
// If `rhs` is a power of two, can just right shift `self`.
let rhsLSB = rhs.trailingZeroBitCount
if rhs >> rhsLSB == 1 {
defer { self >>= rhsLSB }
return _data[0] & ~(~0 << rhsLSB)
}
var carry: Word = 0
for i in (0..<_data.count).reversed() {
let lhs = (high: carry, low: _data[i])
(_data[i], carry) = rhs.dividingFullWidth(lhs)
}
_standardize()
return carry
}
//===--- Numeric --------------------------------------------------------===//
public typealias Magnitude = _BigInt
public var magnitude: _BigInt {
var result = self
result.isNegative = false
return result
}
/// Adds `rhs` to this instance, ignoring any signs.
mutating func _unsignedAdd(_ rhs: _BigInt) {
defer { _checkInvariants() }
let commonCount = Swift.min(_data.count, rhs._data.count)
let maxCount = Swift.max(_data.count, rhs._data.count)
_data.reserveCapacity(maxCount)
// Add the words up to the common count, carrying any overflows
var carry: Word = 0
for i in 0..<commonCount {
(carry, _data[i]) = Word.addingFullWidth(_data[i], rhs._data[i], carry)
}
// If there are leftover words in `self`, just need to handle any carries
if _data.count > rhs._data.count {
for i in commonCount..<maxCount {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].addingFullWidth(carry)
}
// If there are leftover words in `rhs`, need to copy to `self` with carries
} else if _data.count < rhs._data.count {
for i in commonCount..<maxCount {
// Append remaining words if nothing to carry
if carry == 0 {
_data.append(contentsOf: rhs._data.suffix(from: i))
break
}
let sum: Word
(carry, sum) = rhs._data[i].addingFullWidth(carry)
_data.append(sum)
}
}
// If there's any carry left, add it now
if carry != 0 {
_data.append(1)
}
}
/// Subtracts `rhs` from this instance, ignoring the sign.
///
/// - Precondition: `rhs.magnitude <= self.magnitude` (unchecked)
/// - Precondition: `rhs._data.count <= self._data.count`
mutating func _unsignedSubtract(_ rhs: _BigInt) {
precondition(rhs._data.count <= _data.count)
var carry: Word = 0
for i in 0..<rhs._data.count {
(carry, _data[i]) = _data[i].subtractingWithBorrow(rhs._data[i], carry)
}
for i in rhs._data.count..<_data.count {
// No more action needed if there's nothing to carry
if carry == 0 { break }
(carry, _data[i]) = _data[i].subtractingWithBorrow(carry)
}
assert(carry == 0)
_standardize()
}
public static func +=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
if lhs.isNegative == rhs.isNegative {
lhs._unsignedAdd(rhs)
} else {
lhs -= -rhs
}
}
public static func -=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
// Subtracting something of the opposite sign just adds magnitude.
guard lhs.isNegative == rhs.isNegative else {
lhs._unsignedAdd(rhs)
return
}
// Comare `lhs` and `rhs` so we can use `_unsignedSubtract` to subtract
// the smaller magnitude from the larger magnitude.
switch lhs._compareMagnitude(to: rhs) {
case .equal:
lhs = 0
case .greaterThan:
lhs._unsignedSubtract(rhs)
case .lessThan:
// x - y == -y + x == -(y - x)
var result = rhs
result._unsignedSubtract(lhs)
result.isNegative = !lhs.isNegative
lhs = result
}
}
public static func *=(lhs: inout _BigInt, rhs: _BigInt) {
// If either `lhs` or `rhs` is zero, the result is zero.
guard !lhs.isZero && !rhs.isZero else {
lhs = 0
return
}
var newData: [Word] = Array(repeating: 0,
count: lhs._data.count + rhs._data.count)
let (a, b) = lhs._data.count > rhs._data.count
? (lhs._data, rhs._data)
: (rhs._data, lhs._data)
assert(a.count >= b.count)
var carry: Word = 0
for ai in 0..<a.count {
carry = 0
for bi in 0..<b.count {
// Each iteration needs to perform this operation:
//
// newData[ai + bi] += (a[ai] * b[bi]) + carry
//
// However, `a[ai] * b[bi]` produces a double-width result, and both
// additions can overflow to a higher word. The following two lines
// capture the low word of the multiplication and additions in
// `newData[ai + bi]` and any addition overflow in `carry`.
let product = a[ai].multipliedFullWidth(by: b[bi])
(carry, newData[ai + bi]) = Word.addingFullWidth(
newData[ai + bi], product.low, carry)
// Now we combine the high word of the multiplication with any addition
// overflow. It is safe to add `product.high` and `carry` here without
// checking for overflow, because if `product.high == .max - 1`, then
// `carry <= 1`. Otherwise, `carry <= 2`.
//
// Worst-case (aka 9 + 9*9 + 9):
//
// newData a[ai] b[bi] carry
// 0b11111111 + (0b11111111 * 0b11111111) + 0b11111111
// 0b11111111 + (0b11111110_____00000001) + 0b11111111
// (0b11111111_____00000000) + 0b11111111
// (0b11111111_____11111111)
//
// Second-worse case:
//
// 0b11111111 + (0b11111111 * 0b11111110) + 0b11111111
// 0b11111111 + (0b11111101_____00000010) + 0b11111111
// (0b11111110_____00000001) + 0b11111111
// (0b11111111_____00000000)
assert(!product.high.addingReportingOverflow(carry).overflow)
carry = product.high &+ carry
}
// Leftover `carry` is inserted in new highest word.
assert(newData[ai + b.count] == 0)
newData[ai + b.count] = carry
}
lhs._data = newData
lhs.isNegative = lhs.isNegative != rhs.isNegative
lhs._standardize()
}
/// Divides this instance by `rhs`, returning the remainder.
@discardableResult
mutating func _internalDivide(by rhs: _BigInt) -> _BigInt {
precondition(!rhs.isZero, "Divided by zero")
defer { _checkInvariants() }
// Handle quick cases that don't require division:
// If `abs(self) < abs(rhs)`, the result is zero, remainder = self
// If `abs(self) == abs(rhs)`, the result is 1 or -1, remainder = 0
switch _compareMagnitude(to: rhs) {
case .lessThan:
defer { self = 0 }
return self
case .equal:
self = isNegative != rhs.isNegative ? -1 : 1
return 0
default:
break
}
var tempSelf = self.magnitude
let n = tempSelf.bitWidth - rhs.magnitude.bitWidth
var quotient: _BigInt = 0
var tempRHS = rhs.magnitude << n
var tempQuotient: _BigInt = 1 << n
for _ in (0...n).reversed() {
if tempRHS._compareMagnitude(to: tempSelf) != .greaterThan {
tempSelf -= tempRHS
quotient += tempQuotient
}
tempRHS >>= 1
tempQuotient >>= 1
}
// `tempSelf` is the remainder - match sign of original `self`
tempSelf.isNegative = self.isNegative
tempSelf._standardize()
quotient.isNegative = isNegative != rhs.isNegative
self = quotient
_standardize()
return tempSelf
}
public static func /=(lhs: inout _BigInt, rhs: _BigInt) {
lhs._internalDivide(by: rhs)
}
// FIXME: Remove once default implementations are provided:
public static func +(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs += rhs
return lhs
}
public static func -(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func *(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func /(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func %(_ lhs: _BigInt, _ rhs: _BigInt) -> _BigInt {
var lhs = lhs
lhs %= rhs
return lhs
}
//===--- BinaryInteger --------------------------------------------------===//
/// Creates a new instance using the given data array in two's complement
/// representation.
init(_twosComplementData: [Word]) {
guard _twosComplementData.count > 0 else {
self = 0
return
}
// Is the highest bit set?
isNegative = _twosComplementData.last!.leadingZeroBitCount == 0
if isNegative {
_data = _twosComplementData.map(~)
self._unsignedAdd(1 as Word)
} else {
_data = _twosComplementData
}
_standardize()
}
/// Returns an array of the value's data using two's complement representation.
func _dataAsTwosComplement() -> [Word] {
// Special cases:
// * Nonnegative values are already in 2's complement
if !isNegative {
// Positive values need to have a leading zero bit
if _data.last?.leadingZeroBitCount == 0 {
return _data + [0]
} else {
return _data
}
}
// * -1 will get zeroed out below, easier to handle here
if _data.count == 1 && _data.first == 1 { return [~0] }
var x = self
x._unsignedSubtract(1 as Word)
if x._data.last!.leadingZeroBitCount == 0 {
// The highest bit is set to 1, which moves to 0 after negation.
// We need to add another word at the high end so the highest bit is 1.
return x._data.map(~) + [Word.max]
} else {
// The highest bit is set to 0, which moves to 1 after negation.
return x._data.map(~)
}
}
public var words: [UInt] {
assert(UInt.bitWidth % Word.bitWidth == 0)
let twosComplementData = _dataAsTwosComplement()
var words: [UInt] = []
words.reserveCapacity((twosComplementData.count * Word.bitWidth
+ UInt.bitWidth - 1) / UInt.bitWidth)
var word: UInt = 0
var shift = 0
for w in twosComplementData {
word |= UInt(truncatingIfNeeded: w) << shift
shift += Word.bitWidth
if shift == UInt.bitWidth {
words.append(word)
word = 0
shift = 0
}
}
if shift != 0 {
if isNegative {
word |= ~((1 << shift) - 1)
}
words.append(word)
}
return words
}
/// The number of bits used for storage of this value. Always a multiple of
/// `Word.bitWidth`.
public var bitWidth: Int {
if isZero {
return 0
} else {
let twosComplementData = _dataAsTwosComplement()
// If negative, it's okay to have 1s padded on high end
if isNegative {
return twosComplementData.count * Word.bitWidth
}
// If positive, need to make space for at least one zero on high end
return twosComplementData.count * Word.bitWidth
- twosComplementData.last!.leadingZeroBitCount + 1
}
}
/// The number of sequential zeros in the least-significant position of this
/// value's binary representation.
///
/// The numbers 1 and zero have zero trailing zeros.
public var trailingZeroBitCount: Int {
guard !isZero else {
return 0
}
let i = _data.firstIndex(where: { $0 != 0 })!
assert(_data[i] != 0)
return i * Word.bitWidth + _data[i].trailingZeroBitCount
}
public static func %=(lhs: inout _BigInt, rhs: _BigInt) {
defer { lhs._checkInvariants() }
lhs = lhs._internalDivide(by: rhs)
}
public func quotientAndRemainder(dividingBy rhs: _BigInt) ->
(_BigInt, _BigInt)
{
var x = self
let r = x._internalDivide(by: rhs)
return (x, r)
}
public static func &=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s
// * If `rhs >= 0`, length is extended with 0s, which crops `lhsTemp`
if lhsTemp.count > rhsTemp.count && !rhs.isNegative {
lhsTemp.removeLast(lhsTemp.count - rhsTemp.count)
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so `lhs` should get extra
// bits from `rhs`
// * If `lhs >= 0`, length is extended with 0s
if lhsTemp.count < rhsTemp.count && lhs.isNegative {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
// Perform bitwise & on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] &= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static func |=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be 1
// * If `rhs >= 0`, length is extended with 0s, which is a no-op
if lhsTemp.count > rhsTemp.count && rhs.isNegative {
lhsTemp.replaceSubrange(rhsTemp.count..<lhsTemp.count,
with: repeatElement(Word.max, count: lhsTemp.count - rhsTemp.count))
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so those bits of lhs
// should all be 1
// * If `lhs >= 0`, length is extended with 0s, so those bits should be
// copied from rhs
if lhsTemp.count < rhsTemp.count {
if lhs.isNegative {
lhsTemp.append(contentsOf:
repeatElement(Word.max, count: rhsTemp.count - lhsTemp.count))
} else {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
}
// Perform bitwise | on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] |= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static func ^=(lhs: inout _BigInt, rhs: _BigInt) {
var lhsTemp = lhs._dataAsTwosComplement()
let rhsTemp = rhs._dataAsTwosComplement()
// If `lhs` is longer than `rhs`, behavior depends on sign of `rhs`
// * If `rhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be flipped
// * If `rhs >= 0`, length is extended with 0s, which is a no-op
if lhsTemp.count > rhsTemp.count && rhs.isNegative {
for i in rhsTemp.count..<lhsTemp.count {
lhsTemp[i] = ~lhsTemp[i]
}
}
// If `rhs` is longer than `lhs`, behavior depends on sign of `lhs`
// * If `lhs < 0`, length is extended with 1s, so those bits of `lhs`
// should all be flipped copies of `rhs`
// * If `lhs >= 0`, length is extended with 0s, so those bits should
// be copied from rhs
if lhsTemp.count < rhsTemp.count {
if lhs.isNegative {
lhsTemp += rhsTemp.suffix(from: lhsTemp.count).map(~)
} else {
lhsTemp.append(contentsOf: rhsTemp[lhsTemp.count..<rhsTemp.count])
}
}
// Perform bitwise ^ on words that both `lhs` and `rhs` have.
for i in 0..<Swift.min(lhsTemp.count, rhsTemp.count) {
lhsTemp[i] ^= rhsTemp[i]
}
lhs = _BigInt(_twosComplementData: lhsTemp)
}
public static prefix func ~(x: _BigInt) -> _BigInt {
return -x - 1
}
//===--- SignedNumeric --------------------------------------------------===//
public static prefix func -(x: inout _BigInt) {
defer { x._checkInvariants() }
guard x._data.count > 0 else { return }
x.isNegative = !x.isNegative
}
//===--- Strideable -----------------------------------------------------===//
public func distance(to other: _BigInt) -> _BigInt {
return other - self
}
public func advanced(by n: _BigInt) -> _BigInt {
return self + n
}
//===--- Other arithmetic -----------------------------------------------===//
/// Returns the greatest common divisor for this value and `other`.
public func greatestCommonDivisor(with other: _BigInt) -> _BigInt {
// Quick return if either is zero
if other.isZero {
return magnitude
}
if isZero {
return other.magnitude
}
var (x, y) = (self.magnitude, other.magnitude)
let (xLSB, yLSB) = (x.trailingZeroBitCount, y.trailingZeroBitCount)
// Remove any common factor of two
let commonPower = Swift.min(xLSB, yLSB)
x >>= commonPower
y >>= commonPower
// Remove any remaining factor of two
if xLSB != commonPower {
x >>= xLSB - commonPower
}
if yLSB != commonPower {
y >>= yLSB - commonPower
}
while !x.isZero {
// Swap values to ensure that `x >= y`.
if x._compareMagnitude(to: y) == .lessThan {
swap(&x, &y)
}
// Subtract smaller and remove any factors of two
x._unsignedSubtract(y)
x >>= x.trailingZeroBitCount
}
// Add original common factor of two back into result
y <<= commonPower
return y
}
/// Returns the lowest common multiple for this value and `other`.
public func lowestCommonMultiple(with other: _BigInt) -> _BigInt {
let gcd = greatestCommonDivisor(with: other)
if _compareMagnitude(to: other) == .lessThan {
return ((self / gcd) * other).magnitude
} else {
return ((other / gcd) * self).magnitude
}
}
//===--- String methods ------------------------------------------------===//
/// Creates a new instance from the given string.
///
/// - Parameters:
/// - source: The string to parse for the new instance's value. If a
/// character in `source` is not in the range `0...9` or `a...z`, case
/// insensitive, or is not less than `radix`, the result is `nil`.
/// - radix: The radix to use when parsing `source`. `radix` must be in the
/// range `2...36`. The default is `10`.
public init?(_ source: String, radix: Int = 10) {
assert(2...36 ~= radix, "radix must be in range 2...36")
let radix = Word(radix)
func valueForCodeUnit(_ unit: Unicode.UTF16.CodeUnit) -> Word? {
switch unit {
// "0"..."9"
case 48...57: return Word(unit - 48)
// "a"..."z"
case 97...122: return Word(unit - 87)
// "A"..."Z"
case 65...90: return Word(unit - 55)
// invalid character
default: return nil
}
}
var source = source
// Check for a single prefixing hyphen
let negative = source.hasPrefix("-")
if negative {
source = String(source.dropFirst())
}
// Loop through characters, multiplying
for v in source.utf16.map(valueForCodeUnit) {
// Character must be valid and less than radix
guard let v = v else { return nil }
guard v < radix else { return nil }
self.multiply(by: radix)
self.add(v)
}
self.isNegative = negative
}
/// Returns a string representation of this instance.
///
/// - Parameters:
/// - radix: The radix to use when converting this instance to a string.
/// The value passed as `radix` must be in the range `2...36`. The
/// default is `10`.
/// - lowercase: Whether to use lowercase letters to represent digits
/// greater than 10. The default is `true`.
public func toString(radix: Int = 10, lowercase: Bool = true) -> String {
assert(2...36 ~= radix, "radix must be in range 2...36")
let digitsStart = ("0" as Unicode.Scalar).value
let lettersStart = ((lowercase ? "a" : "A") as Unicode.Scalar).value - 10
func toLetter(_ x: UInt32) -> Unicode.Scalar {
return x < 10
? Unicode.Scalar(digitsStart + x)!
: Unicode.Scalar(lettersStart + x)!
}
let radix = _BigInt(radix)
var result: [Unicode.Scalar] = []
var x = self.magnitude
while !x.isZero {
let remainder: _BigInt
(x, remainder) = x.quotientAndRemainder(dividingBy: radix)
result.append(toLetter(UInt32(remainder)))
}
let sign = isNegative ? "-" : ""
let rest = result.count == 0
? "0"
: String(String.UnicodeScalarView(result.reversed()))
return sign + rest
}
public var description: String {
return decimalString
}
public var debugDescription: String {
return "_BigInt(\(hexString), words: \(_data.count))"
}
/// A string representation of this instance's value in base 2.
public var binaryString: String {
return toString(radix: 2)
}
/// A string representation of this instance's value in base 10.
public var decimalString: String {
return toString(radix: 10)
}
/// A string representation of this instance's value in base 16.
public var hexString: String {
return toString(radix: 16, lowercase: false)
}
/// A string representation of this instance's value in base 36.
public var compactString: String {
return toString(radix: 36, lowercase: false)
}
//===--- Comparable -----------------------------------------------------===//
enum _ComparisonResult {
case lessThan, equal, greaterThan
}
/// Returns whether this instance is less than, greather than, or equal to
/// the given value.
func _compare(to rhs: _BigInt) -> _ComparisonResult {
// Negative values are less than positive values
guard isNegative == rhs.isNegative else {
return isNegative ? .lessThan : .greaterThan
}
switch _compareMagnitude(to: rhs) {
case .equal:
return .equal
case .lessThan:
return isNegative ? .greaterThan : .lessThan
case .greaterThan:
return isNegative ? .lessThan : .greaterThan
}
}
/// Returns whether the magnitude of this instance is less than, greather
/// than, or equal to the magnitude of the given value.
func _compareMagnitude(to rhs: _BigInt) -> _ComparisonResult {
guard _data.count == rhs._data.count else {
return _data.count < rhs._data.count ? .lessThan : .greaterThan
}
// Equal number of words: compare from most significant word
for i in (0..<_data.count).reversed() {
if _data[i] < rhs._data[i] { return .lessThan }
if _data[i] > rhs._data[i] { return .greaterThan }
}
return .equal
}
public static func ==(lhs: _BigInt, rhs: _BigInt) -> Bool {
return lhs._compare(to: rhs) == .equal
}
public static func < (lhs: _BigInt, rhs: _BigInt) -> Bool {
return lhs._compare(to: rhs) == .lessThan
}
//===--- Hashable -------------------------------------------------------===//
public func hash(into hasher: inout Hasher) {
hasher.combine(isNegative)
hasher.combine(_data)
}
//===--- Bit shifting operators -----------------------------------------===//
static func _shiftLeft(_ data: inout [Word], byWords words: Int) {
guard words > 0 else { return }
data.insert(contentsOf: repeatElement(0, count: words), at: 0)
}
static func _shiftRight(_ data: inout [Word], byWords words: Int) {
guard words > 0 else { return }
data.removeFirst(Swift.min(data.count, words))
}
public static func <<= <RHS : BinaryInteger>(lhs: inout _BigInt, rhs: RHS) {
defer { lhs._checkInvariants() }
guard rhs != 0 else { return }
guard rhs > 0 else {
lhs >>= 0 - rhs
return
}
let wordWidth = RHS(Word.bitWidth)
// We can add `rhs / bits` extra words full of zero at the low end.
let extraWords = Int(rhs / wordWidth)
lhs._data.reserveCapacity(lhs._data.count + extraWords + 1)
_BigInt._shiftLeft(&lhs._data, byWords: extraWords)
// Each existing word will need to be shifted left by `rhs % bits`.
// For each pair of words, we'll use the high `offset` bits of the
// lower word and the low `Word.bitWidth - offset` bits of the higher
// word.
let highOffset = Int(rhs % wordWidth)
let lowOffset = Word.bitWidth - highOffset
// If there's no offset, we're finished, as `rhs` was a multiple of
// `Word.bitWidth`.
guard highOffset != 0 else { return }
// Add new word at the end, then shift everything left by `offset` bits.
lhs._data.append(0)
for i in ((extraWords + 1)..<lhs._data.count).reversed() {
lhs._data[i] = lhs._data[i] << highOffset
| lhs._data[i - 1] >> lowOffset
}
// Finally, shift the lowest word.
lhs._data[extraWords] = lhs._data[extraWords] << highOffset
lhs._standardize()
}
public static func >>= <RHS : BinaryInteger>(lhs: inout _BigInt, rhs: RHS) {
defer { lhs._checkInvariants() }
guard rhs != 0 else { return }
guard rhs > 0 else {
lhs <<= 0 - rhs
return
}
var tempData = lhs._dataAsTwosComplement()
let wordWidth = RHS(Word.bitWidth)
// We can remove `rhs / bits` full words at the low end.
// If that removes the entirety of `_data`, we're done.
let wordsToRemove = Int(rhs / wordWidth)
_BigInt._shiftRight(&tempData, byWords: wordsToRemove)
guard tempData.count != 0 else {
lhs = lhs.isNegative ? -1 : 0
return
}
// Each existing word will need to be shifted right by `rhs % bits`.
// For each pair of words, we'll use the low `offset` bits of the
// higher word and the high `_BigInt.Word.bitWidth - offset` bits of
// the lower word.
let lowOffset = Int(rhs % wordWidth)
let highOffset = Word.bitWidth - lowOffset
// If there's no offset, we're finished, as `rhs` was a multiple of
// `Word.bitWidth`.
guard lowOffset != 0 else {
lhs = _BigInt(_twosComplementData: tempData)
return
}
// Shift everything right by `offset` bits.
for i in 0..<(tempData.count - 1) {
tempData[i] = tempData[i] >> lowOffset |
tempData[i + 1] << highOffset
}
// Finally, shift the highest word and standardize the result.
tempData[tempData.count - 1] >>= lowOffset
lhs = _BigInt(_twosComplementData: tempData)
}
}
//===--- Bit --------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A one-bit fixed width integer.
struct Bit : FixedWidthInteger, UnsignedInteger {
typealias Magnitude = Bit
var value: UInt8 = 0
// Initializers
init(integerLiteral value: Int) {
self = Bit(value)
}
init(bigEndian value: Bit) {
self = value
}
init(littleEndian value: Bit) {
self = value
}
init?<T: BinaryFloatingPoint>(exactly source: T) {
switch source {
case T(0): value = 0
case T(1): value = 1
default:
return nil
}
}
init<T: BinaryFloatingPoint>(_ source: T) {
self = Bit(exactly: source.rounded(.down))!
}
init<T: BinaryInteger>(_ source: T) {
switch source {
case 0: value = 0
case 1: value = 1
default:
fatalError("Can't represent \(source) as a Bit")
}
}
init<T: BinaryInteger>(truncatingIfNeeded source: T) {
value = UInt8(source & 1)
}
init(_truncatingBits bits: UInt) {
value = UInt8(bits & 1)
}
init<T: BinaryInteger>(clamping source: T) {
value = source >= 1 ? 1 : 0
}
// FixedWidthInteger, BinaryInteger
static var bitWidth: Int {
return 1
}
var bitWidth: Int {
return 1
}
var trailingZeroBitCount: Int {
return Int(~value & 1)
}
static var max: Bit {
return 1
}
static var min: Bit {
return 0
}
static var isSigned: Bool {
return false
}
var nonzeroBitCount: Int {
return value.nonzeroBitCount
}
var leadingZeroBitCount: Int {
return Int(~value & 1)
}
var bigEndian: Bit {
return self
}
var littleEndian: Bit {
return self
}
var byteSwapped: Bit {
return self
}
var words: UInt.Words {
return UInt(value).words
}
// Hashable, CustomStringConvertible
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
var description: String {
return "\(value)"
}
// Arithmetic Operations / Operators
func _checkOverflow(_ v: UInt8) -> Bool {
let mask: UInt8 = ~0 << 1
return v & mask != 0
}
func addingReportingOverflow(_ rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &+ rhs.value
return (Bit(result & 1), _checkOverflow(result))
}
func subtractingReportingOverflow(_ rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &- rhs.value
return (Bit(result & 1), _checkOverflow(result))
}
func multipliedReportingOverflow(by rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
let result = value &* rhs.value
return (Bit(result), false)
}
func dividedReportingOverflow(by rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
return (self, rhs != 0)
}
func remainderReportingOverflow(dividingBy rhs: Bit) ->
(partialValue: Bit, overflow: Bool) {
fatalError()
}
static func +=(lhs: inout Bit, rhs: Bit) {
let result = lhs.addingReportingOverflow(rhs)
assert(!result.overflow, "Addition overflow")
lhs = result.partialValue
}
static func -=(lhs: inout Bit, rhs: Bit) {
let result = lhs.subtractingReportingOverflow(rhs)
assert(!result.overflow, "Subtraction overflow")
lhs = result.partialValue
}
static func *=(lhs: inout Bit, rhs: Bit) {
let result = lhs.multipliedReportingOverflow(by: rhs)
assert(!result.overflow, "Multiplication overflow")
lhs = result.partialValue
}
static func /=(lhs: inout Bit, rhs: Bit) {
let result = lhs.dividedReportingOverflow(by: rhs)
assert(!result.overflow, "Division overflow")
lhs = result.partialValue
}
static func %=(lhs: inout Bit, rhs: Bit) {
assert(rhs != 0, "Modulo sum overflow")
lhs.value = 0 // No remainders with bit division!
}
func multipliedFullWidth(by other: Bit) -> (high: Bit, low: Bit) {
return (0, self * other)
}
func dividingFullWidth(_ dividend: (high: Bit, low: Bit)) ->
(quotient: Bit, remainder: Bit) {
assert(self != 0, "Division overflow")
assert(dividend.high == 0, "Quotient overflow")
return (dividend.low, 0)
}
// FIXME: Remove once default implementations are provided:
public static func +(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs += rhs
return lhs
}
public static func -(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs -= rhs
return lhs
}
public static func *(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs *= rhs
return lhs
}
public static func /(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs /= rhs
return lhs
}
public static func %(_ lhs: Bit, _ rhs: Bit) -> Bit {
var lhs = lhs
lhs %= rhs
return lhs
}
// Bitwise operators
static prefix func ~(x: Bit) -> Bit {
return Bit(~x.value & 1)
}
// Why doesn't the type checker complain about these being missing?
static func &=(lhs: inout Bit, rhs: Bit) {
lhs.value &= rhs.value
}
static func |=(lhs: inout Bit, rhs: Bit) {
lhs.value |= rhs.value
}
static func ^=(lhs: inout Bit, rhs: Bit) {
lhs.value ^= rhs.value
}
static func ==(lhs: Bit, rhs: Bit) -> Bool {
return lhs.value == rhs.value
}
static func <(lhs: Bit, rhs: Bit) -> Bool {
return lhs.value < rhs.value
}
static func <<(lhs: Bit, rhs: Bit) -> Bit {
return rhs == 0 ? lhs : 0
}
static func >>(lhs: Bit, rhs: Bit) -> Bit {
return rhs == 0 ? lhs : 0
}
static func <<=(lhs: inout Bit, rhs: Bit) {
if rhs != 0 {
lhs = 0
}
}
static func >>=(lhs: inout Bit, rhs: Bit) {
if rhs != 0 {
lhs = 0
}
}
}
//===--- Tests ------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
typealias BigInt = _BigInt<UInt>
typealias BigInt8 = _BigInt<UInt8>
typealias BigIntBit = _BigInt<Bit>
func testBinaryInit<T: BinaryInteger>(_ x: T) -> BigInt {
return BigInt(x)
}
func randomBitLength() -> Int {
return Int.random(in: 2...1000)
}
var BitTests = TestSuite("Bit")
BitTests.test("Basics") {
let x = Bit.max
let y = Bit.min
expectTrue(x == 1 as Int)
expectTrue(y == 0 as Int)
expectTrue(x < Int.max)
expectGT(x, y)
expectEqual(x, x)
expectEqual(x, x ^ 0)
expectGT(x, x & 0)
expectEqual(x, x | 0)
expectLT(y, y | 1)
expectEqual(x, ~y)
expectEqual(y, ~x)
expectEqual(x, x + y)
expectGT(x, x &+ x)
expectEqual(1, x.nonzeroBitCount)
expectEqual(0, y.nonzeroBitCount)
expectEqual(0, x.leadingZeroBitCount)
expectEqual(1, y.leadingZeroBitCount)
expectEqual(0, x.trailingZeroBitCount)
expectEqual(1, y.trailingZeroBitCount)
}
var BigIntTests = TestSuite("BigInt")
BigIntTests.test("Initialization") {
let x = testBinaryInit(1_000_000 as Int)
expectEqual(x._data[0], 1_000_000)
let y = testBinaryInit(1_000 as UInt16)
expectEqual(y._data[0], 1_000)
let z = testBinaryInit(-1_000_000 as Int)
expectEqual(z._data[0], 1_000_000)
expectTrue(z.isNegative)
let z6 = testBinaryInit(z * z * z * z * z * z)
expectEqual(z6._data, [12919594847110692864, 54210108624275221])
expectFalse(z6.isNegative)
}
BigIntTests.test("Identity/Fixed point") {
let x = BigInt(repeatElement(UInt.max, count: 20))
let y = -x
expectEqual(x / x, 1)
expectEqual(x / y, -1)
expectEqual(y / x, -1)
expectEqual(y / y, 1)
expectEqual(x % x, 0)
expectEqual(x % y, 0)
expectEqual(y % x, 0)
expectEqual(y % y, 0)
expectEqual(x * 1, x)
expectEqual(y * 1, y)
expectEqual(x * -1, y)
expectEqual(y * -1, x)
expectEqual(-x, y)
expectEqual(-y, x)
expectEqual(x + 0, x)
expectEqual(y + 0, y)
expectEqual(x - 0, x)
expectEqual(y - 0, y)
expectEqual(x - x, 0)
expectEqual(y - y, 0)
}
BigIntTests.test("Max arithmetic") {
let x = BigInt(repeatElement(UInt.max, count: 50))
let y = BigInt(repeatElement(UInt.max, count: 35))
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
BigIntTests.test("Zero arithmetic") {
let zero: BigInt = 0
expectTrue(zero.isZero)
expectFalse(zero.isNegative)
let x: BigInt = 1
expectTrue((x - x).isZero)
expectFalse((x - x).isNegative)
let y: BigInt = -1
expectTrue(y.isNegative)
expectTrue((y - y).isZero)
expectFalse((y - y).isNegative)
expectEqual(x * zero, zero)
expectCrashLater()
_ = x / zero
}
BigIntTests.test("Conformances") {
// Comparable
let x = BigInt(Int.max)
let y = x * x * x * x * x
expectLT(y, y + 1)
expectGT(y, y - 1)
expectGT(y, 0)
let z = -y
expectLT(z, z + 1)
expectGT(z, z - 1)
expectLT(z, 0)
expectEqual(-z, y)
expectEqual(y + z, 0)
// Hashable
expectNotEqual(x.hashValue, y.hashValue)
expectNotEqual(y.hashValue, z.hashValue)
let set = Set([x, y, z])
expectTrue(set.contains(x))
expectTrue(set.contains(y))
expectTrue(set.contains(z))
expectFalse(set.contains(-x))
}
BigIntTests.test("BinaryInteger interop") {
let x: BigInt = 100
let xComp = UInt8(x)
expectTrue(x == xComp)
expectTrue(x < xComp + 1)
expectFalse(xComp + 1 < x)
let y: BigInt = -100
let yComp = Int8(y)
expectTrue(y == yComp)
expectTrue(y < yComp + (1 as Int8))
expectFalse(yComp + (1 as Int8) < y)
// should be: expectTrue(y < yComp + 1), but:
// warning: '+' is deprecated: Mixed-type addition is deprecated.
// Please use explicit type conversion.
let zComp = Int.min + 1
let z = BigInt(zComp)
expectTrue(z == zComp)
expectTrue(zComp == z)
expectFalse(zComp + 1 < z)
expectTrue(z < zComp + 1)
let w = BigInt(UInt.max)
let wComp = UInt(truncatingIfNeeded: w)
expectTrue(w == wComp)
expectTrue(wComp == w)
expectTrue(wComp - (1 as UInt) < w)
expectFalse(w < wComp - (1 as UInt))
// should be:
// expectTrue(wComp - 1 < w)
// expectTrue(w > wComp - 1)
// but crashes at runtime
}
BigIntTests.test("Huge") {
let x = BigInt(randomBits: 1_000_000)
expectGT(x, x - 1)
let y = -x
expectGT(y, y - 1)
}
BigIntTests.test("Numeric").forEach(in: [
("3GFWFN54YXNBS6K2ST8K9B89Q2AMRWCNYP4JAS5ZOPPZ1WU09MXXTIT27ZPVEG2Y",
"9Y1QXS4XYYDSBMU4N3LW7R3R1WKK",
"CIFJIVHV0K4MSX44QEX2US0MFFEAWJVQ8PJZ",
"26HILZ7GZQN8MB4O17NSPO5XN1JI"),
("7PM82EHP7ZN3ZL7KOPB7B8KYDD1R7EEOYWB6M4SEION47EMS6SMBEA0FNR6U9VAM70HPY4WKXBM8DCF1QOR1LE38NJAVOPOZEBLIU1M05",
"-202WEEIRRLRA9FULGA15RYROVW69ZPDHW0FMYSURBNWB93RNMSLRMIFUPDLP5YOO307XUNEFLU49FV12MI22MLCVZ5JH",
"-3UNIZHA6PAL30Y",
"1Y13W1HYB0QV2Z5RDV9Z7QXEGPLZ6SAA2906T3UKA46E6M4S6O9RMUF5ETYBR2QT15FJZP87JE0W06FA17RYOCZ3AYM3"),
("-ICT39SS0ONER9Z7EAPVXS3BNZDD6WJA791CV5LT8I4POLF6QYXBQGUQG0LVGPVLT0L5Z53BX6WVHWLCI5J9CHCROCKH3B381CCLZ4XAALLMD",
"6T1XIVCPIPXODRK8312KVMCDPBMC7J4K0RWB7PM2V4VMBMODQ8STMYSLIXFN9ORRXCTERWS5U4BLUNA4H6NG8O01IM510NJ5STE",
"-2P2RVZ11QF",
"-3YSI67CCOD8OI1HFF7VF5AWEQ34WK6B8AAFV95U7C04GBXN0R6W5GM5OGOO22HY0KADIUBXSY13435TW4VLHCKLM76VS51W5Z9J"),
("-326JY57SJVC",
"-8H98AQ1OY7CGAOOSG",
"0",
"-326JY57SJVC"),
("-XIYY0P3X9JIDF20ZQG2CN5D2Q5CD9WFDDXRLFZRDKZ8V4TSLE2EHRA31XL3YOHPYLE0I0ZAV2V9RF8AGPCYPVWEIYWWWZ3HVDR64M08VZTBL85PR66Z2F0W5AIDPXIAVLS9VVNLNA6I0PKM87YW4T98P0K",
"-BUBZEC4NTOSCO0XHCTETN4ROPSXIJBTEFYMZ7O4Q1REOZO2SFU62KM3L8D45Z2K4NN3EC4BSRNEE",
"2TX1KWYGAW9LAXUYRXZQENY5P3DSVXJJXK4Y9DWGNZHOWCL5QD5PLLZCE6D0G7VBNP9YGFC0Z9XIPCB",
"-3LNPZ9JK5PUXRZ2Y1EJ4E3QRMAMPKZNI90ZFOBQJM5GZUJ84VMF8EILRGCHZGXJX4AXZF0Z00YA"),
("AZZBGH7AH3S7TVRHDJPJ2DR81H4FY5VJW2JH7O4U7CH0GG2DSDDOSTD06S4UM0HP1HAQ68B2LKKWD73UU0FV5M0H0D0NSXUJI7C2HW3P51H1JM5BHGXK98NNNSHMUB0674VKJ57GVVGY4",
"1LYN8LRN3PY24V0YNHGCW47WUWPLKAE4685LP0J74NZYAIMIBZTAF71",
"6TXVE5E9DXTPTHLEAG7HGFTT0B3XIXVM8IGVRONGSSH1UC0HUASRTZX8TVM2VOK9N9NATPWG09G7MDL6CE9LBKN",
"WY37RSPBTEPQUA23AXB3B5AJRIUL76N3LXLP3KQWKFFSR7PR4E1JWH"),
("1000000000000000000000000000000000000000000000",
"1000000000000000000000000000000000000",
"1000000000",
"0"),
])
{ strings in
let x = BigInt(strings.0, radix: 36)!
let y = BigInt(strings.1, radix: 36)!
let q = BigInt(strings.2, radix: 36)!
let r = BigInt(strings.3, radix: 36)!
let (testQ, testR) = x.quotientAndRemainder(dividingBy: y)
expectEqual(testQ, q)
expectEqual(testR, r)
expectEqual(x, y * q + r)
}
BigIntTests.test("Strings") {
let x = BigInt("-3UNIZHA6PAL30Y", radix: 36)!
expectEqual(x.binaryString, "-1000111001110110011101001110000001011001110110011011110011000010010010")
expectEqual(x.decimalString, "-656993338084259999890")
expectEqual(x.hexString, "-239D9D3816766F3092")
expectEqual(x.compactString, "-3UNIZHA6PAL30Y")
expectTrue(BigInt("12345") == 12345)
expectTrue(BigInt("-12345") == -12345)
expectTrue(BigInt("-3UNIZHA6PAL30Y", radix: 10) == nil)
expectTrue(BigInt("---") == nil)
expectTrue(BigInt(" 123") == nil)
}
BigIntTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()),
BigInt(randomBits: randomBitLength()))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
var BigInt8Tests = TestSuite("BigInt<UInt8>")
BigInt8Tests.test("BinaryInteger interop") {
let x: BigInt8 = 100
let xComp = UInt8(x)
expectTrue(x == xComp)
expectTrue(x < xComp + 1)
expectFalse(xComp + 1 < x)
let y: BigInt8 = -100
let yComp = Int8(y)
expectTrue(y == yComp)
expectTrue(y < yComp + (1 as Int8))
expectFalse(yComp + (1 as Int8) < y)
let zComp = Int.min + 1
let z = BigInt8(zComp)
expectTrue(z == zComp)
expectTrue(zComp == z)
expectFalse(zComp + 1 < z)
expectTrue(z < zComp + 1)
let w = BigInt8(UInt.max)
let wComp = UInt(truncatingIfNeeded: w)
expectTrue(w == wComp)
expectTrue(wComp == w)
expectTrue(wComp - (1 as UInt) < w)
expectFalse(w < wComp - (1 as UInt))
}
BigInt8Tests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()),
BigInt8(randomBits: randomBitLength()))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
BigInt8Tests.test("Bitshift") {
expectEqual(BigInt8(255) << 1, 510)
expectTrue(BigInt(UInt32.max) << 16 == UInt(UInt32.max) << 16)
var (x, y) = (1 as BigInt, 1 as UInt)
for i in 0..<64 { // don't test 64-bit shift, UInt64 << 64 == 0
expectTrue(x << i == y << i)
}
(x, y) = (BigInt(UInt.max), UInt.max)
for i in 0...64 { // test 64-bit shift, should both be zero
expectTrue(x >> i == y >> i,
"\(x) as \(type(of:x)) >> \(i) => \(x >> i) != \(y) as \(type(of:y)) >> \(i) => \(y >> i)")
}
x = BigInt(-1)
let z = -1 as Int
for i in 0..<64 {
expectTrue(x << i == z << i)
}
}
BigInt8Tests.test("Bitwise").forEach(in: [
BigInt8(Int.max - 2),
BigInt8(255),
BigInt8(256),
BigInt8(UInt32.max),
])
{ value in
for x in [value, -value] {
expectTrue(x | 0 == x)
expectTrue(x & 0 == 0)
expectTrue(x & ~0 == x)
expectTrue(x ^ 0 == x)
expectTrue(x ^ ~0 == ~x)
expectTrue(x == BigInt8(Int(truncatingIfNeeded: x)))
expectTrue(~x == BigInt8(~Int(truncatingIfNeeded: x)))
}
}
var BigIntBitTests = TestSuite("BigInt<Bit>")
BigIntBitTests.test("Randomized arithmetic").forEach(in: Array(1...10)) { _ in
// Test x == (x / y) * x + (x % y)
let (x, y) = (
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100))
if !y.isZero {
let (q, r) = x.quotientAndRemainder(dividingBy: y)
expectEqual(q * y + r, x)
expectEqual(q * y, x - r)
}
// Test (x0 + y0)(x1 + y1) == x0x1 + x0y1 + y0x1 + y0y1
let (x0, y0, x1, y1) = (
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100),
BigIntBit(randomBits: randomBitLength() % 100))
let r1 = (x0 + y0) * (x1 + y1)
let r2 = ((x0 * x1) + (x0 * y1), (y0 * x1) + (y0 * y1))
expectEqual(r1, r2.0 + r2.1)
}
BigIntBitTests.test("Conformances") {
// Comparable
let x = BigIntBit(Int.max)
let y = x * x * x * x * x
expectLT(y, y + 1)
expectGT(y, y - 1)
expectGT(y, 0)
let z = -y
expectLT(z, z + 1)
expectGT(z, z - 1)
expectLT(z, 0)
expectEqual(-z, y)
expectEqual(y + z, 0)
// Hashable
expectNotEqual(x.hashValue, y.hashValue)
expectNotEqual(y.hashValue, z.hashValue)
let set = Set([x, y, z])
expectTrue(set.contains(x))
expectTrue(set.contains(y))
expectTrue(set.contains(z))
expectFalse(set.contains(-x))
}
BigIntBitTests.test("words") {
expectEqualSequence([1], (1 as BigIntBit).words)
expectEqualSequence([UInt.max, 0], BigIntBit(UInt.max).words)
expectEqualSequence([UInt.max >> 1], BigIntBit(UInt.max >> 1).words)
expectEqualSequence([0, 1], (BigIntBit(UInt.max) + 1).words)
expectEqualSequence([UInt.max], (-1 as BigIntBit).words)
}
runAllTests()
BigIntTests.test("isMultiple") {
// Test that these do not crash.
expectTrue((0 as _BigInt<UInt>).isMultiple(of: 0))
expectFalse((1 as _BigInt<UInt>).isMultiple(of: 0))
}
|
apache-2.0
|
f93ade8946da063198dab28e8d76d235
| 28.231343 | 224 | 0.608994 | 3.623257 | false | false | false | false |
dreamsxin/swift
|
stdlib/public/core/SetAlgebra.swift
|
1
|
23622
|
//===--- SetAlgebra.swift - Protocols for set operations ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
//
//
//===----------------------------------------------------------------------===//
/// A type that provides mathematical set operations.
///
/// You use types that conform to the `SetAlgebra` protocol when you need
/// efficient membership tests or mathematical set operations such as
/// intersection, union, and subtraction. In the standard library, you can
/// use the `Set` type with elements of any hashable type, or you can easily
/// create bit masks with `SetAlgebra` conformance using the `OptionSet`
/// protocol. See those types for more information.
///
/// - Note: Unlike ordinary set types, the `Element` type of an `OptionSet` is
/// identical to the `OptionSet` type itself. The `SetAlgebra` protocol is
/// specifically designed to accommodate both kinds of set.
///
/// Conforming to the SetAlgebra Protocol
/// =====================================
///
/// When implementing a custom type that conforms to the `SetAlgebra` protocol,
/// you must implement the required initializers and methods. For the
/// inherited methods to work properly, conforming types must meet the
/// following axioms. Assume that `S` is a custom type that conforms to the
/// `SetAlgebra` protocol, `x` and `y` are instances of `S`, and `e` is of
/// type `S.Element`---the type that the set holds.
///
/// - `S() == []`
/// - `x.intersection(x) == x`
/// - `x.intersection([]) == []`
/// - `x.union(x) == x`
/// - `x.union([]) == x`
/// - `x.contains(e)` implies `x.union(y).contains(e)`
/// - `x.union(y).contains(e)` implies `x.contains(e) || y.contains(e)`
/// - `x.contains(e) && y.contains(e)` if and only if
/// `x.intersection(y).contains(e)`
/// - `x.isSubset(of: y)` if and only if `y.isSuperset(of: x)`
/// - `x.isStrictSuperset(of: y)` if and only if
/// `x.isSuperset(of: y) && x != y`
/// - `x.isStrictSubset(of: y)` if and only if `x.isSubset(of: y) && x != y`
///
/// - SeeAlso: `OptionSet`, `Set`
public protocol SetAlgebra : Equatable, ArrayLiteralConvertible {
// FIXME: write tests for SetAlgebra
/// A type for which the conforming type provides a containment test.
associatedtype Element
/// Creates an empty set.
///
/// This initializer is equivalent to initializing with an empty array
/// literal. For example, you create an empty `Set` instance with either
/// this initializer or with an empty array literal.
///
/// var emptySet = Set<Int>()
/// print(emptySet.isEmpty)
/// // Prints "true"
///
/// emptySet = []
/// print(emptySet.isEmpty)
/// // Prints "true"
init()
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
/// For example:
///
/// let primes: Set = [2, 3, 5, 7]
/// let x = 5
/// if primes.contains(x) {
/// print("\(x) is prime!")
/// } else {
/// print("\(x). Not prime.")
/// }
/// // Prints "5 is prime!"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise, `false`.
func contains(_ member: Element) -> Bool
/// Returns a new set with the elements of both this and the given set.
///
/// For example:
///
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Marcia", "Nathaniel"]
/// let attendeesAndVisitors = attendees.union(visitors)
/// print(attendeesAndVisitors)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept. For example:
///
/// let initialIndices = Set(0..<5)
/// let expandedIndices = initialIndices.union([2, 3, 6, 7])
/// print(expandedIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set with the unique elements of this set and `other`.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
func union(_ other: Self) -> Self
/// Returns a new set with the elements that are common to both this set and
/// the given set.
///
/// For example:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
func intersection(_ other: Self) -> Self
/// Returns a new set with the elements that are either in this set or in the
/// given set, but not in both.
///
/// For example:
///
/// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
/// print(eitherNeighborsOrEmployees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
func symmetricDifference(_ other: Self) -> Self
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
/// method has no effect. In this example, a new element is inserted into
/// `classDays`, a set of days of the week. When an existing element is
/// inserted, the `classDays` set does not change.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
/// print(classDays.insert(.monday))
/// // Prints "(true, .monday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// print(classDays.insert(.friday))
/// // Prints "(false, .friday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: `(true, newMember)` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `(false, oldMember)`, where `oldMember` is the
/// element that was equal to `newMember`. In some cases, `oldMember` may
/// be distinguishable from `newMember` by identity comparison or some
/// other means.
@discardableResult
mutating func insert(
_ newMember: Element
) -> (inserted: Bool, memberAfterInsert: Element)
/// Removes the given element and any elements subsumed by the given element.
///
/// - Parameter member: The element of the set to remove.
/// - Returns: For ordinary sets, an element equal to `member` if `member` is
/// contained in the set; otherwise, `nil`. In some cases, a returned
/// element may be distinguishable from `newMember` by identity comparison
/// or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the set
/// and `[member]`, or `nil` if the intersection is empty.
@discardableResult
mutating func remove(_ member: Element) -> Element?
/// Inserts the given element into the set unconditionally.
///
/// If an element equal to `newMember` is already contained in the set,
/// `newMember` replaces the existing element. In this example, an existing
/// element is inserted into `classDays`, a set of days of the week.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
/// print(classDays.update(with: .monday))
/// // Prints "Optional(.monday)"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: For ordinary sets, an element equal to `newMember` if the set
/// already contained such a member; otherwise, `nil`. In some cases, the
/// returned element may be distinguishable from `newMember` by identity
/// comparison or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the
/// set and `[newMember]`, or `nil` if the intersection is empty.
@discardableResult
mutating func update(with newMember: Element) -> Element?
/// Adds the elements of the given set to the set.
///
/// For example:
///
/// var attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors: Set = ["Marcia", "Nathaniel"]
/// attendees.formUnion(visitors)
/// print(attendees)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept. For example:
///
/// var initialIndices = Set(0..<5)
/// initialIndices.formUnion([2, 3, 6, 7])
/// print(initialIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func formUnion(_ other: Self)
/// Removes the elements of this set that aren't also in the given set.
///
/// For example:
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formIntersection(neighbors)
/// print(employees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func formIntersection(_ other: Self)
/// Removes the elements of the set that are also in the given set and
/// adds the members of the given set that are not already in the set.
///
/// For example:
///
/// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type.
mutating func formSymmetricDifference(_ other: Self)
//===--- Requirements with default implementations ----------------------===//
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// For example:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtracting(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
func subtracting(_ other: Self) -> Self
/// Returns a Boolean value that indicates whether the set is a subset of
/// another set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
func isSubset(of other: Self) -> Bool
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given set.
///
/// For example:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
func isDisjoint(with other: Self) -> Bool
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a superset of `possibleSubset`;
/// otherwise, `false`.
func isSuperset(of other: Self) -> Bool
/// A Boolean value that indicates whether the set has no elements.
var isEmpty: Bool { get }
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, like
/// an array or a range:
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// - Parameter sequence: The elements to use as members of the new set.
init<S : Sequence>(_ sequence: S) where S.Iterator.Element == Element
/// Removes the elements of the given set from this set.
///
/// For example:
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func subtract(_ other: Self)
}
/// `SetAlgebra` requirements for which default implementations
/// are supplied.
///
/// - Note: A type conforming to `SetAlgebra` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension SetAlgebra {
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, like
/// an array or a range:
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// - Parameter sequence: The elements to use as members of the new set.
public init<S : Sequence>(_ sequence: S)
where S.Iterator.Element == Element {
self.init()
for e in sequence { insert(e) }
}
/// Creates a set containing the elements of the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// Here, a set of strings is created from an array literal holding only
/// strings:
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.isSuperset(of: ["sugar", "salt"]) {
/// print("Whatever it is, it's bound to be delicious!")
/// }
/// // Prints "Whatever it is, it's bound to be delicious!"
///
/// - Parameter arrayLiteral: A list of elements of the new set.
public init(arrayLiteral: Element...) {
self.init(arrayLiteral)
}
/// Removes the elements of the given set from this set.
///
/// For example:
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
public mutating func subtract(_ other: Self) {
self.formIntersection(self.symmetricDifference(other))
}
/// Returns a Boolean value that indicates whether the set is a subset of
/// another set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
public func isSubset(of other: Self) -> Bool {
return self.intersection(other) == self
}
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a superset of `other`; otherwise,
/// `false`.
public func isSuperset(of other: Self) -> Bool {
return other.isSubset(of: self)
}
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given set.
///
/// For example:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
public func isDisjoint(with other: Self) -> Bool {
return self.intersection(other).isEmpty
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// For example:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtract(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
public func subtracting(_ other: Self) -> Self {
return self.intersection(self.symmetricDifference(other))
}
/// A Boolean value that indicates whether the set has no elements.
public var isEmpty: Bool {
return self == Self()
}
/// Returns a Boolean value that indicates whether this set is a strict
/// superset of the given set.
///
/// Set *A* is a strict superset of another set *B* if every member of *B* is
/// also a member of *A* and *A* contains at least one element that is *not*
/// a member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isStrictSuperset(of: attendees))
/// // Prints "true"
/// print(employees.isStrictSuperset(of: employees))
/// // Prints "false"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a strict superset of `other`; otherwise,
/// `false`.
public func isStrictSuperset(of other: Self) -> Bool {
return self.isSuperset(of: other) && self != other
}
/// Returns a Boolean value that indicates whether this set is a strict
/// subset of the given set.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isStrictSubset(of: employees))
/// // Prints "true"
///
/// // A set is never a strict subset of itself:
/// print(attendees.isStrictSubset(of: attendees))
/// // Prints "false"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a strict subset of `other`; otherwise,
/// `false`.
public func isStrictSubset(of other: Self) -> Bool {
return other.isStrictSuperset(of: self)
}
}
@available(*, unavailable, renamed: "SetAlgebra")
public typealias SetAlgebraType = SetAlgebra
extension SetAlgebra {
@available(*, unavailable, renamed: "intersection")
public func intersect(_ other: Self) -> Self {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "symmetricDifference")
public func exclusiveOr(_ other: Self) -> Self {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "formUnion")
public mutating func unionInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "formIntersection")
public mutating func intersectInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "formSymmetricDifference")
public mutating func exclusiveOrInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isSubset(of:)")
public func isSubsetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isDisjoint(with:)")
public func isDisjointWith(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isSuperset(of:)")
public func isSupersetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "subtract")
public mutating func subtractInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isStrictSuperset(of:)")
public func isStrictSupersetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isStrictSubset(of:)")
public func isStrictSubsetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
}
|
apache-2.0
|
d074727d02c709548c29f768c0794e6f
| 37.91598 | 83 | 0.614681 | 3.987508 | false | false | false | false |
sag333ar/GoogleBooksAPIResearch
|
GoogleBooksApp/GoogleBooksUI/UserInterfaceModules/BookDetails/Wireframe/BookDetailsWireframe.swift
|
1
|
804
|
//
// BookDetailWireframe.swift
// GoogleBooksApp
//
// Created by Kothari, Sagar on 9/9/17.
// Copyright © 2017 Sagar Kothari. All rights reserved.
//
import UIKit
import SafariServices
class BookDetailsWireframe {
var view: BookDetailsView!
}
extension BookDetailsWireframe {
func showInfo(_ urlString: String) {
if let url = URL(string: urlString) {
let svc = SFSafariViewController(url: url)
svc.title = "Information of Book"
view.navigationController?.pushViewController(svc, animated: true)
}
}
func showWebReader(_ urlString: String) {
if let url = URL(string: urlString) {
let svc = SFSafariViewController(url: url)
svc.title = "Webreader of Book"
view.navigationController?.pushViewController(svc, animated: true)
}
}
}
|
apache-2.0
|
a680fc9a3a9185ee9b95c0786317b8d4
| 21.305556 | 72 | 0.691158 | 4.015 | false | false | false | false |
HeartOfCarefreeHeavens/TestKitchen_pww
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBSearchHeaderView.swift
|
1
|
1265
|
//
// CBSearchHeaderView.swift
// TestKitchen
//
// Created by qianfeng on 16/8/18.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CBSearchHeaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
// let searchBar = UISearchBar(frame: CGRectMake(0,0,bounds.size.width,bounds.size.height))
// searchBar.placeholder = "输入菜名或食材搜索"
// searchBar.alpha = 0.5
// addSubview(searchBar)
//用TextField创建searchBar
let textField = UITextField(frame: CGRectMake(40,4,bounds.size.width-40*2,bounds.size.height-4*2))
textField.borderStyle = .RoundedRect
textField.placeholder = "输入菜名或食材搜索"
addSubview(textField)
//左边的搜索图片
let imageView = UIImageView.createImageView("search1")
imageView.frame = CGRectMake(0, 0, 30, 30)
textField.leftView = imageView
textField.leftViewMode = .Always
backgroundColor = UIColor(white: 0.8, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
8dbbd7ec90314be6e8ee7493a2c480a5
| 25.8 | 106 | 0.608624 | 4.14433 | false | false | false | false |
TorinKwok/NSRegExNamedCaptureGroup
|
Tests/String+RegularExpression.swift
|
1
|
1675
|
import Foundation
extension String {
private func _ansiColor( _ formats: [ Int ] ) -> String {
let joinedFormat = formats.map{ String( describing: $0 ) }.joined( separator: ";" )
return "\u{001b}[\(joinedFormat)m"
}
private func _ansiColor( _ format: Int ) -> String {
return _ansiColor( [ format ] )
}
private var _ansiColorNone: String {
return _ansiColor( 0 )
}
var boldInTerminal: String {
return _ansiColor( 1 ) + self + _ansiColorNone
}
var highlightedInTerminal: String {
return _ansiColor( 7 ) + self + _ansiColorNone
}
}
infix operator =~: LogicalConjunctionPrecedence
extension String {
var regularExpression: NSRegularExpression? {
return try? self.regularExpression(
options: [
.caseInsensitive
, .allowCommentsAndWhitespace
, .anchorsMatchLines
] )
}
func regularExpression( options: NSRegularExpression.Options = [] ) throws -> NSRegularExpression {
return try NSRegularExpression( pattern: self, options: options )
}
static func =~( text: String, regex: NSRegularExpression ) -> [ NSTextCheckingResult ] {
return regex.matches( in: text, range: NSMakeRange( 0, text.utf16.count ) )
}
static func =~( text: String, regex: NSRegularExpression ) -> Bool {
return ( text =~ regex ).count > 0
}
static func =~( text: String, regex: NSRegularExpression )
-> ( /*template:*/ String ) -> String {
return { template in
regex.stringByReplacingMatches(
in: text
, options: []
, range: NSMakeRange( 0, text.utf16.count )
, withTemplate: template
)
}
}
}
|
apache-2.0
|
9fb29c83dfdfb9024db3a3d49e90b1fc
| 26.459016 | 101 | 0.627463 | 4.229798 | false | false | false | false |
zeroc-ice/ice-demos
|
swift/Chat/Client.swift
|
1
|
6560
|
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Glacier2
import Ice
import PromiseKit
class Client: ObservableObject {
// MARK: - Public Properties
var session: ChatSessionPrx?
var router: Glacier2.RouterPrx?
var callbackProxy: ChatRoomCallbackPrx?
var acmTimeout: Int32 = 0
// MARK: - Private Properties
private var communicator: Ice.Communicator?
// Bindings
@Published var messages: [ChatMessage] = []
@Published var users: [ChatUser] = []
@Published var isLoggedIn: Bool = false
@Published var loginViewModel = LoginViewModel()
@Published var currentUser: ChatUser! {
didSet { isLoggedIn = (currentUser != nil) }
}
// MARK: - Initialize the client with a communicator
init() {
communicator = Client.loadCommunicator()
}
// MARK: - Client management functions
func attemptLogin(completionBlock: @escaping (String?) -> Void) {
if communicator == nil {
self.communicator = Client.loadCommunicator()
}
guard let communicator = communicator else {
return
}
loginViewModel.connecting = true
var chatsession: ChatSessionPrx?
var acmTimeout: Int32 = 0
do {
let router = uncheckedCast(prx: communicator.getDefaultRouter()!, type: Glacier2.RouterPrx.self)
router.createSessionAsync(userId: loginViewModel.username, password: loginViewModel.password)
.then { session -> Promise<Int32> in
precondition(session != nil)
chatsession = uncheckedCast(prx: session!, type: ChatSessionPrx.self)
return router.getACMTimeoutAsync()
}.then { timeout -> Promise<String> in
acmTimeout = timeout
return router.getCategoryForClientAsync()
}.done { [self] category in
self.session = chatsession
self.acmTimeout = acmTimeout
self.router = router
let adapter = try communicator.createObjectAdapterWithRouter(name: "ChatDemo.Client", rtr: router)
try adapter.activate()
let prx = try adapter.add(servant: ChatRoomCallbackInterceptor(ChatRoomCallbackDisp(self)),
id: Ice.Identity(name: UUID().uuidString, category: category))
callbackProxy = uncheckedCast(prx: prx, type: ChatRoomCallbackPrx.self)
loginViewModel.connecting = false
currentUser = ChatUser(name: loginViewModel.username.lowercased())
completionBlock(nil)
}.catch { err in
if let ex = err as? Glacier2.CannotCreateSessionException {
completionBlock("Session creation failed: \(ex.reason)")
} else if let ex = err as? Glacier2.PermissionDeniedException {
completionBlock("Login failed: \(ex.reason)")
} else if let ex = err as? Ice.EndpointParseException {
completionBlock("Invalid router: \(ex)")
} else {
completionBlock("Error: \(err)")
}
}
}
}
func destroySession() {
messages = []
users = []
currentUser = nil
callbackProxy = nil
if let communicator = communicator {
self.communicator = nil
let router = self.router
self.router = nil
session = nil
// Destroy the session and the communicator asyncrhonously to avoid blocking the main thread.
DispatchQueue.global().async {
do {
try router?.destroySession()
} catch {
print("Destory issue \(error.localizedDescription)")
}
communicator.destroy()
}
}
}
// MARK: - Private setup method
private class func loadCommunicator() -> Ice.Communicator {
var initData = Ice.InitializationData()
let properties = Ice.createProperties()
properties.setProperty(key: "Ice.Plugin.IceSSL", value: "1")
properties.setProperty(key: "Ice.Default.Router",
value: "Glacier2/router:wss -p 443 -h zeroc.com -r /demo-proxy/chat/glacier2 -t 10000")
properties.setProperty(key: "IceSSL.UsePlatformCAs", value: "1")
properties.setProperty(key: "IceSSL.CheckCertName", value: "1")
properties.setProperty(key: "IceSSL.VerifyDepthMax", value: "5")
properties.setProperty(key: "Ice.ACM.Client.Timeout", value: "0")
properties.setProperty(key: "Ice.RetryIntervals", value: "-1")
initData.properties = properties
do {
return try Ice.initialize(initData)
} catch {
print(error)
fatalError()
}
}
}
// MARK: - ChatRoomCallBack functions
extension Client: ChatRoomCallback {
func `init`(users: StringSeq, current _: Current) throws {
self.users = users.map { ChatUser(name: $0) }
}
func send(timestamp: Int64, name: String, message: String, current _: Current) throws {
append(ChatMessage(text: message, who: name, timestamp: timestamp))
}
func join(timestamp: Int64, name: String, current _: Current) throws {
append(ChatMessage(text: "\(name) joined.", who: "System Message", timestamp: timestamp))
users.append(ChatUser(name: name))
}
func leave(timestamp: Int64, name: String, current _: Current) throws {
append(ChatMessage(text: "\(name) left.", who: "System Message", timestamp: timestamp))
users.removeAll(where: { $0.displayName == name })
}
func append(_ message: ChatMessage) {
if messages.count > 100 { // max 100 messages
messages.remove(at: 0)
}
messages.append(message)
}
}
class ChatRoomCallbackInterceptor: Disp {
private let servantDisp: Disp
init(_ servantDisp: Disp) {
self.servantDisp = servantDisp
}
func dispatch(request: Request, current: Current) throws -> Promise<Ice.OutputStream>? {
// Dispatch the request to the main thread in order to modify the UI in a thread safe manner.
return try DispatchQueue.main.sync {
try self.servantDisp.dispatch(request: request, current: current)
}
}
}
|
gpl-2.0
|
e809d1457808805fcc0663b713ee4dd6
| 36.485714 | 118 | 0.587805 | 4.788321 | false | false | false | false |
nayzak/Swift-MVVM
|
Swift MVVM/App/BeerViewModel.swift
|
1
|
468
|
//
// BeerViewModel.swift
//
// Created by NayZaK on 03.03.15.
// Copyright (c) 2015 Amur.net. All rights reserved.
//
import Foundation
class BeerViewModel: ViewModel {
let id: Int
let name: String
let description: String
let abv: String
let breweryName: String
init(model: BeerModel) {
id = model.id
name = model.name
description = model.description
abv = "\(model.abv)"
breweryName = model.brewery.name
super.init()
}
}
|
mit
|
2a9ff8beb8b0d02fc80248583b57f4fd
| 16.37037 | 53 | 0.660256 | 3.272727 | false | false | false | false |
obrichak/discounts
|
discounts/Classes/BarCodeGenerator/RSITFGenerator.swift
|
1
|
1678
|
//
// RSITFGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodeisland.com/int2of5.phtml
class RSITFGenerator: RSAbstractCodeGenerator {
let ITF_CHARACTER_ENCODINGS = [
"00110",
"10001",
"01001",
"11000",
"00101",
"10100",
"01100",
"00011",
"10010",
"01010",
]
override func isValid(contents: String) -> Bool {
return super.isValid(contents) && contents.length() % 2 == 0
}
override func initiator() -> String {
return "1010"
}
override func terminator() -> String {
return "1101"
}
override func barcode(contents: String) -> String {
var barcode = ""
for i in 0..<contents.length() / 2 {
let pair = contents.substring(i * 2, length: 2)
let bars = ITF_CHARACTER_ENCODINGS[pair[0].toInt()!]
let spaces = ITF_CHARACTER_ENCODINGS[pair[1].toInt()!]
for j in 0..<10 {
if j % 2 == 0 {
let bar = bars[j / 2].toInt()
if bar == 1 {
barcode += "11"
} else {
barcode += "1"
}
} else {
let space = spaces[j / 2].toInt()
if space == 1 {
barcode += "00"
} else {
barcode += "0"
}
}
}
}
return barcode
}
}
|
gpl-3.0
|
b5fa4efeb5f73feb86dda3bfce4d7703
| 24.815385 | 68 | 0.426698 | 4.34715 | false | false | false | false |
anirudh24seven/wikipedia-ios
|
Wikipedia/Code/NotificationSettingsViewController.swift
|
1
|
9092
|
import UIKit
import UserNotifications
import WMFModel
protocol NotificationSettingsItem {
var title: String { get }
}
struct NotificationSettingsSwitchItem: NotificationSettingsItem {
let title: String
let switchChecker: () -> Bool
let switchAction: (Bool) -> Void
}
struct NotificationSettingsButtonItem: NotificationSettingsItem {
let title: String
let buttonAction: () -> Void
}
struct NotificationSettingsSection {
let headerTitle:String
let items: [NotificationSettingsItem]
}
class NotificationSettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, WMFAnalyticsContextProviding, WMFAnalyticsContentTypeProviding {
@IBOutlet weak var tableView: UITableView!
var sections = [NotificationSettingsSection]()
var observationToken: NSObjectProtocol?
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0);
tableView.registerNib(WMFSettingsTableViewCell.wmf_classNib(), forCellReuseIdentifier: WMFSettingsTableViewCell.identifier())
tableView.delegate = self
tableView.dataSource = self
observationToken = NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidBecomeActiveNotification, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] (note) in
self?.updateSections()
}
}
deinit {
if let token = observationToken {
NSNotificationCenter.defaultCenter().removeObserver(token)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateSections()
}
func analyticsContext() -> String {
return "notification"
}
func analyticsContentType() -> String {
return "current events"
}
func sectionsForSystemSettingsAuthorized() -> [NotificationSettingsSection] {
var updatedSections = [NotificationSettingsSection]()
let infoItems: [NotificationSettingsItem] = [NotificationSettingsButtonItem(title: localizedStringForKeyFallingBackOnEnglish("settings-notifications-learn-more"), buttonAction: { [weak self] in
let title = localizedStringForKeyFallingBackOnEnglish("welcome-notifications-tell-me-more-title")
let message = "\(localizedStringForKeyFallingBackOnEnglish("welcome-notifications-tell-me-more-storage"))\n\n\(localizedStringForKeyFallingBackOnEnglish("welcome-notifications-tell-me-more-creation"))"
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: localizedStringForKeyFallingBackOnEnglish("welcome-explore-tell-me-more-done-button"), style: UIAlertActionStyle.Default, handler: { (action) in
}))
self?.presentViewController(alertController, animated: true, completion: nil)
})]
let infoSection = NotificationSettingsSection(headerTitle: localizedStringForKeyFallingBackOnEnglish("settings-notifications-info"), items: infoItems)
updatedSections.append(infoSection)
let notificationSettingsItems: [NotificationSettingsItem] = [NotificationSettingsSwitchItem(title: localizedStringForKeyFallingBackOnEnglish("settings-notifications-trending"), switchChecker: { () -> Bool in
return NSUserDefaults.wmf_userDefaults().wmf_inTheNewsNotificationsEnabled()
}, switchAction: { (isOn) in
//This (and everything else that references UNUserNotificationCenter in this class) should be moved into WMFNotificationsController
if #available(iOS 10.0, *) {
if (isOn) {
WMFNotificationsController.sharedNotificationsController().requestAuthenticationIfNecessaryWithCompletionHandler({ (granted, error) in
if let error = error {
self.wmf_showAlertWithError(error)
}
})
} else {
UNUserNotificationCenter.currentNotificationCenter().removeAllPendingNotificationRequests()
}
}
if isOn {
PiwikTracker.sharedInstance()?.wmf_logActionEnableInContext(self, contentType: self)
}else{
PiwikTracker.sharedInstance()?.wmf_logActionDisableInContext(self, contentType: self)
}
NSUserDefaults.wmf_userDefaults().wmf_setInTheNewsNotificationsEnabled(isOn)
})]
let notificationSettingsSection = NotificationSettingsSection(headerTitle: localizedStringForKeyFallingBackOnEnglish("settings-notifications-push-notifications"), items: notificationSettingsItems)
updatedSections.append(notificationSettingsSection)
return updatedSections
}
func sectionsForSystemSettingsUnauthorized() -> [NotificationSettingsSection] {
let unauthorizedItems: [NotificationSettingsItem] = [NotificationSettingsButtonItem(title: localizedStringForKeyFallingBackOnEnglish("settings-notifications-system-turn-on"), buttonAction: {
guard let URL = NSURL(string: UIApplicationOpenSettingsURLString) else {
return
}
UIApplication.sharedApplication().openURL(URL)
})]
return [NotificationSettingsSection(headerTitle: localizedStringForKeyFallingBackOnEnglish("settings-notifications-info"), items: unauthorizedItems)]
}
func updateSections() {
tableView.reloadData()
if #available(iOS 10.0, *) {
UNUserNotificationCenter.currentNotificationCenter().getNotificationSettingsWithCompletionHandler { (settings) in
dispatch_async(dispatch_get_main_queue(), {
switch settings.authorizationStatus {
case .Authorized:
fallthrough
case .NotDetermined:
self.sections = self.sectionsForSystemSettingsAuthorized()
break
case .Denied:
self.sections = self.sectionsForSystemSettingsUnauthorized()
break
}
self.tableView.reloadData()
})
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier(WMFSettingsTableViewCell.identifier(), forIndexPath: indexPath) as? WMFSettingsTableViewCell else {
return UITableViewCell()
}
let item = sections[indexPath.section].items[indexPath.item]
cell.title = item.title
cell.iconName = nil
if let switchItem = item as? NotificationSettingsSwitchItem {
cell.disclosureType = .Switch
cell.disclosureSwitch.on = switchItem.switchChecker()
cell.disclosureSwitch.addTarget(self, action: #selector(self.handleSwitchValueChange(_:)), forControlEvents: .ValueChanged)
} else {
cell.disclosureType = .ViewController
}
return cell
}
func handleSwitchValueChange(sender: UISwitch) {
// FIXME: hardcoded item below
let item = sections[1].items[0]
if let switchItem = item as? NotificationSettingsSwitchItem {
switchItem.switchAction(sender.on)
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = WMFTableHeaderLabelView.wmf_viewFromClassNib()
header.text = sections[section].headerTitle
return header;
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let header = WMFTableHeaderLabelView.wmf_viewFromClassNib()
header.text = sections[section].headerTitle
return header.heightWithExpectedWidth(self.view.frame.width)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard let item = sections[indexPath.section].items[indexPath.item] as? NotificationSettingsButtonItem else {
return
}
item.buttonAction()
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return sections[indexPath.section].items[indexPath.item] as? NotificationSettingsSwitchItem == nil
}
}
|
mit
|
011ba29641779e2b18166a90aad079a7
| 44.46 | 215 | 0.67015 | 5.961967 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings
|
Food Hygiene Ratings/AdvancedSearchViewController.swift
|
1
|
7459
|
//
// AdvancedSearchViewController.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 23/02/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import UIKit
class AdvancedSearchViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var businessNameTextField: UITextField!
@IBOutlet weak var placeNameTextField: UITextField!
@IBOutlet weak var localAuthorityCell: UITableViewCell!
@IBOutlet weak var comparisonCell: UITableViewCell!
@IBOutlet weak var ratingsCell: UITableViewCell!
@IBOutlet weak var businessTypeCell: UITableViewCell!
@IBOutlet weak var scottishRatingCell: UITableViewCell!
@IBAction func unwindWithSelectedListItem(segue:UIStoryboardSegue) {
if let vc = segue.source as? ListViewController {
if let selected = vc.selectedItem {
switch vc.id {
case ratingValueListId:
ratingValue = selected
case ratingOperatorListId:
ratingOperator = selected
case localAuthorityListId:
localAuthority = selected
case businessTypeListId:
businessType = selected
case scottishRatingListId:
scottishRating = selected
default:
break
}
}
}
}
var ratingValue : String? {
didSet {
ratingsCell.detailTextLabel?.text = ratingValue
}
}
var ratingOperator : String? {
didSet {
comparisonCell.detailTextLabel?.text = ratingOperator
}
}
var localAuthority : String? {
didSet {
localAuthorityCell.detailTextLabel?.text = localAuthority
}
}
var businessType : String? {
didSet{
businessTypeCell.detailTextLabel?.text = businessType
}
}
var scottishRating : String? {
didSet{
scottishRatingCell.detailTextLabel?.text = scottishRating
}
}
let segueSearchId = "segueAdvancedSearch"
let segueSelectRating = "segueRatingsValue"
let segueSelectOperator = "segueRatingsOperator"
let segueLocalAuthority = "segueLocalAuthority"
let segueBusinessType = "segueBusinessType"
let segueScottishRating = "segueScottishRating"
let ratingValueListId = 0
let ratingOperatorListId = 1
let localAuthorityListId = 2
let businessTypeListId = 3
let scottishRatingListId = 4
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
businessNameTextField.delegate = self
placeNameTextField.delegate = self
}
// override func viewDidAppear(_ animated: Bool) {
// businessNameTextField.becomeFirstResponder()
// }
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField === businessNameTextField {
businessNameTextField.resignFirstResponder()
placeNameTextField.becomeFirstResponder()
} else if textField === placeNameTextField {
placeNameTextField.resignFirstResponder()
performSegue(withIdentifier: segueSearchId, sender: self)
}
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier! {
case segueSearchId:
let query = createQuery()
MainModel.sharedInstance.findEstablishments(query: query)
case segueSelectRating:
if let vc = segue.destination as? ListViewController {
vc.listItems = FoodHygieneAPI.ratingsValues
let selected = ratingValue ?? FoodHygieneAPI.ratingsValues[0]
vc.selectedItem = selected
vc.id = ratingValueListId
vc.title = "Rating"
}
case segueSelectOperator:
if let vc = segue.destination as? ListViewController {
vc.listItems = FoodHygieneAPI.ratingsOperators
let selected = ratingOperator ?? FoodHygieneAPI.ratingsOperators[0]
vc.selectedItem = selected
vc.id = ratingOperatorListId
vc.title = "Rating Comparison"
}
case segueLocalAuthority:
if let vc = segue.destination as? ListViewController {
vc.listItems = MainModel.sharedInstance.localAuthorities.map(){$0.name}
vc.listItems.insert("All", at: 0)
let selected = localAuthority ?? "All"
vc.selectedItem = selected
vc.id = localAuthorityListId
vc.title = "Local Authority"
}
case segueBusinessType:
if let vc = segue.destination as? ListViewController {
vc.listItems = Business.businessNames
let selected = businessType ?? vc.listItems[0]
vc.selectedItem = selected
vc.id = businessTypeListId
vc.title = "Business Type"
}
case segueScottishRating:
if let vc = segue.destination as? ListViewController {
vc.listItems = Rating.scottishRatingNames
let selected = scottishRating ?? vc.listItems[0]
vc.selectedItem = selected
vc.id = scottishRatingListId
vc.title = "Rating Status"
}
default:
break
}
}
fileprivate func createQuery() -> Query {
var query = Query()
if let name = businessNameTextField.text {
if name != "" {
query.businessName = name.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
if let place = placeNameTextField.text {
if place != "" {
query.placeName = place.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
if let rating = ratingValue {
query.ratingValue = rating
}
if let operatorKey = ratingOperator {
query.ratingOperator = operatorKey
}
if let laName = localAuthority {
if laName != "All" {
let la = MainModel.sharedInstance.localAuthorities.first(){
$0.name == laName
}
query.localAuthorityId = la?.searchCode
}
}
if let busType = businessType {
if busType != "All"
{
let busTypeIndex = Business.businessNames.index(of: busType)
if let index = busTypeIndex {
query.businessType = Business.businessTypes[index]
}
}
}
if let rating = scottishRating {
let ratingKey = rating.replacingOccurrences(of: " ", with: "")
query.ratingValue = ratingKey
}
return query
}
}
|
apache-2.0
|
cb1d17857a220a4a5d56b8c4c75d93c1
| 35.203883 | 113 | 0.59292 | 5.388728 | false | false | false | false |
Johnykutty/SwiftLint
|
Source/SwiftLintFramework/Rules/OperatorUsageWhitespaceRule.swift
|
2
|
7630
|
//
// OperatorUsageWhitespaceRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/13/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct OperatorUsageWhitespaceRule: OptInRule, CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "operator_usage_whitespace",
name: "Operator Usage Whitespace",
description: "Operators should be surrounded by a single whitespace " +
"when they are being used.",
nonTriggeringExamples: [
"let foo = 1 + 2\n",
"let foo = 1 > 2\n",
"let foo = !false\n",
"let foo: Int?\n",
"let foo: Array<String>\n",
"let foo: [String]\n",
"let foo = 1 + \n 2\n",
"let range = 1...3\n",
"let range = 1 ... 3\n",
"let range = 1..<3\n",
"#if swift(>=3.0)\n",
"array.removeAtIndex(-200)\n",
"let name = \"image-1\"\n",
"button.setImage(#imageLiteral(resourceName: \"image-1\"), for: .normal)\n",
"let doubleValue = -9e-11\n"
],
triggeringExamples: [
"let foo = 1↓+2\n",
"let foo = 1↓ + 2\n",
"let foo = 1↓ + 2\n",
"let foo = 1↓ + 2\n",
"let foo↓=1↓+2\n",
"let foo↓=1 + 2\n",
"let foo↓=bar\n",
"let range = 1↓ ..< 3\n",
"let foo = bar↓ ?? 0\n",
"let foo = bar↓??0\n",
"let foo = bar↓ != 0\n",
"let foo = bar↓ !== bar2\n",
"let v8 = Int8(1)↓ << 6\n",
"let v8 = 1↓ << (6)\n",
"let v8 = 1↓ << (6)\n let foo = 1 > 2\n"
],
corrections: [
"let foo = 1↓+2\n": "let foo = 1 + 2\n",
"let foo = 1↓ + 2\n": "let foo = 1 + 2\n",
"let foo = 1↓ + 2\n": "let foo = 1 + 2\n",
"let foo = 1↓ + 2\n": "let foo = 1 + 2\n",
"let foo↓=1↓+2\n": "let foo = 1 + 2\n",
"let foo↓=1 + 2\n": "let foo = 1 + 2\n",
"let foo↓=bar\n": "let foo = bar\n",
"let range = 1↓ ..< 3\n": "let range = 1..<3\n",
"let foo = bar↓ ?? 0\n": "let foo = bar ?? 0\n",
"let foo = bar↓??0\n": "let foo = bar ?? 0\n",
"let foo = bar↓ != 0\n": "let foo = bar != 0\n",
"let foo = bar↓ !== bar2\n": "let foo = bar !== bar2\n",
"let v8 = Int8(1)↓ << 6\n": "let v8 = Int8(1) << 6\n",
"let v8 = 1↓ << (6)\n": "let v8 = 1 << (6)\n",
"let v8 = 1↓ << (6)\n let foo = 1 > 2\n": "let v8 = 1 << (6)\n let foo = 1 > 2\n"
]
)
public func validate(file: File) -> [StyleViolation] {
return violationRanges(file: file).map { range, _ in
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location))
}
}
private func violationRanges(file: File) -> [(NSRange, String)] {
let escapedOperators = ["/", "=", "-", "+", "*", "|", "^", "~"].map({ "\\\($0)" }).joined()
let rangePattern = "\\.\\.(?:\\.|<)" // ... or ..<
let notEqualsPattern = "\\!\\=\\=?" // != or !==
let coalescingPattern = "\\?{2}"
let operators = "(?:[\(escapedOperators)%<>&]+|\(rangePattern)|\(coalescingPattern)|" +
"\(notEqualsPattern))"
let oneSpace = "[^\\S\\r\\n]" // to allow lines ending with operators to be valid
let zeroSpaces = oneSpace + "{0}"
let manySpaces = oneSpace + "{2,}"
let leadingVariableOrNumber = "(?:\\b|\\))"
let trailingVariableOrNumber = "(?:\\b|\\()"
let spaces = [(zeroSpaces, zeroSpaces), (oneSpace, manySpaces),
(manySpaces, oneSpace), (manySpaces, manySpaces)]
let patterns = spaces.map { first, second in
leadingVariableOrNumber + first + operators + second + trailingVariableOrNumber
}
let pattern = "(?:\(patterns.joined(separator: "|")))"
let genericPattern = "<(?:\(oneSpace)|\\S)+?>" // not using dot to avoid matching new line
let validRangePattern = leadingVariableOrNumber + zeroSpaces + rangePattern +
zeroSpaces + trailingVariableOrNumber
let excludingPattern = "(?:\(genericPattern)|\(validRangePattern))"
let excludingKinds = SyntaxKind.commentAndStringKinds() + [.objectLiteral]
return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds,
excludingPattern: excludingPattern).flatMap { range in
// if it's only a number (i.e. -9e-11), it shouldn't trigger
guard kinds(in: range, file: file) != [.number] else {
return nil
}
let spacesPattern = oneSpace + "*"
let rangeRegex = regex(spacesPattern + rangePattern + spacesPattern)
// if it's a range operator, the correction shouldn't have spaces
if let matchRange = rangeRegex.firstMatch(in: file.contents, options: [], range: range)?.range {
let correction = operatorInRange(file: file, range: matchRange)
return (matchRange, correction)
}
let pattern = spacesPattern + operators + spacesPattern
let operatorsRegex = regex(pattern)
guard let matchRange = operatorsRegex.firstMatch(in: file.contents,
options: [], range: range)?.range else {
return nil
}
let operatorContent = operatorInRange(file: file, range: matchRange)
let correction = " " + operatorContent + " "
return (matchRange, correction)
}
}
private func kinds(in range: NSRange, file: File) -> [SyntaxKind] {
let contents = file.contents.bridge()
guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length) else {
return []
}
return file.syntaxMap.tokens(inByteRange: byteRange).flatMap { SyntaxKind(rawValue: $0.type) }
}
private func operatorInRange(file: File, range: NSRange) -> String {
return file.contents.bridge().substring(with: range).trimmingCharacters(in: .whitespaces)
}
public func correct(file: File) -> [Correction] {
let violatingRanges = violationRanges(file: file).filter { range, _ in
return !file.ruleEnabled(violatingRanges: [range], for: self).isEmpty
}
var correctedContents = file.contents
var adjustedLocations = [Int]()
for (violatingRange, correction) in violatingRanges.reversed() {
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) {
correctedContents = correctedContents
.replacingCharacters(in: indexRange, with: correction)
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
}
|
mit
|
e468a9b3db1f6d47161fd5689ffa1073
| 40.79558 | 109 | 0.526504 | 3.998414 | false | false | false | false |
citysite102/kapi-kaffeine
|
kapi-kaffeine/KPNewRatingRequest.swift
|
1
|
2525
|
//
// KPNewRatingRequest.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/6/19.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
import ObjectMapper
import PromiseKit
import Alamofire
class KPNewRatingRequest: NetworkRequest {
enum requestType {
case put
case add
}
typealias ResponseType = RawJsonResult
private var cafeID: String?
private var wifi: NSNumber?
private var seat: NSNumber?
private var food: NSNumber?
private var quiet: NSNumber?
private var tasty: NSNumber?
private var cheap: NSNumber?
private var music: NSNumber?
private var type: requestType?
var method: Alamofire.HTTPMethod {
return self.type == requestType.add ?
.post :
.put }
var endpoint: String { return "/rates" }
var parameters: [String : Any]? {
var parameters = [String : Any]()
parameters["member_id"] = KPUserManager.sharedManager.currentUser?.identifier
parameters["cafe_id"] = cafeID
if wifi?.intValue ?? 0 != 0 {
parameters["wifi"] = wifi
}
if seat?.intValue ?? 0 != 0 {
parameters["seat"] = seat
}
if food?.intValue ?? 0 != 0 {
parameters["food"] = food
}
if quiet?.intValue ?? 0 != 0 {
parameters["quiet"] = quiet
}
if tasty?.intValue ?? 0 != 0 {
parameters["tasty"] = tasty
}
if cheap?.intValue ?? 0 != 0 {
parameters["cheap"] = cheap
}
if music?.intValue ?? 0 != 0 {
parameters["music"] = music
}
return parameters
}
public func perform(_ cafeID: String,
_ wifi: NSNumber? = 0,
_ seat: NSNumber? = 0,
_ food: NSNumber? = 0,
_ quiet: NSNumber? = 0,
_ tasty: NSNumber? = 0,
_ cheap: NSNumber? = 0,
_ music: NSNumber? = 0,
_ type: requestType) -> Promise<(ResponseType)> {
self.cafeID = cafeID
self.wifi = wifi
self.seat = seat
self.food = food
self.quiet = quiet
self.tasty = tasty
self.cheap = cheap
self.music = music
self.type = type
return networkClient.performRequest(self).then(execute: responseHandler)
}
}
|
mit
|
d9ed77e729496bba3b9223d45a067c40
| 26.714286 | 85 | 0.515067 | 4.619048 | false | false | false | false |
huangboju/Moots
|
算法学习/LeetCode/LeetCode/Trap.swift
|
1
|
1025
|
//
// Trap.swift
// LeetCode
//
// Created by jourhuang on 2021/4/24.
// Copyright © 2021 伯驹 黄. All rights reserved.
//
import Foundation
//height = [0,1,0,2,1,0,1,3,2,1,2,1]
// https://leetcode-cn.com/problems/trapping-rain-water/
func trap(_ height: [Int]) -> Int {
if height.count <= 2 {
return 0
}
var leftMax = 0
var rightMax = 0
var result = 0
var left = 0, right = height.count - 1
while left <= right {
// 说明左墙可靠
if leftMax <= rightMax {
let water = leftMax - height[left]
if water < 0 {
leftMax = height[left]
} else {
result += water
}
left += 1
} else {
// 说明右墙可靠
let water = rightMax - height[right]
if water < 0 {
rightMax = height[right]
} else {
result += water
}
right -= 1
}
}
return result
}
|
mit
|
f14d8948f4bfef5cc7de3894dda700fb
| 21.088889 | 56 | 0.459759 | 3.627737 | false | false | false | false |
aktowns/swen
|
Sources/Swen/Timer.swift
|
1
|
1779
|
//
// Timer.swift created on 28/12/15
// Swen project
//
// Copyright 2015 Ashley Towns <[email protected]>
//
// 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 CSDL
public class Timer {
var startTicks: UInt32 = 0
var pauseTicks: Uint32 = 0
var paused: Bool = false
var started: Bool = false
public func start() {
self.started = true
self.paused = false
self.startTicks = 0
self.pauseTicks = 0
}
public func stop() {
self.started = false
self.paused = false
self.startTicks = 0
self.pauseTicks = 0
}
public func pause() {
if self.started && !self.paused {
self.paused = true
self.pauseTicks = Timer.globalTicks() - self.startTicks
self.startTicks = 0
}
}
public func unpause() {
if self.started && self.paused {
self.paused = false
self.startTicks = Timer.globalTicks() - self.pauseTicks
self.pauseTicks = 0
}
}
public func ticks() -> UInt32 {
var time: Uint32 = 0
if started {
if paused {
time = self.pauseTicks
} else {
time = Timer.globalTicks() - startTicks
}
}
return time
}
public static func globalTicks() -> UInt32 {
return SDL_GetTicks()
}
}
|
apache-2.0
|
4653a582b96b19450ced183ede5650f1
| 21.518987 | 77 | 0.639123 | 3.745263 | false | false | false | false |
xiaoxionglaoshi/SwiftProgramming
|
007 ClosuresDemo/007 ClosuresDemo/DNCustomView.swift
|
1
|
1068
|
//
// DNCustomView.swift
// 007 ClosuresDemo
//
// Created by mainone on 16/10/13.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
//定义一个无参数,无返回值的闭包类型
typealias ClickBlock = (() -> ())
class DNCustomView: UIView {
var btnClickBlock: ClickBlock?
override init(frame: CGRect) {
super.init(frame: frame)
let button = UIButton(type: .custom)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setTitle("点我啊", for: .normal)
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(DNCustomView.btnClick), for: .touchUpInside)
self.addSubview(button)
}
func btnClick() {
if self.btnClickBlock != nil {
//点击按钮执行闭包
//注意:属性btnClickBlock是可选类型,需要先解包
self.btnClickBlock!()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
e05b1d0e8ed21159c2ec6ab13f08386b
| 25.459459 | 93 | 0.61287 | 3.779923 | false | false | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Services/Comprehend/Comprehend_Error.swift
|
1
|
6022
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Comprehend
public struct ComprehendErrorType: AWSErrorType {
enum Code: String {
case batchSizeLimitExceededException = "BatchSizeLimitExceededException"
case concurrentModificationException = "ConcurrentModificationException"
case internalServerException = "InternalServerException"
case invalidFilterException = "InvalidFilterException"
case invalidRequestException = "InvalidRequestException"
case jobNotFoundException = "JobNotFoundException"
case kmsKeyValidationException = "KmsKeyValidationException"
case resourceInUseException = "ResourceInUseException"
case resourceLimitExceededException = "ResourceLimitExceededException"
case resourceNotFoundException = "ResourceNotFoundException"
case resourceUnavailableException = "ResourceUnavailableException"
case textSizeLimitExceededException = "TextSizeLimitExceededException"
case tooManyRequestsException = "TooManyRequestsException"
case tooManyTagKeysException = "TooManyTagKeysException"
case tooManyTagsException = "TooManyTagsException"
case unsupportedLanguageException = "UnsupportedLanguageException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Comprehend
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The number of documents in the request exceeds the limit of 25. Try your request again with fewer documents.
public static var batchSizeLimitExceededException: Self { .init(.batchSizeLimitExceededException) }
/// Concurrent modification of the tags associated with an Amazon Comprehend resource is not supported.
public static var concurrentModificationException: Self { .init(.concurrentModificationException) }
/// An internal server error occurred. Retry your request.
public static var internalServerException: Self { .init(.internalServerException) }
/// The filter specified for the operation is invalid. Specify a different filter.
public static var invalidFilterException: Self { .init(.invalidFilterException) }
/// The request is invalid.
public static var invalidRequestException: Self { .init(.invalidRequestException) }
/// The specified job was not found. Check the job ID and try again.
public static var jobNotFoundException: Self { .init(.jobNotFoundException) }
/// The KMS customer managed key (CMK) entered cannot be validated. Verify the key and re-enter it.
public static var kmsKeyValidationException: Self { .init(.kmsKeyValidationException) }
/// The specified resource name is already in use. Use a different name and try your request again.
public static var resourceInUseException: Self { .init(.resourceInUseException) }
/// The maximum number of resources per account has been exceeded. Review the resources, and then try your request again.
public static var resourceLimitExceededException: Self { .init(.resourceLimitExceededException) }
/// The specified resource ARN was not found. Check the ARN and try your request again.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// The specified resource is not available. Check the resource and try your request again.
public static var resourceUnavailableException: Self { .init(.resourceUnavailableException) }
/// The size of the input text exceeds the limit. Use a smaller document.
public static var textSizeLimitExceededException: Self { .init(.textSizeLimitExceededException) }
/// The number of requests exceeds the limit. Resubmit your request later.
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
/// The request contains more tag keys than can be associated with a resource (50 tag keys per resource).
public static var tooManyTagKeysException: Self { .init(.tooManyTagKeysException) }
/// The request contains more tags than can be associated with a resource (50 tags per resource). The maximum number of tags includes both existing tags and those included in your current request.
public static var tooManyTagsException: Self { .init(.tooManyTagsException) }
/// Amazon Comprehend can't process the language of the input text. For all custom entity recognition APIs (such as CreateEntityRecognizer), only English, Spanish, French, Italian, German, or Portuguese are accepted. For most other APIs, such as those for Custom Classification, Amazon Comprehend accepts text in all supported languages. For a list of supported languages, see supported-languages.
public static var unsupportedLanguageException: Self { .init(.unsupportedLanguageException) }
}
extension ComprehendErrorType: Equatable {
public static func == (lhs: ComprehendErrorType, rhs: ComprehendErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ComprehendErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
|
apache-2.0
|
d939614ac7cefea2a895ba011c46ba77
| 58.039216 | 401 | 0.733311 | 5.46461 | false | false | false | false |
jpush/jchat-swift
|
JChat/Src/UserModule/ViewController/JCMineViewController.swift
|
1
|
6901
|
//
// JCMineViewController.swift
// JChat
//
// Created by JIGUANG on 2017/2/16.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCMineViewController: UIViewController {
//MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
deinit {
NotificationCenter.default.removeObserver(self)
JMessage.remove(self, with: nil)
}
fileprivate lazy var tableview: UITableView = {
let tableview = UITableView(frame: self.view.frame, style: .grouped)
tableview.delegate = self
tableview.dataSource = self
tableview.separatorStyle = .none
tableview.register(JCMineInfoCell.self, forCellReuseIdentifier: "JCMineInfoCell")
tableview.register(JCMineAvatorCell.self, forCellReuseIdentifier: "JCMineAvatorCell")
tableview.register(JCButtonCell.self, forCellReuseIdentifier: "JCButtonCell")
return tableview
}()
//MARK: - private func
private func _init() {
view.backgroundColor = .white
view.addSubview(tableview)
JMessage.add(self, with: nil)
NotificationCenter.default.addObserver(self, selector: #selector(_updateUserInfo), name: NSNotification.Name(rawValue: kUpdateUserInfo), object: nil)
}
@objc func _updateUserInfo() {
tableview.reloadData()
}
func updateCurrentUserAvator() {
JMSGUser.myInfo().thumbAvatarData({ (data, id, error) in
if let data = data {
let imageData = NSKeyedArchiver.archivedData(withRootObject: data)
UserDefaults.standard.set(imageData, forKey: kLastUserAvator)
} else {
UserDefaults.standard.removeObject(forKey: kLastUserAvator)
}
})
}
}
extension JCMineViewController: JMessageDelegate {
func onReceive(_ event: JMSGUserLoginStatusChangeEvent!) {
switch event.eventType.rawValue {
case JMSGLoginStatusChangeEventType.eventNotificationCurrentUserInfoChange.rawValue:
updateCurrentUserAvator()
tableview.reloadData()
default:
break
}
}
}
extension JCMineViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 85
}
if indexPath.section == 2 {
return 40
}
return 45
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 || section == 2 {
return 1
}
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
return tableView.dequeueReusableCell(withIdentifier: "JCMineAvatorCell", for: indexPath)
}
if indexPath.section == 2 {
return tableView.dequeueReusableCell(withIdentifier: "JCButtonCell", for: indexPath)
}
return tableView.dequeueReusableCell(withIdentifier: "JCMineInfoCell", for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.selectionStyle = .none
if indexPath.section == 2 {
guard let cell = cell as? JCButtonCell else {
return
}
cell.delegate = self
return
}
cell.accessoryType = .disclosureIndicator
if indexPath.section == 0 {
guard let cell = cell as? JCMineAvatorCell else {
return
}
let user = JMSGUser.myInfo()
cell.baindDate(user: user)
return
}
guard let cell = cell as? JCMineInfoCell else {
return
}
if indexPath.section == 1 && indexPath.row == 1 {
cell.delegate = self
cell.accessoryType = .none
cell.isShowSwitch = true
}
switch indexPath.row {
case 0:
cell.title = "修改密码"
case 1:
cell.isSwitchOn = JMessage.isSetGlobalNoDisturb()
cell.title = "免打扰"
case 2:
cell.title = "意见反馈"
case 3:
cell.title = "关于JChat"
default:
break
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
let vc = JCMyInfoViewController()
navigationController?.pushViewController(vc, animated: true)
return
}
switch indexPath.row {
case 0:
navigationController?.pushViewController(JCUpdatePassworkViewController(), animated: true)
case 2:
navigationController?.pushViewController(JCFeedbackViewController(), animated: true)
case 3:
navigationController?.pushViewController(JCJChatInfoViewController(), animated: true)
default:
break
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0001
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 {
return 5
}
return 15
}
}
extension JCMineViewController: UIAlertViewDelegate {
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
switch buttonIndex {
case 1:
JMSGUser.logout({ (result, error) in
JCVerificationInfoDB.shareInstance.queue = nil
UserDefaults.standard.removeObject(forKey: kCurrentUserName)
UserDefaults.standard.removeObject(forKey: kCurrentUserPassword)
let appDelegate = UIApplication.shared.delegate
let window = appDelegate?.window!
window?.rootViewController = JCNavigationController(rootViewController: JCLoginViewController())
})
default:
break
}
}
}
extension JCMineViewController: JCMineInfoCellDelegate {
func mineInfoCell(clickSwitchButton button: UISwitch, indexPath: IndexPath?) {
JMessage.setIsGlobalNoDisturb(button.isOn) { (result, error) in
}
}
}
extension JCMineViewController: JCButtonCellDelegate {
func buttonCell(clickButton button: UIButton) {
let alertView = UIAlertView(title: "", message: "确定要退出登录?", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
alertView.show()
}
}
|
mit
|
2a39de09db31e8fd53715e26b76c7729
| 31.76555 | 157 | 0.615508 | 5.068838 | false | false | false | false |
KarlWarfel/nutshell-ios
|
Nutshell/DataModel/CoreData/TimeChange.swift
|
1
|
946
|
//
// TimeChange.swift
// Nutshell
//
// Created by Brian King on 9/15/15.
// Copyright © 2015 Tidepool. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
class TimeChange: DeviceMetadata {
override class func fromJSON(json: JSON, moc: NSManagedObjectContext) -> TimeChange? {
if let entityDescription = NSEntityDescription.entityForName("TimeChange", inManagedObjectContext: moc) {
let me = TimeChange(entity: entityDescription, insertIntoManagedObjectContext: nil)
me.changeFrom = NutUtils.dateFromJSON(json["changeFrom"].string)
me.changeTo = NutUtils.dateFromJSON(json["changeTo"].string)
me.changeAgent = json["changeAgent"].string
me.changeTimezone = json["changeTimezone"].string
me.changeReasons = json["changeReasons"].string
return me
}
return nil
}
}
|
bsd-2-clause
|
b965de0c2d1b047715b60c8aff7bdb4e
| 31.586207 | 113 | 0.653968 | 4.821429 | false | false | false | false |
eeschimosu/SwiftPages
|
SwiftPages/SwiftPages.swift
|
1
|
12180
|
//
// SwiftPages.swift
// SwiftPages
//
// Created by Gabriel Alvarado on 6/27/15.
// Copyright (c) 2015 Gabriel Alvarado. All rights reserved.
//
import UIKit
public class SwiftPages: UIView, UIScrollViewDelegate {
//Items variables
private var containerView: UIView!
private var scrollView: UIScrollView!
private var topBar: UIView!
private var animatedBar: UIView!
private var viewControllerIDs: [String] = []
private var buttonTitles: [String] = []
private var buttonImages: [UIImage] = []
private var pageViews: [UIViewController?] = []
//Container view position variables
private var xOrigin: CGFloat = 0
private var yOrigin: CGFloat = 64
private var distanceToBottom: CGFloat = 0
//Color variables
private var animatedBarColor = UIColor(red: 28/255, green: 95/255, blue: 185/255, alpha: 1)
private var topBarBackground = UIColor.whiteColor()
private var buttonsTextColor = UIColor.grayColor()
private var containerViewBackground = UIColor.whiteColor()
//Item size variables
private var topBarHeight: CGFloat = 52
private var animatedBarHeight: CGFloat = 3
//Bar item variables
private var aeroEffectInTopBar: Bool = false //This gives the top bap a blurred effect, also overlayes the it over the VC's
private var buttonsWithImages: Bool = false
private var barShadow: Bool = true
private var buttonsTextFontAndSize: UIFont = UIFont(name: "HelveticaNeue-Light", size: 20)!
// MARK: - Positions Of The Container View API -
public func setOriginX (origin : CGFloat) { xOrigin = origin }
public func setOriginY (origin : CGFloat) { yOrigin = origin }
public func setDistanceToBottom (distance : CGFloat) { distanceToBottom = distance }
// MARK: - API's -
public func setAnimatedBarColor (color : UIColor) { animatedBarColor = color }
public func setTopBarBackground (color : UIColor) { topBarBackground = color }
public func setButtonsTextColor (color : UIColor) { buttonsTextColor = color }
public func setContainerViewBackground (color : UIColor) { containerViewBackground = color }
public func setTopBarHeight (pointSize : CGFloat) { topBarHeight = pointSize}
public func setAnimatedBarHeight (pointSize : CGFloat) { animatedBarHeight = pointSize}
public func setButtonsTextFontAndSize (fontAndSize : UIFont) { buttonsTextFontAndSize = fontAndSize}
public func enableAeroEffectInTopBar (boolValue : Bool) { aeroEffectInTopBar = boolValue}
public func enableButtonsWithImages (boolValue : Bool) { buttonsWithImages = boolValue}
public func enableBarShadow (boolValue : Bool) { barShadow = boolValue}
override public func drawRect(rect: CGRect)
{
// MARK: - Size Of The Container View -
var pagesContainerHeight = self.frame.height - yOrigin - distanceToBottom
var pagesContainerWidth = self.frame.width
//Set the containerView, every item is constructed relative to this view
containerView = UIView(frame: CGRectMake(xOrigin, yOrigin, pagesContainerWidth, pagesContainerHeight))
containerView.backgroundColor = containerViewBackground
self.addSubview(containerView)
//Set the scrollview
if (aeroEffectInTopBar) {
scrollView = UIScrollView(frame: CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height))
} else {
scrollView = UIScrollView(frame: CGRectMake(0, topBarHeight, containerView.frame.size.width, containerView.frame.size.height - topBarHeight))
}
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.delegate = self
scrollView.backgroundColor = UIColor.clearColor()
containerView.addSubview(scrollView)
//Set the top bar
topBar = UIView(frame: CGRectMake(0, 0, containerView.frame.size.width, topBarHeight))
topBar.backgroundColor = topBarBackground
if (aeroEffectInTopBar) {
//Create the blurred visual effect
//You can choose between ExtraLight, Light and Dark
topBar.backgroundColor = UIColor.clearColor()
let blurEffect: UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = topBar.bounds
blurView.setTranslatesAutoresizingMaskIntoConstraints(false)
topBar.addSubview(blurView)
}
containerView.addSubview(topBar)
//Set the top bar buttons
var buttonsXPosition: CGFloat = 0
var buttonNumber = 0
//Check to see if the top bar will be created with images ot text
if (!buttonsWithImages) {
for item in buttonTitles
{
var barButton: UIButton!
barButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, containerView.frame.size.width/(CGFloat)(viewControllerIDs.count), topBarHeight))
barButton.backgroundColor = UIColor.clearColor()
barButton.titleLabel!.font = buttonsTextFontAndSize
barButton.setTitle(buttonTitles[buttonNumber], forState: UIControlState.Normal)
barButton.setTitleColor(buttonsTextColor, forState: UIControlState.Normal)
barButton.tag = buttonNumber
barButton.addTarget(self, action: "barButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
topBar.addSubview(barButton)
buttonsXPosition = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count) + buttonsXPosition
buttonNumber++
}
} else {
for item in buttonImages
{
var barButton: UIButton!
barButton = UIButton(frame: CGRectMake(buttonsXPosition, 0, containerView.frame.size.width/(CGFloat)(viewControllerIDs.count), topBarHeight))
barButton.backgroundColor = UIColor.clearColor()
barButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
barButton.setImage(item, forState: .Normal)
barButton.tag = buttonNumber
barButton.addTarget(self, action: "barButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
topBar.addSubview(barButton)
buttonsXPosition = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count) + buttonsXPosition
buttonNumber++
}
}
//Set up the animated UIView
animatedBar = UIView(frame: CGRectMake(0, topBarHeight - animatedBarHeight + 1, (containerView.frame.size.width/(CGFloat)(viewControllerIDs.count))*0.8, animatedBarHeight))
animatedBar.center.x = containerView.frame.size.width/(CGFloat)(viewControllerIDs.count * 2)
animatedBar.backgroundColor = animatedBarColor
containerView.addSubview(animatedBar)
//Add the bar shadow (set to true or false with the barShadow var)
if (barShadow) {
var shadowView = UIView(frame: CGRectMake(0, topBarHeight, containerView.frame.size.width, 4))
var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = shadowView.bounds
gradient.colors = [UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 0.28).CGColor, UIColor.clearColor().CGColor]
shadowView.layer.insertSublayer(gradient, atIndex: 0)
containerView.addSubview(shadowView)
}
let pageCount = viewControllerIDs.count
//Fill the array containing the VC instances with nil objects as placeholders
for _ in 0..<pageCount {
pageViews.append(nil)
}
//Defining the content size of the scrollview
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageCount),
height: pagesScrollViewSize.height)
//Load the pages to show initially
loadVisiblePages()
}
// MARK: - Initialization Functions -
public func initializeWithVCIDsArrayAndButtonTitlesArray (VCIDsArray: [String], buttonTitlesArray: [String])
{
//Important - Titles Array must Have The Same Number Of Items As The viewControllerIDs Array
if VCIDsArray.count == buttonTitlesArray.count {
viewControllerIDs = VCIDsArray
buttonTitles = buttonTitlesArray
buttonsWithImages = false
} else {
println("Initilization failed, the VC ID array count does not match the button titles array count.")
}
}
public func initializeWithVCIDsArrayAndButtonImagesArray (VCIDsArray: [String], buttonImagesArray: [UIImage])
{
//Important - Images Array must Have The Same Number Of Items As The viewControllerIDs Array
if VCIDsArray.count == buttonImagesArray.count {
viewControllerIDs = VCIDsArray
buttonImages = buttonImagesArray
buttonsWithImages = true
} else {
println("Initilization failed, the VC ID array count does not match the button images array count.")
}
}
public func loadPage(page: Int)
{
if page < 0 || page >= viewControllerIDs.count {
// If it's outside the range of what you have to display, then do nothing
return
}
//Use optional binding to check if the view has already been loaded
if let pageView = pageViews[page]
{
// Do nothing. The view is already loaded.
} else
{
println("Loading Page \(page)")
//The pageView instance is nil, create the page
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
//Create the variable that will hold the VC being load
var newPageView: UIViewController
//Look for the VC by its identifier in the storyboard and add it to the scrollview
newPageView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(viewControllerIDs[page]) as! UIViewController
newPageView.view.frame = frame
scrollView.addSubview(newPageView.view)
//Replace the nil in the pageViews array with the VC just created
pageViews[page] = newPageView
}
}
public func loadVisiblePages()
{
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
// Work out which pages you want to load
let firstPage = page - 1
let lastPage = page + 1
// Load pages in our range
for index in firstPage...lastPage {
loadPage(index)
}
}
public func barButtonAction(sender: UIButton?)
{
var index: Int = sender!.tag
let pagesScrollViewSize = scrollView.frame.size
[scrollView .setContentOffset(CGPointMake(pagesScrollViewSize.width * (CGFloat)(index), 0), animated: true)]
}
public func scrollViewDidScroll(scrollView: UIScrollView)
{
// Load the pages that are now on screen
loadVisiblePages()
//The calculations for the animated bar's movements
//The offset addition is based on the width of the animated bar (button width times 0.8)
var offsetAddition = (containerView.frame.size.width/(CGFloat)(viewControllerIDs.count))*0.1
animatedBar.frame = CGRectMake((offsetAddition + (scrollView.contentOffset.x/(CGFloat)(viewControllerIDs.count))), animatedBar.frame.origin.y, animatedBar.frame.size.width, animatedBar.frame.size.height);
}
}
|
mit
|
634ed2f0c85604eaab8b28e85a5a97b1
| 46.030888 | 212 | 0.661412 | 5.178571 | false | false | false | false |
february29/Learning
|
swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Map.swift
|
37
|
3360
|
//
// Map.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<R>(_ transform: @escaping (E) throws -> R)
-> Observable<R> {
return self.asObservable().composeMap(transform)
}
}
final fileprivate class MapSink<SourceType, O : ObserverType> : Sink<O>, ObserverType {
typealias Transform = (SourceType) throws -> ResultType
typealias ResultType = O.E
typealias Element = SourceType
private let _transform: Transform
init(transform: @escaping Transform, observer: O, cancel: Cancelable) {
_transform = transform
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let element):
do {
let mappedElement = try _transform(element)
forwardOn(.next(mappedElement))
}
catch let e {
forwardOn(.error(e))
dispose()
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
forwardOn(.completed)
dispose()
}
}
}
#if TRACE_RESOURCES
fileprivate var _numberOfMapOperators: AtomicInt = 0
extension Resources {
public static var numberOfMapOperators: Int32 {
return _numberOfMapOperators.valueSnapshot()
}
}
#endif
internal func _map<Element, R>(source: Observable<Element>, transform: @escaping (Element) throws -> R) -> Observable<R> {
return Map(source: source, transform: transform)
}
final fileprivate class Map<SourceType, ResultType>: Producer<ResultType> {
typealias Transform = (SourceType) throws -> ResultType
private let _source: Observable<SourceType>
private let _transform: Transform
init(source: Observable<SourceType>, transform: @escaping Transform) {
_source = source
_transform = transform
#if TRACE_RESOURCES
let _ = AtomicIncrement(&_numberOfMapOperators)
#endif
}
override func composeMap<R>(_ selector: @escaping (ResultType) throws -> R) -> Observable<R> {
let originalSelector = _transform
return Map<SourceType, R>(source: _source, transform: { (s: SourceType) throws -> R in
let r: ResultType = try originalSelector(s)
return try selector(r)
})
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType {
let sink = MapSink(transform: _transform, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
#if TRACE_RESOURCES
deinit {
let _ = AtomicDecrement(&_numberOfMapOperators)
}
#endif
}
|
mit
|
bb9c0601cca1baeaf0e8bd9f93a06034
| 30.101852 | 147 | 0.636499 | 4.626722 | false | false | false | false |
gouyz/GYZBaking
|
baking/Classes/Category/Controller/GYZGoodsDetailsVC.swift
|
1
|
6809
|
//
// GYZGoodsDetailsVC.swift
// baking
// 商品详情
// Created by gouyz on 2017/4/17.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
import MBProgressHUD
import SKPhotoBrowser
private let goodsDetailsCell = "goodsDetailsCell"
private let goodsDetailsConmentHeader = "goodsDetailsConmentHeader"
class GYZGoodsDetailsVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
var hud : MBProgressHUD?
/// 商品ID
var goodId: String = ""
var detailsModel: GYZGoodsDetailModel?
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
navBarBgAlpha = 0
let leftBtn = UIButton(type: .custom)
leftBtn.backgroundColor = kYellowFontColor
leftBtn.setImage(UIImage(named: "icon_black_white"), for: .normal)
leftBtn.frame = CGRect.init(x: 0, y: 0, width: kTitleHeight, height: kTitleHeight)
leftBtn.addTarget(self, action: #selector(clickedBackBtn), for: .touchUpInside)
leftBtn.cornerRadius = 22
navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBtn)
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsMake(-kTitleAndStateHeight, 0, 0, 0))
}
tableView.tableHeaderView = headerView
headerView.headerImg.addOnClickListener(target: self, action: #selector(clickImgDetail))
requestGoodsDetailData()
}
/// 返回
func clickedBackBtn() {
_ = navigationController?.popViewController(animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
navBarBgAlpha = 1
}
func clickImgDetail(){
let urlArr = GYZTool.getImgUrls(url: detailsModel?.goods_img)
if urlArr == nil {
return
}
let browser = SKPhotoBrowser(photos: createWebPhotos(urls: urlArr))
browser.initializePageIndex(0)
// browser.delegate = self
present(browser, animated: true, completion: nil)
}
func createWebPhotos(urls: [String]?) -> [SKPhotoProtocol] {
return (0..<(urls?.count)!).map { (i: Int) -> SKPhotoProtocol in
let photo = SKPhoto.photoWithImageURL((urls?[i])!)
SKPhotoBrowserOptions.displayToolbar = false
// photo.shouldCachePhotoURLImage = true
return photo
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 懒加载UITableView
lazy var tableView : UITableView = {
let table = UITableView(frame: CGRect.zero, style: .grouped)
table.dataSource = self
table.delegate = self
table.tableFooterView = UIView()
table.separatorColor = kGrayLineColor
// 设置大概高度
table.estimatedRowHeight = 110
// 设置行高为自动适配
table.rowHeight = UITableViewAutomaticDimension
table.register(GYZBusinessConmentCell.self, forCellReuseIdentifier: goodsDetailsCell)
table.register(GYZGoodsConmentHeader.self, forHeaderFooterViewReuseIdentifier: goodsDetailsConmentHeader)
return table
}()
lazy var headerView: GYZGoodsDetailsHeaderView = GYZGoodsDetailsHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 300))
/// 创建HUD
func createHUD(message: String){
if hud == nil {
hud = MBProgressHUD.showHUD(message: message,toView: view)
}else{
hud?.show(animated: true)
}
}
///获取商品详情数据
func requestGoodsDetailData(){
weak var weakSelf = self
createHUD(message: "加载中...")
GYZNetWork.requestNetwork("Goods/goodsInfo", parameters : ["good_id" : goodId], success: { (response) in
weakSelf?.hud?.hide(animated: true)
// GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
guard let info = data["info"].dictionaryObject else { return }
weakSelf?.detailsModel = GYZGoodsDetailModel.init(dict: info)
weakSelf?.headerView.dataModel = weakSelf?.detailsModel
weakSelf?.tableView.reloadData()
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return detailsModel?.comment == nil ? 0 : (detailsModel?.comment?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: goodsDetailsCell) as! GYZBusinessConmentCell
cell.dataModel = detailsModel?.comment?[indexPath.row]
cell.selectionStyle = .none
return cell
}
///MARK : UITableViewDelegate
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: goodsDetailsConmentHeader) as! GYZGoodsConmentHeader
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return kTitleHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.00001
}
//MARK:UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 禁止下拉
if scrollView.contentOffset.y <= 0 {
scrollView.contentOffset.y = 0
return
}
let contentOffsetY = scrollView.contentOffset.y
let showNavBarOffsetY = 200 - topLayoutGuide.length
//navigationBar alpha
if contentOffsetY > showNavBarOffsetY {
var navAlpha = (contentOffsetY - (showNavBarOffsetY)) / 40.0
if navAlpha > 1 {
navAlpha = 1
}
navBarBgAlpha = navAlpha
}else{
navBarBgAlpha = 0
}
}
}
|
mit
|
c776858682dc944f66ef04cd7d2633d4
| 33.777202 | 149 | 0.618445 | 5.143295 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/WordPressUITests/WPUITestCredentials.swift
|
1
|
982
|
import UITestsFoundation
// These are fake credentials used for the mocked UI tests
struct WPUITestCredentials {
static let testWPcomUserEmail: String = "[email protected]"
static let testWPcomUsername: String = "e2eflowtestingmobile"
static let testWPcomPassword: String = "mocked_password"
static let testWPcomSiteAddress: String = "tricountyrealestate.wordpress.com"
static let testWPcomSitePrimaryAddress: String = "tricountyrealestate.wordpress.com"
static let selfHostedUsername: String = "e2eflowtestingmobile"
static let selfHostedPassword: String = "mocked_password"
static let selfHostedSiteAddress: String = "\(WireMock.URL().absoluteString)"
static let signupEmail: String = "[email protected]"
static let signupUsername: String = "e2eflowsignuptestingmobile"
static let signupDisplayName: String = "Eeflowsignuptestingmobile"
static let signupPassword: String = "mocked_password"
}
|
gpl-2.0
|
675f7e4b27fc6223cb78f6fd25c8cf01
| 56.764706 | 89 | 0.786151 | 4.008163 | false | true | false | false |
samsao/DataProvider
|
Example/DataProvider/TableViewExampleController.swift
|
1
|
6418
|
//
// TableViewExampleController.swift
// DataProvider
//
// Created by Guilherme Silva Lisboa on 2016-03-16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import DataProvider
let kCellRID : String = "MycellRID"
class TableViewExampleController: UIViewController {
private var tableView : UITableView!
private var provider : TableViewProvider!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.frame,style: UITableViewStyle.grouped)
view.addSubview(tableView)
navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(TableViewExampleController.addPerson)), UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: #selector(TableViewExampleController.resetData))]
self.createProvider()
}
/**
Example of how to create section header/Footer view configuration to be used in the table view.
*/
private func createSectionViewConfig(text : String, bgColor : UIColor) -> ProviderSectionViewConfiguration {
//Create your view as needed.
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.width, height: 50))
view.backgroundColor = bgColor
let label = UILabel(frame: view.frame)
label.text = text
label.textColor = .white
view.addSubview(label)
//Initialize the configuration sending your view as parameter. You can also set a custom height for the configuration in case your view uses autolayout
let config = ProviderSectionViewConfiguration(view: view)
return config
}
func addPerson() {
let item = ProviderItem(data: Person(name: "PersonName", lastName: "\(NSDate())"), cellReuseIdentifier: kCellRID)
provider.addItemsToProvider(items: [item], inSection: 0, rowAnimation: UITableViewRowAnimation.automatic)
}
func resetData() {
let headerConfig = self.createSectionViewConfig(text: "Section 1 Header", bgColor: UIColor.black)
let footerConfig = self.createSectionViewConfig(text: "Section 1 Footer", bgColor: .lightGray)
let section1 = ProviderSection(items: ProviderItem.itemsCollectionWithData(dataArray: Person.peopleCollection(), cellReuseIdentifier: kCellRID), headerViewConfig: headerConfig, footerViewConfig: footerConfig)
let headerConfig2 = self.createSectionViewConfig(text: "Section 2 Header", bgColor: .black)
let footerConfig2 = self.createSectionViewConfig(text: "Section 2 Footer", bgColor: .lightGray)
let section2 = ProviderSection(items: ProviderItem.itemsCollectionWithData(dataArray: Person.peopleCollection(), cellReuseIdentifier: kCellRID), headerViewConfig: headerConfig2, footerViewConfig: footerConfig2)
provider.updateProviderData(newSections: [section1,section2])
}
private func createProvider() {
let data = Person.peopleCollection()
//Create the items and sections for the provider to use.
let providerItems : [ProviderItem] = ProviderItem.itemsCollectionWithData(dataArray: data, cellReuseIdentifier: kCellRID)
let section = ProviderSection(items: providerItems)
//Optional provider configuration
let providerConfig = ProviderConfiguration(reuseIdentifier: kCellRID, cellClass: UITableViewCell.self)
//Create the provider object
let provider = TableViewProvider(withTableView: tableView, sections: [section], delegate: self, cellConfiguration: [providerConfig])
self.provider = provider
}
}
extension TableViewExampleController : TableViewProviderDelegate {
/**
Called when a cell of the table view is deselected.
- parameter provider: table view provider object.
- parameter indexPath: index path of the selected item.
*/
public func provider(provider: TableViewProvider, didDeselectCellAtIndexPath indexPath: IndexPath) {
}
public func provider(provider : TableViewProvider, didSelectCellAtIndexPath indexPath: IndexPath) {
let item: ProviderItem = provider.providerItemAtIndexPath(indexPath: indexPath)!
let data = item.data as! Person
let alert = UIAlertController(title: "selected cell", message: "person name: \(data.name,data.lastName)", preferredStyle: UIAlertControllerStyle.alert)
//Delete row
alert.addAction(UIAlertAction(title: "Delete Cell", style: UIAlertActionStyle.destructive, handler: {[weak self] (action) -> Void in
//You can either remove with index paths
// provider.removeItems([indexPath])
//Or with a block, up to your need
provider.removeItems(removeBlock: { (item) -> Bool in
if let otherPerson = item.data as? Person {
return data.fullName() == otherPerson.fullName()
}
return false
}, inSection: indexPath.section)
// provider.removeItems({ (item) -> Bool in
// if let otherPerson = item.data as? Person {
// return data.fullName() == otherPerson.fullName()
// }
// return false
// }, inSection: indexPath.section)
self?.dismiss(animated: true, completion: nil)
}))
//Dismiss view
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: {[weak self] (action) -> Void in
self?.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
extension UITableViewCell : ProviderCellProtocol {
public func configureCell(cellData: Any) {
if let person = cellData as? Person {
textLabel?.text = person.name + " " + person.lastName
}
}
}
|
mit
|
956e792045ebda07d75633e69d560541
| 42.358108 | 321 | 0.664641 | 5.096902 | false | true | false | false |
yarshure/Surf
|
Surf-Mac/StatusView.swift
|
1
|
5724
|
//
// StatusView.swift
// Surf
//
// Created by networkextension on 21/11/2016.
// Copyright © 2016 yarshure. All rights reserved.
//
import Cocoa
import SFSocket
import XRuler
import NetworkExtension
import SwiftyJSON
class StatusView: NSView {
var report:SFVPNStatistics = SFVPNStatistics.shared
var reportTimer:Timer?
@IBOutlet weak var iconView: NSImageView!
@IBOutlet weak var upView: NSTextField!
@IBOutlet weak var downView: NSTextField!
@IBOutlet weak var upTrafficeView: NSTextField!
@IBOutlet weak var downTrafficView: NSTextField!
@IBOutlet weak var buttonView: NSButton!
override func awakeFromNib() {
let font = NSFont.init(name: "ionicons", size: 10)
config()
upView.font = font
downView.font = font
downView.stringValue = "\u{f35d}"
upView.stringValue = "\u{f366}"
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
func config(){
if reportTimer == nil {
reportTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(StatusView.requestReportXPC(_:)), userInfo: nil, repeats: true)
return
}else {
if let t = reportTimer, !(t.isValid) {
reportTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(StatusView.requestReportXPC(_:)), userInfo: nil, repeats: true)
}
}
}
@objc func requestReport(_ timer:Timer){
let now = getInterfaceTraffic()
if now.TunSent != 0 && now.TunReceived != 0 {
//report.lastTraffice.tx = now.TunSent -
if now.TunSent > report.totalTraffice.tx {
report.lastTraffice.tx = now.TunSent - report.totalTraffice.tx
report.lastTraffice.rx = now.TunReceived - report.totalTraffice.rx
report.updateMax()
}
report.totalTraffice.tx = now.TunSent
report.totalTraffice.rx = now.TunReceived
let t = report.lastTraffice
upTrafficeView.stringValue = self.toString(x: t.tx,label: "",speed: true)
downTrafficView.stringValue = self.toString(x: t.rx,label: "",speed: true)
}else {
upTrafficeView.stringValue = "0 B/s"
downTrafficView.stringValue = "0 B/s"
}
//tableView.reloadData()
}
public func toString(x:UInt,label:String,speed:Bool) ->String {
var s = "/s"
if !speed {
s = ""
}
if x < 1024{
return label + " \(x) B" + s
}else if x >= 1024 && x < 1024*1024 {
return label + String(format: "%d KB", Int(Float(x)/1024.0)) + s
}else if x >= 1024*1024 && x < 1024*1024*1024 {
//return label + "\(x/1024/1024) MB" + s
return label + String(format: "%d MB", Int(Float(x)/1024/1024)) + s
}else {
//return label + "\(x/1024/1024/1024) GB" + s
return label + String(format: "%d GB", Int(Float(x)/1024/1024/1024)) + s
}
}
@objc func requestReportXPC(_ timer:Timer) {
if let m = SFVPNManager.shared.manager , m.connection.status == .connected {
//print("\(m.protocolConfiguration)")
let date = NSDate()
let me = SFVPNXPSCommand.STATUS.rawValue + "|\(date)"
if let session = m.connection as? NETunnelProviderSession,
let message = me.data(using: .utf8)
{
do {
try session.sendProviderMessage(message) { [weak self] response in
// print("------\(Date()) %0.2f",Date().timeIntervalSince(d0))
if response != nil {
self!.processData(data: response!)
//print("------\(Date()) %0.2f",Date().timeIntervalSince(d0))
} else {
//self!.alertMessageAction("Got a nil response from the provider",complete: nil)
}
}
} catch {
//alertMessageAction("Failed to Get result ",complete: nil)
}
}else {
//alertMessageAction("Connection not Stated",complete: nil)
}
}else {
//alertMessageAction("message dont init",complete: nil)
//tableView.reloadData()
}
}
func processData(data:Data) {
//results.removeAll()
//print("111")
//let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
let obj = try! JSON.init(data: data)
if obj.error == nil {
//alertMessageAction("message dont init",complete: nil)
report.map(j: obj)
//bug here
if let m = SFVPNManager.shared.manager, m.connection.status == .connected{
//chartsView.updateFlow(report.netflow)
//chartsView.isHidden = false
if let last = report.netflow.totalFlows.last {
upTrafficeView.stringValue = self.toString(x: last.tx,label: "",speed: true)
downTrafficView.stringValue = self.toString(x: last.rx,label: "",speed: true)
}
}else {
}
//print(report.netflow.currentFlows)
}
}
}
|
bsd-3-clause
|
6c48046167944210559596a8d8e5c577
| 33.896341 | 167 | 0.522104 | 4.319245 | false | false | false | false |
tjw/swift
|
stdlib/public/core/ArrayType.swift
|
4
|
2732
|
//===--- ArrayType.swift - Protocol for Array-like types ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal protocol ArrayProtocol
: RangeReplaceableCollection,
ExpressibleByArrayLiteral
{
//===--- public interface -----------------------------------------------===//
/// The number of elements the Array stores.
var count: Int { get }
/// The number of elements the Array can store without reallocation.
var capacity: Int { get }
/// `true` if and only if the Array is empty.
var isEmpty: Bool { get }
/// An object that guarantees the lifetime of this array's elements.
var _owner: AnyObject? { get }
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { get }
subscript(index: Int) -> Element { get set }
//===--- basic mutations ------------------------------------------------===//
/// Reserve enough space to store minimumCapacity elements.
///
/// - Postcondition: `capacity >= minimumCapacity` and the array has
/// mutable contiguous storage.
///
/// - Complexity: O(`self.count`).
mutating func reserveCapacity(_ minimumCapacity: Int)
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
///
/// - Precondition: `startIndex <= i`, `i <= endIndex`.
mutating func insert(_ newElement: Element, at i: Int)
/// Remove and return the element at the given index.
///
/// - returns: The removed element.
///
/// - Complexity: Worst case O(*n*).
///
/// - Precondition: `count > index`.
@discardableResult
mutating func remove(at index: Int) -> Element
//===--- implementation detail -----------------------------------------===//
associatedtype _Buffer : _ArrayBufferProtocol
init(_ buffer: _Buffer)
// For testing.
var _buffer: _Buffer { get }
}
extension ArrayProtocol {
// Since RangeReplaceableCollection now has a version of filter that is less
// efficient, we should make the default implementation coming from Sequence
// preferred.
@inlinable
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}
}
|
apache-2.0
|
db842de90a6ac79259dbf593cec573d6
| 31.141176 | 80 | 0.614202 | 4.86121 | false | false | false | false |
wbaumann/SmartReceiptsiOS
|
SmartReceipts/Modules/Edit Receipt/EditReceiptInteractor.swift
|
2
|
6353
|
//
// EditReceiptInteractor.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 18/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import Viperit
import RxSwift
import Toaster
fileprivate let MIN_SCANS_TOOLTIP = 5
class EditReceiptInteractor: Interactor {
private let tooltipBag = DisposeBag()
private var authService: AuthServiceInterface!
private var scansPurchaseTracker: ScansPurchaseTracker!
private var tooltipService: TooltipService!
var receiptFilePath: URL?
let bag = DisposeBag()
required init(
authService: AuthServiceInterface,
scansPurchaseTracker: ScansPurchaseTracker,
tooltipService: TooltipService
) {
self.authService = authService
self.scansPurchaseTracker = scansPurchaseTracker
self.tooltipService = tooltipService
}
convenience required init() {
self.init(
authService: AuthService.shared,
scansPurchaseTracker: ScansPurchaseTracker.shared,
tooltipService: TooltipService.shared
)
}
func configureSubscribers() {
presenter.addReceiptSubject
.subscribe(onNext: { [unowned self] receipt in
Logger.debug("Added Receipt: \(receipt.name)")
AnalyticsManager.sharedManager.record(event: Event.receiptsPersistNewReceipt())
self.saveImage(to: receipt)
self.save(receipt: receipt)
}).disposed(by: bag)
presenter.updateReceiptSubject
.subscribe(onNext: { [unowned self] receipt in
Logger.debug("Updated Receipt: \(receipt.name)")
AnalyticsManager.sharedManager.record(event: Event.receiptsPersistUpdateReceipt())
self.replaceImageIfNeeded(receipt: receipt)
self.save(receipt: receipt)
}).disposed(by: bag)
presenter.paymentMehtodInsert
.subscribe(onNext: { [weak self] in
self?.insertPaymentMethods()
}).disposed(by: bag)
}
func tooltipText() -> String? {
if authService.isLoggedIn && scansPurchaseTracker.remainingScans < MIN_SCANS_TOOLTIP {
let format = LocalizedString("ocr.informational.tooltip.limited.scans.text")
return String.localizedStringWithFormat(format, scansPurchaseTracker.remainingScans)
} else if !authService.isLoggedIn && !tooltipService.configureOCRDismissed() {
presenter.tooltipClose
.subscribe(onNext: { [unowned self] in
self.tooltipService.markConfigureOCRDismissed()
}).disposed(by: tooltipBag)
return LocalizedString("ocr_informational_tooltip_configure_text")
}
return nil
}
private func insertPaymentMethods() {
let csvColumns = Database.sharedInstance().allCSVColumns() as! [ReceiptColumn]
let pdfColumns = Database.sharedInstance().allPDFColumns() as! [ReceiptColumn]
let columnName = LocalizedString("column_item_payment_method")
let columnType = 27
if !csvColumns.contains(where: { $0.isKind(of: ReceiptColumnPaymentMethod.self) }) {
let index = Database.sharedInstance().nextCSVColumnObjectID()
let paymentMethodColumn = ReceiptColumnPaymentMethod(index: index,type: columnType, name: columnName)
Database.sharedInstance().addCSVColumn(paymentMethodColumn)
}
if !pdfColumns.contains(where: { $0.isKind(of: ReceiptColumnPaymentMethod.self) }) {
let index = Database.sharedInstance().nextPDFColumnObjectID()
let paymentMethodColumn = ReceiptColumnPaymentMethod(index: index,type: columnType, name: columnName)
Database.sharedInstance().addPDFColumn(paymentMethodColumn)
}
}
private func save(receipt: WBReceipt) {
receipt.lastLocalModificationTime = Date()
if !Database.sharedInstance().save(receipt) {
presenter.present(errorDescription: LocalizedString("database_error"))
let action = receipt.objectId == 0 ? "insert" : "update"
Logger.error("Can't \(action) receipt: \(receipt.description)")
} else {
validateDate(in: receipt)
presenter.close()
}
}
private func replaceImageIfNeeded(receipt: WBReceipt) {
if receipt.hasPDF() || receipt.hasImage() {
let currentPath = receipt.imageFilePath(for: receipt.trip)
let tripFolder = currentPath.asNSString.deletingLastPathComponent
let newFileName = String(format: "%tu_%@.%@", receipt.objectId, receipt.omittedName, currentPath.asNSString.pathExtension)
let newPath = "\(tripFolder)/\(newFileName)"
receipt.setFilename(newFileName)
do {
try FileManager.default.moveItem(atPath: currentPath, toPath: newPath)
} catch let error as NSError {
Logger.error(error.localizedDescription)
}
}
}
private func saveImage(to receipt: WBReceipt) {
if let url = receiptFilePath, let fileData = try? Data(contentsOf: url) {
var imgFileName = ""
let nextId = Database.sharedInstance().nextReceiptID()
imgFileName = String(format: "%tu_%@.%@", nextId, receipt.omittedName, url.pathExtension)
let path = receipt.trip.file(inDirectoryPath: imgFileName)
if !FileManager.forceWrite(data: fileData, to: path!) {
imgFileName = ""
} else {
receipt.setFilename(imgFileName)
}
}
}
private func validateDate(in receipt: WBReceipt) {
Observable<Void>.just(())
.filter({ receipt.date > receipt.trip.endDate || receipt.date < receipt.trip.startDate })
.subscribe(onNext: {
let message = LocalizedString("DIALOG_RECEIPTMENU_TOAST_BAD_DATE")
Toast.show(message)
}).disposed(by: bag)
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension EditReceiptInteractor {
var presenter: EditReceiptPresenter {
return _presenter as! EditReceiptPresenter
}
}
|
agpl-3.0
|
a9bb56d8805fa8a365e827d083e20c8d
| 39.458599 | 134 | 0.633659 | 4.878648 | false | false | false | false |
AnneBlair/YYGRegular
|
POP/Negotiate/Negotiate/RequestCenter.swift
|
1
|
1227
|
//
// RequestCenter.swift
// Negotiate
//
// Created by 区块国际-yin on 17/2/5.
// Copyright © 2017年 区块国际-yin. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
/// 商品详情请求
struct goodsParticulars: Request {
var goodsId: String
var path: String {
return Api.goodsParticularsURL
}
var method: HTTPMethod = .post
var parameter: [String : AnyObject] {
return ["goods_id": goodsId as AnyObject]
}
typealias Analysis = ParticularsAnalysis
}
extension ParticularsAnalysis: Decodable {
static func parse(anyData: Any) -> ParticularsAnalysis? {
return ParticularsAnalysis(anyData: anyData)
}
}
struct ParticularsAnalysis {
var message: Bool
var tempData: Any
init?(anyData: Any) {
let obj = JSON(anyData)
guard let name = obj["errno"].int else {
self.message = false
return nil
}
if name == 2000 {
self.message = true
self.tempData = anyData
} else {
self.message = false
self.tempData = anyData
}
}
}
|
mit
|
80e7c99ea29b64decd5f9f97de844e49
| 18.540984 | 61 | 0.572148 | 4.197183 | false | false | false | false |
Ryce/stege-ios
|
Stege/ViewController.swift
|
1
|
1591
|
//
// ViewController.swift
// Stege
//
// Created by Hamon Riazy on 25/07/15.
// Copyright (c) 2015 ryce. All rights reserved.
//
import UIKit
import AVFoundation
import EasyAnimation
class ViewController: UIViewController {
@IBOutlet var stegeImage: UIImageView!
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
self.stegeImage.clipsToBounds = true
self.stegeImage.layer.cornerRadius = 50.0
// 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.
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
// play random audio
let number = Int(rand()) % 5
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(String(number), ofType: "m4a")!)
self.audioPlayer = AVAudioPlayer(contentsOfURL: url, error: nil)
self.audioPlayer.play()
// wiggle image
UIView.animateAndChainWithDuration(0.25, delay: 0.0, options: .CurveEaseOut, animations: {
self.stegeImage.transform = CGAffineTransformMakeScale(0.8, 0.8)
}, completion: nil).animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0.0, options: nil, animations: {
self.stegeImage.transform = CGAffineTransformMakeScale(1, 1)
}, completion: nil)
}
}
|
gpl-2.0
|
4c374050b70712399c7500e39274c9f5
| 31.469388 | 154 | 0.65682 | 4.519886 | false | false | false | false |
danielpi/Swift-Playgrounds
|
Swift-Playgrounds/The Swift Programming Language/LanguageGuide/08-Enumerations.playground/Contents.swift
|
1
|
3406
|
// Enumerations
// An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.
enum CompassPoint {
case north
case south
case east
case west
}
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
var directionToHead = CompassPoint.west
directionToHead = .east
// Matching Enumeration Values with a Switch Statement
directionToHead = .south
switch directionToHead {
case .north:
print("Lots of planets have a north")
case .south:
print("Watch out for penguins")
case .east:
print("Where the sun rises")
case .west:
print("Where the skies are blue")
}
let somePlanet = Planet.earth
switch somePlanet {
case .earth:
print("Mostly Harmless")
default:
print("Not a safe place for humans")
}
// Associated Values
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check)")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}
productBarcode = Barcode.upc(8, 85909, 51226, 3)
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
}
// Raw Values
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
// Implicitly Assigned Raw Values
enum PlanetRaw: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
let earthsOrder = PlanetRaw.earth.rawValue
// earthsOrder is 3
enum CompassPointRaw: String {
case north, south, east, west
}
let sunsetDirection = CompassPointRaw.west.rawValue
// sunsetDirection is "West"
// Initializing from a Raw Value
let possiblePlanet = PlanetRaw(rawValue: 7)
let positionToFind = 11
if let somePlanet = PlanetRaw(rawValue: positionToFind) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
// Recursive Enumerations
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
indirect enum ArithmeticExpression2 {
case number(Int)
case addition(ArithmeticExpression2, ArithmeticExpression2)
case multiplication(ArithmeticExpression2, ArithmeticExpression2)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case .number(let value):
return value
case let .addition(lhs, rhs):
return evaluate(lhs) + evaluate(rhs)
case let .multiplication(lhs, rhs):
return evaluate(lhs) * evaluate(rhs)
}
}
print(evaluate(product))
|
mit
|
5523ed12c82ff96b6f6fb9554d88a01c
| 24.044118 | 149 | 0.71697 | 4.128485 | false | false | false | false |
shahmishal/swift
|
test/SILGen/switch_var.swift
|
5
|
27507
|
// RUN: %target-swift-emit-silgen -module-name switch_var %s | %FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_1yyF
func test_var_1() {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK-NOT: br bb
case var x:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
a(x: x)
}
// CHECK: function_ref @$s10switch_var1byyF
b()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_2yyF
func test_var_2() {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// -- TODO: Clean up these empty waypoint bbs.
case var x where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case var y where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b(x: y)
case var z:
// CHECK: [[NO_CASE2]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CONT]]
c(x: z)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s10switch_var1dyyF
d()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_3yyF
func test_var_3() {
// CHECK: function_ref @$s10switch_var3fooSiyF
// CHECK: function_ref @$s10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2aa1xySi_Sit_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
aa(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
a(x: y)
b(x: z)
// CHECK: [[NO_CASE2]]:
// CHECK: [[WADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$s10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case var w where ansed(x: w.0):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2bb1xySi_Sit_tF
// CHECK: br [[CONT]]
bb(x: w)
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[WADDR]]
case var v:
// CHECK: [[VADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%.*]] = project_box [[VADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[V]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2cc1xySi_Sit_tF
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[CONT]]
cc(x: v)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s10switch_var1dyyF
d()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_41pyAA1P_p_tF : $@convention(thin) (@in_guaranteed P) -> () {
func test_var_4(p p: P) {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch (p, foo()) {
// CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int)
// CHECK: store
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1
// CHECK: [[PAIR_1:%.*]] = load [trivial] [[T0]] : $*Int
// CHECK: [[TMP:%.*]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*X
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[X]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case (is X, var x) where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[TMP:%.*]] = alloc_stack $Y
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*Y
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (is Y, var y) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var (P, Int) }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$s10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
case var z where ansed(x: z.1):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$s10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK-NEXT: destroy_addr [[PAIR]]
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
c(x: z.1)
// CHECK: [[DFLT_NO_CASE3]]:
// CHECK-NEXT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_addr
case (_, var w):
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[WADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1d1xySi_tF
// CHECK: destroy_value [[WADDR]]
// CHECK-NEXT: destroy_addr [[PAIR_0]] : $*P
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[CONT]]
d(x: w)
}
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_5yyF : $@convention(thin) () -> () {
func test_var_5() {
// CHECK: function_ref @$s10switch_var3fooSiyF
// CHECK: function_ref @$s10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b()
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case (_, _) where runced():
// CHECK: [[CASE3]]:
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: br [[CASE4:bb[0-9]+]]
case _:
// CHECK: [[CASE4]]:
d()
}
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B7_returnyyF : $@convention(thin) () -> () {
func test_var_return() {
switch (foo(), bar()) {
case var x where runced():
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: function_ref @$s10switch_var1ayyF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[EPILOG:bb[0-9]+]]
a()
return
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
case (var y, var z) where funged():
// CHECK: function_ref @$s10switch_var1byyF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[EPILOG]]
b()
return
case var w where ansed():
// CHECK: [[WADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%[0-9]+]] = project_box [[WADDR]]
// CHECK: function_ref @$s10switch_var1cyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[EPILOG]]
c()
return
case var v:
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%[0-9]+]] = project_box [[VADDR]]
// CHECK: function_ref @$s10switch_var1dyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[EPILOG]]
d()
return
}
}
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var8test_letyyF : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @$s10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: function_ref @$s10switch_var6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[BORROWED_VAL_COPY]])
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[BORROWED_VAL_2:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY_2:%.*]] = copy_value [[BORROWED_VAL_2]]
// CHECK: function_ref @$s10switch_var6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
// CHECK: [[B:%.*]] = function_ref @$s10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY_2]])
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: [[BORROWED_VAL_3:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY_3:%.*]] = copy_value [[BORROWED_VAL_3]]
// CHECK: function_ref @$s10switch_var4barsSSyF
// CHECK: [[BORROWED_VAL_COPY_3:%.*]] = begin_borrow [[VAL_COPY_3]]
// CHECK: store_borrow [[BORROWED_VAL_COPY_3]] to [[IN_ARG:%.*]] :
// CHECK: apply {{%.*}}<String>({{.*}}, [[IN_ARG]])
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: [[YES_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: [[FUNC:%.*]] = function_ref @$s10switch_var1cyyF
// CHECK-NEXT: apply [[FUNC]](
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
c()
case _:
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: function_ref @$s10switch_var1dyyF
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$s10switch_var8test_letyyF'
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var015test_mixed_let_B0yyF : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: bb0:
// CHECK: [[FOOS:%.*]] = function_ref @$s10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
switch foos() {
// First pattern.
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }, var, name "x"
// CHECK: [[PBOX:%.*]] = project_box [[BOX]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: store [[VAL_COPY]] to [init] [[PBOX]]
// CHECK: cond_br {{.*}}, [[CASE1:bb[0-9]+]], [[NOCASE1:bb[0-9]+]]
case var x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[X]])
// CHECK: destroy_value [[BOX]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NOCASE1]]:
// CHECK: destroy_value [[BOX]]
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: cond_br {{.*}}, [[CASE2:bb[0-9]+]], [[NOCASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[B:%.*]] = function_ref @$s10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NOCASE2]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: store_borrow [[BORROWED_VAL_COPY]] to [[TMP_VAL_COPY_ADDR:%.*]] :
// CHECK: apply {{.*}}<String>({{.*}}, [[TMP_VAL_COPY_ADDR]])
// CHECK: cond_br {{.*}}, [[CASE3:bb[0-9]+]], [[NOCASE3:bb[0-9]+]]
case bars():
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[FUNC:%.*]] = function_ref @$s10switch_var1cyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
c()
// CHECK: [[NOCASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[D_FUNC:%.*]] = function_ref @$s10switch_var1dyyF : $@convention(thin) () -> ()
// CHECK: apply [[D_FUNC]]()
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
case _:
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$s10switch_var015test_mixed_let_B0yyF'
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns1yyF : $@convention(thin) () -> () {
func test_multiple_patterns1() {
// CHECK: function_ref @$s10switch_var6foobarSi_SityF
switch foobar() {
// CHECK-NOT: br bb
case (0, let x), (let x, 0):
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: debug_value [[FIRST_X:%.*]] :
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: debug_value [[SECOND_X:%.*]] :
// CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$s10switch_var1byyF
b()
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns2yyF : $@convention(thin) () -> () {
func test_multiple_patterns2() {
let t1 = 2
let t2 = 4
// CHECK: debug_value [[T1:%.+]] :
// CHECK: debug_value [[T2:%.+]] :
switch (0,0) {
// CHECK-NOT: br bb
case (_, let x) where x > t1, (let x, _) where x > t2:
// CHECK: ([[FIRST:%[0-9]+]], [[SECOND:%[0-9]+]]) = destructure_tuple {{%.+}} : $(Int, Int)
// CHECK: apply {{%.+}}([[SECOND]], [[T1]], {{%.+}})
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[SECOND]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: apply {{%.*}}([[FIRST]], [[T2]], {{%.+}})
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: br [[CASE_BODY]]([[FIRST]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$s10switch_var1byyF
b()
}
}
enum Foo {
case A(Int, Double)
case B(Double, Int)
case C(Int, Int, Double)
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns3yyF : $@convention(thin) () -> () {
func test_multiple_patterns3() {
let f = Foo.C(0, 1, 2.0)
switch f {
// CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
case .A(let x, let n), .B(let n, let x), .C(_, let x, let n):
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double)
// CHECK: [[C]]([[C_TUP:%.*]] : $(Int, Int, Double)):
// CHECK: ([[C__:%.*]], [[C_X:%.*]], [[C_N:%.*]]) = destructure_tuple [[C_TUP]]
// CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
// CHECK: [[FUNC_A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
enum Bar {
case Y(Foo, Int)
case Z(Int, Foo)
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns4yyF : $@convention(thin) () -> () {
func test_multiple_patterns4() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _):
// CHECK: [[Y]]([[Y_TUP:%.*]] : $(Foo, Int)):
// CHECK: ([[Y_F:%.*]], [[Y_X:%.*]]) = destructure_tuple [[Y_TUP]]
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]([[Z_TUP:%.*]] : $(Int, Foo)):
// CHECK: ([[Z_X:%.*]], [[Z_F:%.*]]) = destructure_tuple [[Z_TUP]]
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: [[FUNC_A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
func aaa(x x: inout Int) {}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns5yyF : $@convention(thin) () -> () {
func test_multiple_patterns5() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _):
// CHECK: [[Y]]([[Y_TUP:%.*]] : $(Foo, Int)):
// CHECK: ([[Y_F:%.*]], [[Y_X:%.*]]) = destructure_tuple [[Y_TUP]]
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]([[Z_TUP:%.*]] : $(Int, Foo)):
// CHECK: ([[Z_X:%.*]], [[Z_F:%.*]]) = destructure_tuple [[Z_TUP]]
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
// CHECK: [[FUNC_AAA:%.*]] = function_ref @$s10switch_var3aaa1xySiz_tF
// CHECK: apply [[FUNC_AAA]]([[WRITE]])
aaa(x: &x)
}
}
// rdar://problem/29252758 -- local decls must not be reemitted.
func test_against_reemission(x: Bar) {
switch x {
case .Y(let a, _), .Z(_, let a):
let b = a
}
}
class C {}
class D: C {}
func f(_: D) -> Bool { return true }
// CHECK-LABEL: sil hidden [ossa] @{{.*}}test_multiple_patterns_value_semantics
func test_multiple_patterns_value_semantics(_ y: C) {
switch y {
// CHECK: checked_cast_br {{%.*}} : $C to $D, [[AS_D:bb[0-9]+]], [[NOT_AS_D:bb[0-9]+]]
// CHECK: [[AS_D]]({{.*}}):
// CHECK: cond_br {{%.*}}, [[F_TRUE:bb[0-9]+]], [[F_FALSE:bb[0-9]+]]
// CHECK: [[F_TRUE]]:
// CHECK: [[BINDING:%.*]] = copy_value [[ORIG:%.*]] :
// CHECK: destroy_value [[ORIG]]
// CHECK: br {{bb[0-9]+}}([[BINDING]]
case let x as D where f(x), let x as D: break
default: break
}
}
|
apache-2.0
|
712d78a52a0379067057a7e3dec9791a
| 37.364017 | 161 | 0.511288 | 2.858464 | false | false | false | false |
james-gray/selektor
|
Selektor/Models/SelektorObject.swift
|
1
|
1860
|
//
// SelektorObject.swift
// Selektor
//
// Created by James Gray on 2016-05-28.
// Copyright © 2016 James Gray. All rights reserved.
import Foundation
import CoreData
import Cocoa
// Subclass of NSManagedObject that entity classes should subclass for the purpose
// of exposing their entity names to the DataController via the `getEntityName` method.
// NOTE: This could also be accomplished with an NSManagedObject extension, however
// I've opted to simply subclass NSManagedObject in case I need other common
// functionality that only makes sense within the context of this app.
@objc(SelektorObject)
class SelektorObject: NSManagedObject {
// MARK: Properties
@NSManaged var name: String?
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
/**
Return a threadlocal DataController if one has been configured, otherwise use the AppDelegate's
DataController.
*/
lazy var dataController: DataController = {
let currentThread = NSThread.currentThread()
let threadDictionary = currentThread.threadDictionary
let dataController = threadDictionary.valueForKey("dc") as? DataController ?? (NSApplication.sharedApplication().delegate
as? AppDelegate)?.dataController
return dataController!
}()
/**
Returns the Core Data entity name for this managed object.
XXX: Hack due to Swift's lack of support for class vars as of yet.
A `class func` is effectively equivalent to a `static func`, but can be
overridden by subclasses (unlike static funcs.)
Similarly, `static var`s cannot be overridden (and `class vars` don't exist)
so we must use a getter method instead.
- returns: The string entity name.
*/
class func getEntityName() -> String {
print("Subclasses should override abstract method `getEntityName`!")
abort()
}
}
|
gpl-3.0
|
b0fa98ba77682111ddcba691715324c8
| 34.769231 | 125 | 0.736417 | 4.803618 | false | false | false | false |
kumabook/FeedlyKit
|
Spec/StreamsAPISpec.swift
|
1
|
4136
|
//
// StreamsAPISpec.swift
// FeedlyKit
//
// Created by Hiroki Kumamoto on 3/10/16.
// Copyright © 2016 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import FeedlyKit
import Quick
import Nimble
class StreamsAPISpec: QuickSpec {
let perPage = 5
let feedId = "feed/http://kumabook.github.io/feed.xml"
let client: CloudAPIClient = CloudAPIClient(target: SpecHelper.target)
var entryIds: [String] = []
var entries: [Entry] = []
override func spec() {
describe("fetchIds") {
var statusCode = 0
beforeEach {
let params = PaginationParams()
params.count = self.perPage
let _ = self.client.fetchEntryIds(self.feedId, paginationParams: params) {
guard let code = $0.response?.statusCode,
let val = $0.result.value else { return }
statusCode = code
self.entryIds = val.ids
}
}
it ("fetch entries ids") {
expect(statusCode).toFinally(equal(200))
expect(self.entryIds.count).toFinally(equal(self.perPage))
}
}
describe("fetchContents") {
var statusCode = 0
beforeEach {
let params = PaginationParams()
params.count = self.perPage
let _ = self.client.fetchContents(self.feedId, paginationParams: params) {
guard let code = $0.response?.statusCode,
let val = $0.result.value else { return }
statusCode = code
self.entries = val.items
}
}
it ("fetches entries contents") {
expect(statusCode).toFinally(equal(200))
expect(self.entries.count).toFinally(equal(self.perPage))
}
}
describe("Pagination") {
let params = PaginationParams()
params.count = self.perPage
params.continuation = ""
var statusCode = 0
func clear() {
self.entryIds = []
params.continuation = ""
}
func fetchIds(_ params: PaginationParams, times: Int) {
if times == 0 { return }
sleep(1);
let _ = self.client.fetchEntryIds(self.feedId, paginationParams: params) {
guard let code = $0.response?.statusCode,
let val = $0.result.value else { return }
statusCode = code
self.entryIds.append(contentsOf: val.ids)
params.continuation = val.continuation
if times > 0 && params.continuation != nil {
fetchIds(params, times: times - 1)
}
}
}
context("first page") {
statusCode = 0
beforeEach {
clear()
fetchIds(params, times: 1)
}
it ("fetches first page") {
expect(statusCode).toFinally(equal(200))
expect(self.entryIds.count).toFinally(equal(self.perPage))
}
}
context("second page") {
statusCode = 0
beforeEach {
clear()
fetchIds(params, times: 2)
}
it ("fetches second page") {
expect(statusCode).toFinally(equal(200))
expect(self.entryIds.count).toFinally(equal(self.perPage * 2))
}
}
/* context("last page") {
statusCode = 0
beforeEach {
clear()
fetchIds(params, times: Int.max)
}
it ("eventually fetches last page") {
expect(params.continuation).toEventually(beNil())
}
}*/
}
}
}
|
mit
|
49bcb3d43205f00547e31c9ff701ff58
| 34.042373 | 90 | 0.466989 | 5.111248 | false | false | false | false |
zjjzmw1/speedxSwift
|
speedxSwift/Pods/RealmSwift/RealmSwift/Object.swift
|
3
|
16659
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
In Realm you define your model classes by subclassing `Object` and adding properties to be persisted.
You then instantiate and use your custom subclasses instead of using the Object class directly.
```swift
class Dog: Object {
dynamic var name: String = ""
dynamic var adopted: Bool = false
let siblings = List<Dog>()
}
```
### Supported property types
- `String`, `NSString`
- `Int`
- `Int8`, `Int16`, `Int32`, `Int64`
- `Float`
- `Double`
- `Bool`
- `NSDate`
- `NSData`
- `RealmOptional<T>` for optional numeric properties
- `Object` subclasses for to-one relationships
- `List<T: Object>` for to-many relationships
`String`, `NSString`, `NSDate`, `NSData` and `Object` subclass properties can be
optional. `Int`, `Int8`, Int16`, Int32`, `Int64`, `Float`, `Double`, `Bool`
and `List` properties cannot. To store an optional number, instead use
`RealmOptional<Int>`, `RealmOptional<Float>`, `RealmOptional<Double>`, or
`RealmOptional<Bool>` instead, which wraps an optional value of the generic type.
All property types except for `List` and `RealmOptional` *must* be declared as
`dynamic var`. `List` and `RealmOptional` properties must be declared as
non-dynamic `let` properties.
### Querying
You can gets `Results` of an Object subclass via the `objects(_:)` instance
method on `Realm`.
### Relationships
See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
*/
@objc(RealmSwiftObject)
public class Object: RLMObjectBase {
// MARK: Initializers
/**
Initialize a standalone (unpersisted) `Object`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
- see: Realm().add(_:)
*/
public override required init() {
super.init()
}
/**
Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or
`Dictionary<String, AnyObject>`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON object such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
*/
public init(value: AnyObject) {
self.dynamicType.sharedSchema() // ensure this class' objectSchema is loaded in the partialSharedSchema
super.init(value: value, schema: RLMSchema.partialSharedSchema())
}
// MARK: Properties
/// The `Realm` this object belongs to, or `nil` if the object
/// does not belong to a realm (the object is standalone).
public var realm: Realm? {
if let rlmReam = RLMObjectBaseRealm(self) {
return Realm(rlmReam)
}
return nil
}
/// The `ObjectSchema` which lists the persisted properties for this object.
public var objectSchema: ObjectSchema {
return ObjectSchema(RLMObjectBaseObjectSchema(self))
}
/// Indicates if an object can no longer be accessed.
///
/// An object can no longer be accessed if the object has been deleted from the containing
/// `realm` or if `invalidate` is called on the containing `realm`.
public override var invalidated: Bool { return super.invalidated }
/// Returns a human-readable description of this object.
public override var description: String { return super.description }
#if os(OSX)
/// Helper to return the class name for an Object subclass.
public final override var className: String { return "" }
#else
/// Helper to return the class name for an Object subclass.
public final var className: String { return "" }
#endif
/**
WARNING: This is an internal helper method not intended for public use.
:nodoc:
*/
public override class func objectUtilClass(isSwift: Bool) -> AnyClass {
return ObjectUtil.self
}
// MARK: Object Customization
/**
Override to designate a property as the primary key for an `Object` subclass. Only properties of
type String and Int can be designated as the primary key. Primary key
properties enforce uniqueness for each value whenever the property is set which incurs some overhead.
Indexes are created automatically for primary key properties.
- returns: Name of the property designated as the primary key, or `nil` if the model has no primary key.
*/
public class func primaryKey() -> String? { return nil }
/**
Override to return an array of property names to ignore. These properties will not be persisted
and are treated as transient.
- returns: `Array` of property names to ignore.
*/
public class func ignoredProperties() -> [String] { return [] }
/**
Return an array of property names for properties which should be indexed.
Only supported for string, integer, boolean and NSDate properties.
- returns: `Array` of property names to index.
*/
public class func indexedProperties() -> [String] { return [] }
// MARK: Inverse Relationships
/**
Get an `Array` of objects of type `T` which have this object as the given property value. This can
be used to get the inverse relationship value for `Object` and `List` properties.
- parameter type: The type of object on which the relationship to query is defined.
- parameter propertyName: The name of the property which defines the relationship.
- returns: An `Array` of objects of type `T` which have this object as their value for the `propertyName` property.
*/
@available(*, deprecated=1, message="Use a LinkingObjects property")
public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] {
return RLMObjectBaseLinkingObjectsOfClass(self, (T.self as Object.Type).className(), propertyName) as! [T]
}
// MARK: Key-Value Coding & Subscripting
/// Returns or sets the value of the property with the given name.
public subscript(key: String) -> AnyObject? {
get {
if realm == nil {
return valueForKey(key)
}
let property = RLMValidatedGetProperty(self, key)
if property.type == .Array {
return listForProperty(property)
}
// No special logic is needed for optional numbers here because the NSNumber returned by RLMDynamicGet
// is better for callers than the RealmOptional that optionalForProperty would give us.
return RLMDynamicGet(self, property)
}
set(value) {
if realm == nil {
setValue(value, forKey: key)
} else {
RLMDynamicValidatedSet(self, key, value)
}
}
}
// MARK: Dynamic list
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use instance variables or cast the KVC returns.
Returns a List of DynamicObjects for a property name
- warning: This method is useful only in specialized circumstances
- parameter propertyName: The name of the property to get a List<DynamicObject>
- returns: A List of DynamicObjects
:nodoc:
*/
public func dynamicList(propertyName: String) -> List<DynamicObject> {
return unsafeBitCast(listForProperty(RLMValidatedGetProperty(self, propertyName)), List<DynamicObject>.self)
}
// MARK: Equatable
/**
Returns whether both objects are equal.
Objects are considered equal when they are both from the same Realm and point to the same
underlying object in the database.
- parameter object: Object to compare for equality.
*/
public override func isEqual(object: AnyObject?) -> Bool {
return RLMObjectBaseAreEqual(self as RLMObjectBase?, object as? RLMObjectBase)
}
// MARK: Private functions
// FIXME: None of these functions should be exposed in the public interface.
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override required init(value: AnyObject, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
// Helper for getting the list object for a property
internal func listForProperty(prop: RLMProperty) -> RLMListBase {
return object_getIvar(self, prop.swiftIvar) as! RLMListBase
}
// Helper for getting the optional object for a property
internal func optionalForProperty(prop: RLMProperty) -> RLMOptionalBase {
return object_getIvar(self, prop.swiftIvar) as! RLMOptionalBase
}
// Helper for getting the linking objects object for a property
internal func linkingObjectsForProperty(prop: RLMProperty) -> LinkingObjectsBase? {
return object_getIvar(self, prop.swiftIvar) as? LinkingObjectsBase
}
}
/// Object interface which allows untyped getters and setters for Objects.
/// :nodoc:
public final class DynamicObject: Object {
private var listProperties = [String: List<DynamicObject>]()
private var optionalProperties = [String: RLMOptionalBase]()
// Override to create List<DynamicObject> on access
internal override func listForProperty(prop: RLMProperty) -> RLMListBase {
if let list = listProperties[prop.name] {
return list
}
let list = List<DynamicObject>()
listProperties[prop.name] = list
return list
}
// Override to create RealmOptional on access
internal override func optionalForProperty(prop: RLMProperty) -> RLMOptionalBase {
if let optional = optionalProperties[prop.name] {
return optional
}
let optional = RLMOptionalBase()
optional.property = prop
optionalProperties[prop.name] = optional
return optional
}
// Dynamic objects never have linking objects properties
internal override func linkingObjectsForProperty(prop: RLMProperty) -> LinkingObjectsBase? {
return nil
}
/// :nodoc:
public override func valueForUndefinedKey(key: String) -> AnyObject? {
return self[key]
}
/// :nodoc:
public override func setValue(value: AnyObject?, forUndefinedKey key: String) {
self[key] = value
}
/// :nodoc:
public override class func shouldIncludeInDefaultSchema() -> Bool {
return false
}
}
/// :nodoc:
/// Internal class. Do not use directly.
@objc(RealmSwiftObjectUtil)
public class ObjectUtil: NSObject {
@objc private class func swiftVersion() -> NSString {
return swiftLanguageVersion
}
@objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.ignoredProperties() as NSArray?
}
return nil
}
@objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.indexedProperties() as NSArray?
}
return nil
}
@objc private class func linkingObjectsPropertiesForClass(type: AnyClass) -> NSDictionary? {
// Not used for Swift. getLinkingObjectsProperties(_:) is used instead.
return nil
}
// Get the names of all properties in the object which are of type List<>.
@objc private class func getGenericListPropertyNames(object: AnyObject) -> NSArray {
return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in
return prop.value.dynamicType is RLMListBase.Type
}.flatMap { (prop: Mirror.Child) in
return prop.label
}
}
@objc private class func initializeListProperty(object: RLMObjectBase, property: RLMProperty, array: RLMArray) {
(object as! Object).listForProperty(property)._rlmArray = array
}
@objc private class func initializeOptionalProperty(object: RLMObjectBase, property: RLMProperty) {
let optional = (object as! Object).optionalForProperty(property)
optional.property = property
optional.object = object
}
// swiftlint:disable:next cyclomatic_complexity
@objc private class func getOptionalProperties(object: AnyObject) -> NSDictionary {
let children = Mirror(reflecting: object).children
return children.reduce([String: AnyObject]()) { ( properties: [String:AnyObject], prop: Mirror.Child) in
guard let name = prop.label else { return properties }
let mirror = Mirror(reflecting: prop.value)
let type = mirror.subjectType
var properties = properties
if type is Optional<String>.Type || type is Optional<NSString>.Type {
properties[name] = Int(PropertyType.String.rawValue)
} else if type is Optional<NSDate>.Type {
properties[name] = Int(PropertyType.Date.rawValue)
} else if type is Optional<NSData>.Type {
properties[name] = Int(PropertyType.Data.rawValue)
} else if type is Optional<Object>.Type {
properties[name] = Int(PropertyType.Object.rawValue)
} else if type is RealmOptional<Int>.Type ||
type is RealmOptional<Int8>.Type ||
type is RealmOptional<Int16>.Type ||
type is RealmOptional<Int32>.Type ||
type is RealmOptional<Int64>.Type {
properties[name] = Int(PropertyType.Int.rawValue)
} else if type is RealmOptional<Float>.Type {
properties[name] = Int(PropertyType.Float.rawValue)
} else if type is RealmOptional<Double>.Type {
properties[name] = Int(PropertyType.Double.rawValue)
} else if type is RealmOptional<Bool>.Type {
properties[name] = Int(PropertyType.Bool.rawValue)
} else if prop.value as? RLMOptionalBase != nil {
throwRealmException("'\(type)' is not a a valid RealmOptional type.")
} else if mirror.displayStyle == .Optional {
properties[name] = NSNull()
}
return properties
}
}
@objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? {
return nil
}
// Get information about each of the linking objects properties.
@objc private class func getLinkingObjectsProperties(object: AnyObject) -> NSDictionary {
let properties = Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in
return prop.value as? LinkingObjectsBase != nil
}.flatMap { (prop: Mirror.Child) in
(prop.label!, prop.value as! LinkingObjectsBase)
}
return properties.reduce([:] as [String : [String: String ]]) { (dictionary, property) in
var d = dictionary
let (name, results) = property
d[name] = ["class": results.objectClassName, "property": results.propertyName]
return d
}
}
@objc private class func initializeLinkingObjectsProperty(object: RLMObjectBase, property: RLMProperty,
results: RLMResults) {
guard let linkingObjects = (object as! Object).linkingObjectsForProperty(property) else { return }
linkingObjects.rlmResults = results
}
}
|
mit
|
d4b3450670ae3484b21134c96881508c
| 36.947608 | 119 | 0.656522 | 4.837108 | false | false | false | false |
Petrachkov/DottedCircleProgressView
|
Example/DottedCircleProgressView/ViewController.swift
|
1
|
2384
|
//
// ViewController.swift
// DottedCircleProgressView
//
// Created by sergey petrachkov on 10/25/2016.
// Copyright (c) 2016 sergey petrachkov. All rights reserved.
//
import UIKit
import DottedCircleProgressView
class ViewController: UIViewController {
var progressView : DottedCircleProgressView!
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: self.view.frame.width * 0.5 - 33 * 0.5,
y: self.view.frame.height * 0.5 - 33 * 0.5,
width: 33,
height: 33)
let progressConfig = ProgressLayerConfigurator(fillColor: UIColor.white.cgColor,
backgroundColor: UIColor.white.cgColor,
strokeColor: UIColor.white.cgColor,
instanceColor: UIColor.white.cgColor,
frame: CGRect(x: 9,
y: 9,
width: frame.width - 18,
height: frame.height - 18),
instanceCount: 8,
dotSize: 3)
self.progressView = DottedCircleProgressView(frame: frame,
progressConfigurator: progressConfig)
self.progressView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
self.progressView.layer.cornerRadius = progressView.frame.size.width * 0.5
self.progressView.clipsToBounds = true
self.view.addSubview(self.progressView)
let visibilitySwitch = UISwitch(frame: CGRect(x: self.view.frame.width * 0.5 - 50 * 0.5,
y: progressView.frame.maxY + 10,
width: 60,
height: 40))
visibilitySwitch.addTarget(self,
action: #selector(ViewController.switchStateChanged(sender:)),
for: .valueChanged)
visibilitySwitch.isOn = true
self.view.addSubview(visibilitySwitch)
}
func switchStateChanged(sender : UISwitch) {
progressView.isHidden = !sender.isOn
}
}
|
mit
|
52f12e09d3907f820e20684aa3338f5a
| 43.981132 | 93 | 0.5 | 5.061571 | false | true | false | false |
kopto/KRActivityIndicatorView
|
KRActivityIndicatorView/KRActivityIndicatorAnimationLineScaleParty.swift
|
1
|
2777
|
//
// KRActivityIndicatorAnimationLineScaleParty.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
class KRActivityIndicatorAnimationLineScaleParty: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let lineSize = size.width / 7
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations: [CFTimeInterval] = [1.26, 0.43, 1.01, 0.73]
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0.77, 0.29, 0.28, 0.74]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// Animation
let animation = CAKeyframeAnimation(keyPath:"transform.scale")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.5, 1]
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
for i in 0 ..< 4 {
let line = KRActivityIndicatorShape.line.layerWith(size: CGSize(width: lineSize, height: size.height), color: color)
let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height)
animation.beginTime = beginTime + beginTimes[i]
animation.duration = durations[i]
line.frame = frame
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
|
mit
|
8db2bedc0f18c794fdefc8016a8177f5
| 43.790323 | 128 | 0.690673 | 4.537582 | false | false | false | false |
mykoma/NetworkingLib
|
Demo/NetworkingDemo/NetworkingDemo/OAuthTransaction.swift
|
1
|
1634
|
//
// OAuthTransaction.swift
// NetworkingDemo
//
// Created by Apple on 2017/8/17.
// Copyright © 2017年 Goluk. All rights reserved.
//
import UIKit
import Networking
class OAuthTransaction: RemoteServerTransaction {
// value of AuthType.rawValue
var platform: String? = "weixin"
var openid: String? = "oMLAX1csGr1Zka88rTlVRVkQFRVQ"
var name: String? = "成都老刘"
var gender: Int? = 1
var avatar: String? = "http://wx.qlogo.cn/mmopen/INk4JvWfe8U2ibibdeYkxah8PZd6PKrqJJKT3KvSZ9p1sBVIeW6NQDpSTgzkNCw6lgyvTB4hCHH42eiadWnF43HOFzmFvUEmQIF/0"
override func subUri() -> String {
return "/user/authlogin"
}
override func httpType() -> HttpMethodType {
return .POST_BODY
}
override func httpData() -> Data? {
var dict: [String: AnyObject] = [:]
if let openid = openid {
dict["openid"] = openid as AnyObject
}
if let name = name {
dict["name"] = name as AnyObject
}
if let avatar = avatar {
dict["avatar"] = avatar as AnyObject
}
if let gender = gender {
dict["sex"] = gender as AnyObject
}
let jsonData = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted)
return jsonData
}
override func excludeParameters() -> [String] {
var superList = super.excludeParameters()
superList.append("openid")
superList.append("name")
superList.append("gender")
superList.append("avatar")
return superList
}
}
|
mit
|
82127bc5ecef6d4dc82bed731b8807d3
| 27.982143 | 155 | 0.618608 | 3.697039 | false | false | false | false |
kstaring/swift
|
benchmark/utils/main.swift
|
1
|
10274
|
//===--- main.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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is automatically generated from templates and should not
// be directly modified. Instead, make changes to
// scripts/generate_harness/main.swift_template and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
// This is just a driver for performance overview tests.
import TestsUtils
import DriverUtils
import Ackermann
import AngryPhonebook
import AnyHashableWithAClass
import Array2D
import ArrayAppend
import ArrayInClass
import ArrayLiteral
import ArrayOfGenericPOD
import ArrayOfGenericRef
import ArrayOfPOD
import ArrayOfRef
import ArraySubscript
import BitCount
import ByteSwap
import Calculator
import CaptureProp
import Chars
import ClassArrayGetter
import DeadArray
import DictTest
import DictTest2
import DictTest3
import DictionaryBridge
import DictionaryLiteral
import DictionaryRemove
import DictionarySwap
import ErrorHandling
import Fibonacci
import GlobalClass
import Hanoi
import Hash
import Histogram
import Integrate
import IterateData
import Join
import LinkedList
import MapReduce
import Memset
import MonteCarloE
import MonteCarloPi
import NSDictionaryCastToSwift
import NSError
import NSStringConversion
import NopDeinit
import ObjectAllocation
import ObjectiveCBridging
import ObjectiveCBridgingStubs
import ObjectiveCNoBridgingStubs
import ObserverClosure
import ObserverForwarderStruct
import ObserverPartiallyAppliedMethod
import ObserverUnappliedMethod
import OpenClose
import Phonebook
import PolymorphicCalls
import PopFront
import PopFrontGeneric
import Prims
import ProtocolDispatch
import ProtocolDispatch2
import RC4
import RGBHistogram
import RangeAssignment
import RecursiveOwnedParameter
import SetTests
import SevenBoom
import Sim2DArray
import SortLettersInPlace
import SortStrings
import StackPromo
import StaticArray
import StrComplexWalk
import StrToInt
import StringBuilder
import StringInterpolation
import StringTests
import StringWalk
import SuperChars
import TwoSum
import TypeFlood
import UTF8Decode
import Walsh
import XorLoop
precommitTests = [
"AngryPhonebook": run_AngryPhonebook,
"AnyHashableWithAClass": run_AnyHashableWithAClass,
"Array2D": run_Array2D,
"ArrayAppend": run_ArrayAppend,
"ArrayAppendReserved": run_ArrayAppendReserved,
"ArrayAppendSequence": run_ArrayAppendSequence,
"ArrayAppendArrayOfInt": run_ArrayAppendArrayOfInt,
"ArrayAppendStrings": run_ArrayAppendStrings,
"ArrayAppendGenericStructs": run_ArrayAppendGenericStructs,
"ArrayAppendOptionals": run_ArrayAppendOptionals,
"ArrayAppendLazyMap": run_ArrayAppendLazyMap,
"ArrayAppendRepeatCol": run_ArrayAppendRepeatCol,
"ArrayInClass": run_ArrayInClass,
"ArrayLiteral": run_ArrayLiteral,
"ArrayOfGenericPOD": run_ArrayOfGenericPOD,
"ArrayOfGenericRef": run_ArrayOfGenericRef,
"ArrayOfPOD": run_ArrayOfPOD,
"ArrayOfRef": run_ArrayOfRef,
"ArraySubscript": run_ArraySubscript,
"ArrayValueProp": run_ArrayValueProp,
"ArrayValueProp2": run_ArrayValueProp2,
"ArrayValueProp3": run_ArrayValueProp3,
"ArrayValueProp4": run_ArrayValueProp4,
"BitCount": run_BitCount,
"ByteSwap": run_ByteSwap,
"Calculator": run_Calculator,
"CaptureProp": run_CaptureProp,
"Chars": run_Chars,
"ClassArrayGetter": run_ClassArrayGetter,
"DeadArray": run_DeadArray,
"Dictionary": run_Dictionary,
"Dictionary2": run_Dictionary2,
"Dictionary2OfObjects": run_Dictionary2OfObjects,
"Dictionary3": run_Dictionary3,
"Dictionary3OfObjects": run_Dictionary3OfObjects,
"DictionaryBridge": run_DictionaryBridge,
"DictionaryLiteral": run_DictionaryLiteral,
"DictionaryOfObjects": run_DictionaryOfObjects,
"DictionaryRemove": run_DictionaryRemove,
"DictionaryRemoveOfObjects": run_DictionaryRemoveOfObjects,
"DictionarySwap": run_DictionarySwap,
"DictionarySwapOfObjects": run_DictionarySwapOfObjects,
"ErrorHandling": run_ErrorHandling,
"GlobalClass": run_GlobalClass,
"Hanoi": run_Hanoi,
"HashTest": run_HashTest,
"Histogram": run_Histogram,
"Integrate": run_Integrate,
"IterateData": run_IterateData,
"Join": run_Join,
"LinkedList": run_LinkedList,
"MapReduce": run_MapReduce,
"Memset": run_Memset,
"MonteCarloE": run_MonteCarloE,
"MonteCarloPi": run_MonteCarloPi,
"NSDictionaryCastToSwift": run_NSDictionaryCastToSwift,
"NSError": run_NSError,
"NSStringConversion": run_NSStringConversion,
"NopDeinit": run_NopDeinit,
"ObjectAllocation": run_ObjectAllocation,
"ObjectiveCBridgeFromNSArrayAnyObject": run_ObjectiveCBridgeFromNSArrayAnyObject,
"ObjectiveCBridgeFromNSArrayAnyObjectForced": run_ObjectiveCBridgeFromNSArrayAnyObjectForced,
"ObjectiveCBridgeFromNSArrayAnyObjectToString": run_ObjectiveCBridgeFromNSArrayAnyObjectToString,
"ObjectiveCBridgeFromNSArrayAnyObjectToStringForced": run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced,
"ObjectiveCBridgeFromNSDictionaryAnyObject": run_ObjectiveCBridgeFromNSDictionaryAnyObject,
"ObjectiveCBridgeFromNSDictionaryAnyObjectForced": run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced,
"ObjectiveCBridgeFromNSDictionaryAnyObjectToString": run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString,
"ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced": run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced,
"ObjectiveCBridgeFromNSSetAnyObject": run_ObjectiveCBridgeFromNSSetAnyObject,
"ObjectiveCBridgeFromNSSetAnyObjectForced": run_ObjectiveCBridgeFromNSSetAnyObjectForced,
"ObjectiveCBridgeFromNSSetAnyObjectToString": run_ObjectiveCBridgeFromNSSetAnyObjectToString,
"ObjectiveCBridgeFromNSSetAnyObjectToStringForced": run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced,
"ObjectiveCBridgeFromNSString": run_ObjectiveCBridgeFromNSString,
"ObjectiveCBridgeFromNSStringForced": run_ObjectiveCBridgeFromNSStringForced,
"ObjectiveCBridgeStubDataAppend": run_ObjectiveCBridgeStubDataAppend,
"ObjectiveCBridgeStubDateAccess": run_ObjectiveCBridgeStubDateAccess,
"ObjectiveCBridgeStubDateMutation": run_ObjectiveCBridgeStubDateMutation,
"ObjectiveCBridgeStubFromArrayOfNSString": run_ObjectiveCBridgeStubFromArrayOfNSString,
"ObjectiveCBridgeStubFromNSDate": run_ObjectiveCBridgeStubFromNSDate,
"ObjectiveCBridgeStubFromNSDateRef": run_ObjectiveCBridgeStubFromNSDateRef,
"ObjectiveCBridgeStubFromNSString": run_ObjectiveCBridgeStubFromNSString,
"ObjectiveCBridgeStubFromNSStringRef": run_ObjectiveCBridgeStubFromNSStringRef,
"ObjectiveCBridgeStubNSDataAppend": run_ObjectiveCBridgeStubNSDataAppend,
"ObjectiveCBridgeStubNSDateMutationRef": run_ObjectiveCBridgeStubNSDateMutationRef,
"ObjectiveCBridgeStubNSDateRefAccess": run_ObjectiveCBridgeStubNSDateRefAccess,
"ObjectiveCBridgeStubToArrayOfNSString": run_ObjectiveCBridgeStubToArrayOfNSString,
"ObjectiveCBridgeStubToNSDate": run_ObjectiveCBridgeStubToNSDate,
"ObjectiveCBridgeStubToNSDateRef": run_ObjectiveCBridgeStubToNSDateRef,
"ObjectiveCBridgeStubToNSString": run_ObjectiveCBridgeStubToNSString,
"ObjectiveCBridgeStubToNSStringRef": run_ObjectiveCBridgeStubToNSStringRef,
"ObjectiveCBridgeStubURLAppendPath": run_ObjectiveCBridgeStubURLAppendPath,
"ObjectiveCBridgeStubURLAppendPathRef": run_ObjectiveCBridgeStubURLAppendPathRef,
"ObjectiveCBridgeToNSArray": run_ObjectiveCBridgeToNSArray,
"ObjectiveCBridgeToNSDictionary": run_ObjectiveCBridgeToNSDictionary,
"ObjectiveCBridgeToNSSet": run_ObjectiveCBridgeToNSSet,
"ObjectiveCBridgeToNSString": run_ObjectiveCBridgeToNSString,
"ObserverClosure": run_ObserverClosure,
"ObserverForwarderStruct": run_ObserverForwarderStruct,
"ObserverPartiallyAppliedMethod": run_ObserverPartiallyAppliedMethod,
"ObserverUnappliedMethod": run_ObserverUnappliedMethod,
"OpenClose": run_OpenClose,
"Phonebook": run_Phonebook,
"PolymorphicCalls": run_PolymorphicCalls,
"PopFrontArray": run_PopFrontArray,
"PopFrontArrayGeneric": run_PopFrontArrayGeneric,
"PopFrontUnsafePointer": run_PopFrontUnsafePointer,
"Prims": run_Prims,
"ProtocolDispatch": run_ProtocolDispatch,
"ProtocolDispatch2": run_ProtocolDispatch2,
"RC4": run_RC4,
"RGBHistogram": run_RGBHistogram,
"RGBHistogramOfObjects": run_RGBHistogramOfObjects,
"RangeAssignment": run_RangeAssignment,
"RecursiveOwnedParameter": run_RecursiveOwnedParameter,
"SetExclusiveOr": run_SetExclusiveOr,
"SetExclusiveOr_OfObjects": run_SetExclusiveOr_OfObjects,
"SetIntersect": run_SetIntersect,
"SetIntersect_OfObjects": run_SetIntersect_OfObjects,
"SetIsSubsetOf": run_SetIsSubsetOf,
"SetIsSubsetOf_OfObjects": run_SetIsSubsetOf_OfObjects,
"SetUnion": run_SetUnion,
"SetUnion_OfObjects": run_SetUnion_OfObjects,
"SevenBoom": run_SevenBoom,
"Sim2DArray": run_Sim2DArray,
"SortLettersInPlace": run_SortLettersInPlace,
"SortStrings": run_SortStrings,
"SortStringsUnicode": run_SortStringsUnicode,
"StackPromo": run_StackPromo,
"StaticArray": run_StaticArray,
"StrComplexWalk": run_StrComplexWalk,
"StrToInt": run_StrToInt,
"StringBuilder": run_StringBuilder,
"StringEqualPointerComparison": run_StringEqualPointerComparison,
"StringHasPrefix": run_StringHasPrefix,
"StringHasPrefixUnicode": run_StringHasPrefixUnicode,
"StringHasSuffix": run_StringHasSuffix,
"StringHasSuffixUnicode": run_StringHasSuffixUnicode,
"StringInterpolation": run_StringInterpolation,
"StringWalk": run_StringWalk,
"StringWithCString": run_StringWithCString,
"SuperChars": run_SuperChars,
"TwoSum": run_TwoSum,
"TypeFlood": run_TypeFlood,
"UTF8Decode": run_UTF8Decode,
"Walsh": run_Walsh,
"XorLoop": run_XorLoop,
]
otherTests = [
"Ackermann": run_Ackermann,
"Fibonacci": run_Fibonacci,
]
main()
|
apache-2.0
|
062db5b87947e60c4c53ac499e42ad53
| 38.21374 | 121 | 0.804945 | 5.244513 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Models/Shepard/Shepard.ClassTalent.swift
|
1
|
748
|
//
// Shepard.ClassTalent.swift
// MEGameTracker
//
// Created by Emily Ivie on 8/15/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
extension Shepard {
// Dumb reserved words, uhg.
/// Game options for Shepard's class.
public enum ClassTalent: String, Codable {
case soldier = "Soldier"
case engineer = "Engineer"
case adept = "Adept"
case infiltrator = "Infiltrator"
case sentinel = "Sentinel"
case vanguard = "Vanguard"
/// Creates an enum from a string value, if possible.
public init?(stringValue: String?) {
self.init(rawValue: stringValue ?? "")
}
/// Returns the string value of an enum.
public var stringValue: String {
return rawValue
}
}
}
// already Equatable
|
mit
|
f6180b4839e2da13d2c7e7118a3efd13
| 19.75 | 55 | 0.681392 | 3.38009 | false | false | false | false |
fgengine/quickly
|
Quickly/ViewControllers/Stack/QStackViewController.swift
|
1
|
12242
|
//
// Quickly
//
open class QStackViewController : QViewController, IQStackViewController, IQModalContentViewController, IQHamburgerContentViewController, IQJalousieContentViewController {
open var barView: QStackbar? {
set(value) { self.set(barView: value) }
get { return self._barView }
}
open var barSize: QStackViewControllerBarSize {
set(value) { self.set(barSize: value) }
get { return self._barSize }
}
open var barHidden: Bool {
set(value) { self.set(barHidden: value) }
get { return self._barHidden }
}
open private(set) var viewController: IQStackContentViewController
open var presentAnimation: IQStackViewControllerPresentAnimation?
open var dismissAnimation: IQStackViewControllerDismissAnimation?
open var interactiveDismissAnimation: IQStackViewControllerInteractiveDismissAnimation?
private var _barView: QStackbar?
private var _barSize: QStackViewControllerBarSize
private var _barHidden: Bool
public init(
barSize: QStackViewControllerBarSize = .fixed(height: 50),
barHidden: Bool = false,
viewController: IQStackContentViewController,
presentAnimation: IQStackViewControllerPresentAnimation? = nil,
dismissAnimation: IQStackViewControllerDismissAnimation? = nil,
interactiveDismissAnimation: IQStackViewControllerInteractiveDismissAnimation? = nil
) {
self._barSize = barSize
self._barHidden = false
self.viewController = viewController
self.presentAnimation = presentAnimation
self.dismissAnimation = dismissAnimation
self.interactiveDismissAnimation = interactiveDismissAnimation
super.init()
}
open override func setup() {
super.setup()
self.viewController.parentViewController = self
}
open override func didLoad() {
self._updateAdditionalEdgeInsets()
self.viewController.view.frame = self.view.bounds
self.view.addSubview(self.viewController.view)
if let barView = self._barView {
barView.edgeInsets = self._barEdgeInsets()
barView.frame = self._barFrame(bounds: self.view.bounds)
self.view.addSubview(barView)
}
}
open override func layout(bounds: CGRect) {
self.viewController.view.frame = bounds
if let barView = self._barView {
barView.edgeInsets = self._barEdgeInsets()
barView.frame = self._barFrame(bounds: bounds)
}
}
open override func prepareInteractivePresent() {
super.prepareInteractivePresent()
self.viewController.prepareInteractivePresent()
}
open override func cancelInteractivePresent() {
super.cancelInteractivePresent()
self.viewController.cancelInteractivePresent()
}
open override func finishInteractivePresent() {
super.finishInteractivePresent()
self.viewController.finishInteractivePresent()
}
open override func willPresent(animated: Bool) {
super.willPresent(animated: animated)
self.viewController.willPresent(animated: animated)
}
open override func didPresent(animated: Bool) {
super.didPresent(animated: animated)
self.viewController.didPresent(animated: animated)
}
open override func prepareInteractiveDismiss() {
super.prepareInteractiveDismiss()
self.viewController.prepareInteractiveDismiss()
}
open override func cancelInteractiveDismiss() {
super.cancelInteractiveDismiss()
self.viewController.cancelInteractiveDismiss()
}
open override func finishInteractiveDismiss() {
super.finishInteractiveDismiss()
self.viewController.finishInteractiveDismiss()
}
open override func willDismiss(animated: Bool) {
super.willDismiss(animated: animated)
self.viewController.willDismiss(animated: animated)
}
open override func didDismiss(animated: Bool) {
super.didDismiss(animated: animated)
self.viewController.didDismiss(animated: animated)
}
open override func willTransition(size: CGSize) {
super.willTransition(size: size)
self.viewController.willTransition(size: size)
}
open override func didTransition(size: CGSize) {
super.didTransition(size: size)
self.viewController.didTransition(size: size)
}
open override func supportedOrientations() -> UIInterfaceOrientationMask {
return self.viewController.supportedOrientations()
}
open override func preferedStatusBarHidden() -> Bool {
return self.viewController.preferedStatusBarHidden()
}
open override func preferedStatusBarStyle() -> UIStatusBarStyle {
return self.viewController.preferedStatusBarStyle()
}
open override func preferedStatusBarAnimation() -> UIStatusBarAnimation {
return self.viewController.preferedStatusBarAnimation()
}
open func set(barView: QStackbar?, animated: Bool = false) {
if self._barView != barView {
if self.isLoaded == true && self.isLoading == false {
if let view = self._barView {
view.removeFromSuperview()
}
self._barView = barView
if let view = self._barView {
view.frame = self._barFrame(bounds: self.view.bounds)
view.edgeInsets = self._barEdgeInsets()
self.view.insertSubview(view, aboveSubview: self.viewController.view)
}
self.setNeedLayout()
} else {
self._barView = barView
}
self._updateAdditionalEdgeInsets()
}
}
open func set(barSize: QStackViewControllerBarSize, animated: Bool = false) {
if self._barSize != barSize {
self._barSize = barSize
self._updateAdditionalEdgeInsets()
if self.isLoaded == true && self.isLoading == false {
self.setNeedLayout()
if animated == true {
UIView.animate(withDuration: 0.1, delay: 0, options: [ .beginFromCurrentState ], animations: {
self.layoutIfNeeded()
})
}
}
}
}
open func set(barHidden: Bool, animated: Bool = false) {
if self._barHidden != barHidden {
self._barHidden = barHidden
self.setNeedLayout()
self._updateAdditionalEdgeInsets()
if self.isLoaded == true {
if animated == true {
UIView.animate(withDuration: 0.1, delay: 0, options: [ .beginFromCurrentState ], animations: {
self.layoutIfNeeded()
})
}
}
}
}
// MARK: IQContentOwnerViewController
open func beginUpdateContent() {
}
open func updateContent() {
if let view = self._barView {
view.frame = self._barFrame(bounds: self.view.bounds)
}
}
open func finishUpdateContent(velocity: CGPoint) -> CGPoint? {
if self._barHidden == true {
return nil
}
switch self._barSize {
case .fixed(_):
return nil
case .range(let minHeight, let maxHeight):
let edgeInsets = self.inheritedEdgeInsets
let contentOffset = self.viewController.contentOffset
let interactiveBarHeight = maxHeight - contentOffset.y
let normalizedBarHeight = max(minHeight, min(interactiveBarHeight, maxHeight)) + edgeInsets.top
let minimalBarHeight = minHeight + edgeInsets.top
let maximalBarHeight = maxHeight + edgeInsets.top
if (normalizedBarHeight > minimalBarHeight) && (normalizedBarHeight < maximalBarHeight) {
let middleBarHeight = minimalBarHeight + ((maximalBarHeight - minimalBarHeight) / 2)
return CGPoint(
x: contentOffset.x,
y: normalizedBarHeight > middleBarHeight ? -maximalBarHeight : -minimalBarHeight
)
}
return nil
}
}
open func endUpdateContent() {
if let view = self._barView {
view.frame = self._barFrame(bounds: self.view.bounds)
}
}
// MARK: IQContentViewController
public var contentOffset: CGPoint {
get { return CGPoint.zero }
}
public var contentSize: CGSize {
get {
guard self.isLoaded == true else { return CGSize.zero }
return self.view.bounds.size
}
}
open func notifyBeginUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.beginUpdateContent()
}
}
open func notifyUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.updateContent()
}
}
open func notifyFinishUpdateContent(velocity: CGPoint) -> CGPoint? {
if let viewController = self.contentOwnerViewController {
return viewController.finishUpdateContent(velocity: velocity)
}
return nil
}
open func notifyEndUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.endUpdateContent()
}
}
// MARK: IQModalContentViewController
open func modalShouldInteractive() -> Bool {
guard let currentViewController = self.viewController as? IQModalContentViewController else { return false }
return currentViewController.modalShouldInteractive()
}
// MARK: IQHamburgerContentViewController
open func hamburgerShouldInteractive() -> Bool {
guard let currentViewController = self.viewController as? IQHamburgerContentViewController else { return false }
return currentViewController.hamburgerShouldInteractive()
}
// MARK: IQJalousieContentViewController
open func jalousieShouldInteractive() -> Bool {
guard let currentViewController = self.viewController as? IQJalousieContentViewController else { return false }
return currentViewController.jalousieShouldInteractive()
}
}
// MARK: Private
private extension QStackViewController {
func _updateAdditionalEdgeInsets() {
guard self._barView != nil && self._barHidden == false else {
self.additionalEdgeInsets = UIEdgeInsets.zero
return
}
switch self._barSize {
case .fixed(let height):
self.additionalEdgeInsets = UIEdgeInsets(
top: height,
left: 0,
bottom: 0,
right: 0
)
case .range(_, let max):
self.additionalEdgeInsets = UIEdgeInsets(
top: max,
left: 0,
bottom: 0,
right: 0
)
}
}
func _barFrame(bounds: CGRect) -> CGRect {
let edgeInsets = self.inheritedEdgeInsets
var barHeight: CGFloat
switch self._barSize {
case .fixed(let height):
barHeight = height + edgeInsets.top
case .range(let minHeight, let maxHeight):
let contentOffset = self.viewController.contentOffset
let interactiveBarHeight = maxHeight - contentOffset.y
barHeight = max(minHeight, min(interactiveBarHeight, maxHeight)) + edgeInsets.top
}
if self._barHidden == true {
return CGRect(x: bounds.origin.x, y: bounds.origin.y - barHeight, width: bounds.size.width, height: barHeight)
}
return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.size.width, height: barHeight)
}
func _barEdgeInsets() -> UIEdgeInsets {
let edgeInsets = self.inheritedEdgeInsets
return UIEdgeInsets(
top: edgeInsets.top,
left: edgeInsets.left,
bottom: 0,
right: edgeInsets.right
)
}
}
|
mit
|
c07d722d29b45b3bba319c522265ccd9
| 33.484507 | 171 | 0.624081 | 5.26991 | false | false | false | false |
taichisocks/taichiOSX
|
taichiOSX/swifter/ActiveRecord/SwifterSQLiteDatabaseProxy.swift
|
2
|
4674
|
//
// SQLiteProxy.swift
// Swifter
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
class SQLiteSequenceElement {
let statementPointer: COpaquePointer
init(pointer: COpaquePointer) {
self.statementPointer = pointer
}
func string(column: Int32) -> String {
if let value = String.fromCString(UnsafePointer<CChar>(sqlite3_column_text(statementPointer, column))) {
return value
}
/// Should never happend :)
/// From 'String.fromCString' documentation:
/// Returns `nil` if the `CString` is `NULL` or if it contains ill-formed
/// UTF-8 code unit sequences.
return "????"
}
func integer(column: Int32) -> Int32 {
return sqlite3_column_int(statementPointer, column)
}
func double(column: Int32) -> Double {
return sqlite3_column_double(statementPointer, column)
}
}
class SQLiteSequenceGenarator: GeneratorType {
let statementPointer: COpaquePointer
init(pointer: COpaquePointer) {
self.statementPointer = pointer
}
func next() -> SQLiteSequenceElement? {
if ( sqlite3_step(statementPointer) == SQLITE_ROW ) {
return SQLiteSequenceElement(pointer: statementPointer)
}
sqlite3_finalize(statementPointer)
return nil
}
}
class SQLiteSequence: SequenceType {
var statementPointer = COpaquePointer()
init?(db: COpaquePointer, sql: String, err: NSErrorPointer? = nil) {
let result = sql.withCString { sqlite3_prepare(db, $0, Int32(strlen($0)), &self.statementPointer, nil) };
if result != SQLITE_OK {
if let err = err { err.memory = error("Can't prepare statement: \(sql), Error: \(result)") }
return nil
}
}
func error(reason: String) -> NSError {
return NSError(domain: "SQLiteSequence", code: 0, userInfo: [NSLocalizedDescriptionKey : reason])
}
func generate() -> SQLiteSequenceGenarator {
return SQLiteSequenceGenarator(pointer: statementPointer)
}
}
class SwifterSQLiteDatabaseProxy: SwifterDatabseProxy {
let name: String
init(name databaseName: String) {
name = databaseName
}
func err(reason: String) -> NSError {
return NSError(domain: "SwifterSQLiteDatabaseProxy", code: 0, userInfo: [NSLocalizedDescriptionKey : reason])
}
func execute<Result>(name: String, sql: String, err: NSErrorPointer? = nil, f: ((SQLiteSequence) -> Result?)? = nil ) -> Result? {
var database = COpaquePointer()
if ( SQLITE_OK == name.withCString { sqlite3_open($0, &database) } ) {
if let sequence = SQLiteSequence(db: database, sql: sql, err: err) {
var result: Result?
if let f = f {
result = f(sequence)
}
sqlite3_close(database)
return result
}
sqlite3_close(database)
}
return nil
}
func scheme(error: NSErrorPointer?) -> [String: [(String, String)]]? {
let tables: [String]? = execute(name, sql: "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", err: error) { map($0, { $0.string(0) }) }
if let tables = tables {
var scheme = [String: [(String, String)]]()
for table in tables {
let columns: [(String, String)]? = execute(name, sql: "PRAGMA table_info('\(table)');", err: error) { map($0, { ($0.string(1), $0.string(2)) } ) }
if let columns = columns {
scheme[table] = columns
} else {
return nil
}
}
return scheme
}
return nil
}
func createTable(name: String, columns: [String: String], error: NSErrorPointer?) -> Bool {
return false
}
func deleteTable(name: String, error: NSErrorPointer?) -> Bool {
return false
}
func insertColumn(table: String, column: String, error: NSErrorPointer?) -> Bool {
return false
}
func deleteColumn(table: String, column: String, error: NSErrorPointer?) -> Bool {
return false
}
func copyColumn(table: String, from: String, to: String, error: NSErrorPointer?) -> Bool {
return false
}
func insertRow(table: String, value: [String: String], error: NSErrorPointer?) -> Int {
return 0
}
func deleteRow(table: String, id: Int, error: NSErrorPointer?) -> Bool {
return false
}
}
|
apache-2.0
|
f2bffbeafbc5b59cefedea3e6beb429e
| 30.795918 | 162 | 0.581853 | 4.450476 | false | false | false | false |
ITzTravelInTime/TINU
|
EFI Partition Mounter/EFI Partition Mounter/EFIPartitionMounterWindowController.swift
|
1
|
3900
|
/*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Cocoa
#if (!macOnlyMode && TINU) || (!TINU && isTool)
public class EFIPartitionMounterWindowController: NSWindowController, NSToolbarDelegate {
@IBOutlet weak var toolBar: NSToolbar!
@IBOutlet weak var reloadToolBarItem: NSToolbarItem!
@IBOutlet weak var reloadToolBarItemButton: NSButton!
//@IBOutlet weak var menuBarModeToolBarItem: NSToolbarItem!
public func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier]{
#if TINU
return [reloadToolBarItem.itemIdentifier, .flexibleSpace, .space]
#else
return [reloadToolBarItem.itemIdentifier, menuBarModeToolBarItem.itemIdentifier, .flexibleSpace, .space]
#endif
}
public func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier]{
#if TINU
return [.flexibleSpace, reloadToolBarItem.itemIdentifier]
#else
return [.flexibleSpace, menuBarModeToolBarItem.itemIdentifier, reloadToolBarItem.itemIdentifier]
#endif
}
override public func windowDidLoad() {
super.windowDidLoad()
toolBar.delegate = self
guard let controller = self.window?.contentViewController as? EFIPartitionMounterViewController else { return }
self.window?.title = EFIPMTextManager.getViewString(context: controller, stringID: "title")
self.reloadToolBarItem.label = EFIPMTextManager.getViewString(context: controller, stringID: "refreshButton")
self.window?.isFullScreenEnaled = true
self.window?.collectionBehavior.insert(.fullScreenNone)
DispatchQueue.global(qos: .userInteractive).async {
var ok = false
while(!ok){
DispatchQueue.main.sync {
guard let vc = self.contentViewController as? EFIPartitionMounterViewController else{ return }
ok = true
//For somereason connection actions won't work on high sierra and below
self.reloadToolBarItem.target = vc
self.reloadToolBarItem.action = #selector(vc.refresh(_:))
self.reloadToolBarItemButton.target = vc
self.reloadToolBarItemButton.action = #selector(vc.refresh(_:))
}
}
}
}
@IBAction func reload(_ sender: NSToolbarItem) {
if let win = self.window?.contentViewController as? EFIPartitionMounterViewController{
win.refresh(sender)
}
}
@IBAction func toggleMenuBarMode(_ sender: NSToolbarItem) {
if let win = self.window?.contentViewController as? EFIPartitionMounterViewController{
win.toggleIconMode(sender)
}
}
override public func close() {
#if TINU
UIManager.shared.EFIPartitionMonuterTool = nil
#else
guard let win = self.window?.contentViewController as? EFIPartitionMounterViewController else { return }
if !win.barMode{
NSApplication.shared().terminate(self)
}
#endif
super.close()
}
#if !isTool
convenience init() {
//creates an instace of the window
self.init(window: (NSStoryboard(name: "EFIPartitionMounterTool", bundle: Bundle.main).instantiateController(withIdentifier: "EFIMounterWindow") as! NSWindowController).window)
//self.init(windowNibName: "ContactsWindowController")
}
#endif
}
#endif
|
gpl-2.0
|
4aa4d197aac5b6a63d5907baa9541d57
| 30.707317 | 177 | 0.750513 | 4.140127 | false | false | false | false |
rsbauer/Newsy
|
Newsy/Classes/Models/Transforms/DateStringTransform.swift
|
1
|
894
|
//
// DateStringTransform.swift
// Newsy
//
// Created by Astro on 8/25/15.
// Copyright (c) 2015 Rock Solid Bits. All rights reserved.
//
import Foundation
import ObjectMapper
// convert "Tue, 25 Aug 2015 13:08:43 GMT" to NSDate
public class DateStringTransform: TransformType {
public typealias Object = NSDate
public typealias JSON = String
let dateFormatter = NSDateFormatter()
public init() {
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
}
public func transformFromJSON(value: AnyObject?) -> NSDate? {
if let dateString = value as? String {
return dateFormatter.dateFromString(dateString)
}
return nil
}
public func transformToJSON(value: NSDate?) -> String? {
if let date = value {
return dateFormatter.stringFromDate(date)
}
return nil
}
}
|
mit
|
c888a1e0593bed8230835420c46b2b40
| 23.833333 | 65 | 0.639821 | 4.425743 | false | true | false | false |
google/EarlGrey
|
Demo/EarlGreyContribs/EarlGreyContribsSwiftTests/EarlGreyContribsSwiftTests.swift
|
2
|
2797
|
//
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import EarlGrey
import XCTest
class EarlGreyContribsSwiftTests: XCTestCase {
override func tearDown() {
EarlGrey.selectElement(with: grey_anyOf([grey_text("EarlGreyContribTestApp"),
grey_text("Back")]))
.perform(grey_tap())
super.tearDown()
}
func testBasicViewController() {
EarlGrey.selectElement(with: grey_text("Basic Views"))
.usingSearch(grey_scrollInDirection(.down, 50),
onElementWith: grey_kindOfClass(UITableView.self))
.perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityLabel("textField"))
.perform(grey_typeText("Foo"))
EarlGrey.selectElement(with: grey_accessibilityLabel("showButton"))
.perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityLabel("textLabel"))
.assert(grey_text("Foo"))
}
func testCountOfTableViewCells() {
var error: NSError? = nil
let matcher: GREYMatcher! = grey_kindOfClass(UITableViewCell.self)
let countOfTableViewCells: UInt = count(matcher: matcher)
GREYAssert(countOfTableViewCells > 1, reason: "There are more than one cell present.")
EarlGrey.selectElement(with: matcher)
.atIndex(countOfTableViewCells + 1)
.assert(grey_notNil(), error: &error)
let errorCode: GREYInteractionErrorCode =
GREYInteractionErrorCode.matchedElementIndexOutOfBoundsErrorCode
let errorReason: String = "The Interaction element's index being used was over the count " +
"of matched elements available."
GREYAssert(error?.code == errorCode.rawValue, reason:errorReason)
}
}
func count(matcher: GREYMatcher!) -> UInt {
var error: NSError? = nil
var index: UInt = 0
let countMatcher: GREYElementMatcherBlock =
GREYElementMatcherBlock.matcher(matchesBlock: { (element: Any) -> Bool in
if (matcher.matches(element)) {
index = index + 1;
}
return false;
}) { (description: AnyObject?) in
let greyDescription:GREYDescription = description as! GREYDescription
greyDescription.appendText("Count of Matcher")
}
EarlGrey.selectElement(with: countMatcher)
.assert(grey_notNil(), error: &error);
return index
}
|
apache-2.0
|
9fbb681f7c15d3eaa80a9869a635ff93
| 36.797297 | 96 | 0.703253 | 4.460925 | false | true | false | false |
firebase/friendlyeats-ios
|
FriendlyEats/FiltersViewController.swift
|
1
|
6188
|
//
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class FiltersViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
weak var delegate: FiltersViewControllerDelegate?
static func fromStoryboard(delegate: FiltersViewControllerDelegate? = nil) ->
(navigationController: UINavigationController, filtersController: FiltersViewController) {
let navController = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "FiltersViewController")
as! UINavigationController
let controller = navController.viewControllers[0] as! FiltersViewController
controller.delegate = delegate
return (navigationController: navController, filtersController: controller)
}
@IBOutlet var categoryTextField: UITextField! {
didSet {
categoryTextField.inputView = categoryPickerView
}
}
@IBOutlet var cityTextField: UITextField! {
didSet {
cityTextField.inputView = cityPickerView
}
}
@IBOutlet var priceTextField: UITextField! {
didSet {
priceTextField.inputView = pricePickerView
}
}
@IBOutlet var sortByTextField: UITextField! {
didSet {
sortByTextField.inputView = sortByPickerView
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Blue bar with white color
navigationController?.navigationBar.barTintColor =
UIColor(red: 0x3d/0xff, green: 0x5a/0xff, blue: 0xfe/0xff, alpha: 1.0)
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.titleTextAttributes =
convertToOptionalNSAttributedStringKeyDictionary([ NSAttributedString.Key.foregroundColor.rawValue: UIColor.white ])
}
private func price(from string: String) -> Int? {
switch string {
case "$":
return 1
case "$$":
return 2
case "$$$":
return 3
case _:
return nil
}
}
@IBAction func didTapDoneButton(_ sender: Any) {
let price = priceTextField.text.flatMap { self.price(from: $0) }
delegate?.controller(self, didSelectCategory: categoryTextField.text,
city: cityTextField.text, price: price, sortBy: sortByTextField.text)
navigationController?.dismiss(animated: true, completion: nil)
}
@IBAction func didTapCancelButton(_ sender: Any) {
navigationController?.dismiss(animated: true, completion: nil)
}
func clearFilters() {
categoryTextField.text = ""
cityTextField.text = ""
priceTextField.text = ""
sortByTextField.text = ""
}
private lazy var sortByPickerView: UIPickerView = {
let pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
return pickerView
}()
private lazy var pricePickerView: UIPickerView = {
let pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
return pickerView
}()
private lazy var cityPickerView: UIPickerView = {
let pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
return pickerView
}()
private lazy var categoryPickerView: UIPickerView = {
let pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
return pickerView
}()
private let sortByOptions = ["name", "category", "city", "price", "avgRating"]
private let priceOptions = ["$", "$$", "$$$"]
private let cityOptions = Restaurant.cities
private let categoryOptions = Restaurant.categories
// MARK: UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch pickerView {
case sortByPickerView:
return sortByOptions.count
case pricePickerView:
return priceOptions.count
case cityPickerView:
return cityOptions.count
case categoryPickerView:
return categoryOptions.count
case _:
fatalError("Unhandled picker view: \(pickerView)")
}
}
// MARK: - UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent: Int) -> String? {
switch pickerView {
case sortByPickerView:
return sortByOptions[row]
case pricePickerView:
return priceOptions[row]
case cityPickerView:
return cityOptions[row]
case categoryPickerView:
return categoryOptions[row]
case _:
fatalError("Unhandled picker view: \(pickerView)")
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch pickerView {
case sortByPickerView:
sortByTextField.text = sortByOptions[row]
case pricePickerView:
priceTextField.text = priceOptions[row]
case cityPickerView:
cityTextField.text = cityOptions[row]
case categoryPickerView:
categoryTextField.text = categoryOptions[row]
case _:
fatalError("Unhandled picker view: \(pickerView)")
}
}
}
protocol FiltersViewControllerDelegate: NSObjectProtocol {
func controller(_ controller: FiltersViewController,
didSelectCategory category: String?,
city: String?, price: Int?, sortBy: String?)
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
|
apache-2.0
|
74b56333cea782f05c476ba2f23eafb1
| 29.94 | 126 | 0.708468 | 4.915012 | false | false | false | false |
lacklock/ReactiveCocoaExtension
|
Pods/ReactiveSwift/Sources/Atomic.swift
|
1
|
7700
|
//
// Atomic.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-10.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import MachO
#endif
/// Represents a finite state machine that can transit from one state to
/// another.
internal protocol AtomicStateProtocol {
associatedtype State: RawRepresentable
/// Try to transit from the expected current state to the specified next
/// state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the transition succeeds. `false` otherwise.
func tryTransiting(from expected: State, to next: State) -> Bool
}
/// A simple, generic lock-free finite state machine.
///
/// - warning: `deinitialize` must be called to dispose of the consumed memory.
internal struct UnsafeAtomicState<State: RawRepresentable>: AtomicStateProtocol where State.RawValue == Int32 {
internal typealias Transition = (expected: State, next: State)
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
private let value: UnsafeMutablePointer<Int32>
/// Create a finite state machine with the specified initial state.
///
/// - parameters:
/// - initial: The desired initial state.
internal init(_ initial: State) {
value = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
value.initialize(to: initial.rawValue)
}
/// Deinitialize the finite state machine.
internal func deinitialize() {
value.deinitialize()
value.deallocate(capacity: 1)
}
/// Compare the current state with the specified state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the current state matches the expected state. `false`
/// otherwise.
@inline(__always)
internal func `is`(_ expected: State) -> Bool {
return OSAtomicCompareAndSwap32Barrier(expected.rawValue,
expected.rawValue,
value)
}
/// Try to transit from the expected current state to the specified next
/// state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the transition succeeds. `false` otherwise.
@inline(__always)
internal func tryTransiting(from expected: State, to next: State) -> Bool {
return OSAtomicCompareAndSwap32Barrier(expected.rawValue,
next.rawValue,
value)
}
#else
private let value: Atomic<Int32>
/// Create a finite state machine with the specified initial state.
///
/// - parameters:
/// - initial: The desired initial state.
internal init(_ initial: State) {
value = Atomic(initial.rawValue)
}
/// Deinitialize the finite state machine.
internal func deinitialize() {}
/// Compare the current state with the specified state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the current state matches the expected state. `false`
/// otherwise.
internal func `is`(_ expected: State) -> Bool {
return value.modify { $0 == expected.rawValue }
}
/// Try to transit from the expected current state to the specified next
/// state.
///
/// - parameters:
/// - expected: The expected state.
///
/// - returns:
/// `true` if the transition succeeds. `false` otherwise.
internal func tryTransiting(from expected: State, to next: State) -> Bool {
return value.modify { value in
if value == expected.rawValue {
value = next.rawValue
return true
}
return false
}
}
#endif
}
final class PosixThreadMutex: NSLocking {
private var mutex = pthread_mutex_t()
init() {
let result = pthread_mutex_init(&mutex, nil)
precondition(result == 0, "Failed to initialize mutex with error \(result).")
}
deinit {
let result = pthread_mutex_destroy(&mutex)
precondition(result == 0, "Failed to destroy mutex with error \(result).")
}
func lock() {
let result = pthread_mutex_lock(&mutex)
precondition(result == 0, "Failed to lock \(self) with error \(result).")
}
func unlock() {
let result = pthread_mutex_unlock(&mutex)
precondition(result == 0, "Failed to unlock \(self) with error \(result).")
}
}
/// An atomic variable.
public final class Atomic<Value>: AtomicProtocol {
private let lock: PosixThreadMutex
private var _value: Value
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
public init(_ value: Value) {
_value = value
lock = PosixThreadMutex()
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
/// An atomic variable which uses a recursive lock.
internal final class RecursiveAtomic<Value>: AtomicProtocol {
private let lock: NSRecursiveLock
private var _value: Value
private let didSetObserver: ((Value) -> Void)?
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
/// - name: An optional name used to create the recursive lock.
/// - action: An optional closure which would be invoked every time the
/// value of `self` is mutated.
internal init(_ value: Value, name: StaticString? = nil, didSet action: ((Value) -> Void)? = nil) {
_value = value
lock = NSRecursiveLock()
lock.name = name.map(String.init(describing:))
didSetObserver = action
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer {
didSetObserver?(_value)
lock.unlock()
}
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
public protocol AtomicProtocol: class {
associatedtype Value
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result
}
extension AtomicProtocol {
/// Atomically get or set the value of the variable.
public var value: Value {
get {
return withValue { $0 }
}
set(newValue) {
swap(newValue)
}
}
/// Atomically replace the contents of the variable.
///
/// - parameters:
/// - newValue: A new value for the variable.
///
/// - returns: The old value.
@discardableResult
public func swap(_ newValue: Value) -> Value {
return modify { (value: inout Value) in
let oldValue = value
value = newValue
return oldValue
}
}
}
|
mit
|
0ded1f3104cca9f65ba229fe1154d26c
| 25.923077 | 111 | 0.66013 | 3.67893 | false | false | false | false |
CoderST/DYZB
|
DYZB/DYZB/Class/Profile/Controller/WatchHistoryViewController.swift
|
1
|
3430
|
//
// WatchHistoryViewController.swift
// DYZB
//
// Created by xiudou on 2017/6/22.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
import SVProgressHUD
let WatchHistoryItemHeight : CGFloat = 120
fileprivate let watchHistoryIdentifier = "watchHistoryIdentifier"
class WatchHistoryViewController: BaseViewController {
fileprivate lazy var watchHistoryVM : WatchHistoryVM = WatchHistoryVM()
// 展示主界面的collectionView
fileprivate lazy var collectionView : UICollectionView = {
// 设置layout属性
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: sScreenW, height: WatchHistoryItemHeight)
// layout.headerReferenceSize = CGSize(width: sScreenW, height: sHeadHeight)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
// layout.sectionInset = UIEdgeInsets(top: 0, left: sEdgeMargin, bottom: 0, right: sEdgeMargin)
// 创建UICollectionView
let collectionView = UICollectionView(frame: CGRect(x: 0, y: sStatusBarH + sNavatationBarH, width: sScreenW, height: sScreenH - sStatusBarH - sNavatationBarH), collectionViewLayout: layout)
// 设置数据源
collectionView.dataSource = self
// collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
// 注册cell
collectionView.register(WatchHistoryCell.self, forCellWithReuseIdentifier: watchHistoryIdentifier)
return collectionView;
}()
override func viewDidLoad() {
baseContentView = collectionView
super.viewDidLoad()
title = "观看历史"
view.addSubview(collectionView)
setupNavigationBar()
setupData()
}
}
extension WatchHistoryViewController{
fileprivate func setupNavigationBar(){
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "清除", style: .done, target: self, action: #selector(clearHistoryAction))
}
func clearHistoryAction(){
watchHistoryVM.clearHistory {
self.collectionView.reloadData()
SVProgressHUD.showSuccess(withStatus: "清楚成功")
}
}
fileprivate func setupData(){
watchHistoryVM.loadWatchHistoryDatas({
self.collectionView.reloadData()
self.endAnimation()
}, { (message) in
SVProgressHUD.showError(withStatus: message)
}) {
}
}
}
extension WatchHistoryViewController : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return watchHistoryVM.watchHistoryModelFrameArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: watchHistoryIdentifier, for: indexPath) as! WatchHistoryCell
// cell.gameCenterModel = watchHistoryVM.watchHistoryModelArray[indexPath.item]
let watchHistoryModelFrame = watchHistoryVM.watchHistoryModelFrameArray[indexPath.item]
cell.watchHistoryModelFrame = watchHistoryModelFrame
// cell.contentView.backgroundColor = UIColor.randomColor()
return cell
}
}
|
mit
|
0450b1f43590e961b01806f767f8a0cf
| 33.377551 | 197 | 0.683882 | 5.486971 | false | false | false | false |
damoyan/BYRClient
|
FromScratch/Model/APIManager.swift
|
1
|
3668
|
//
// APIManager.swift
// FromScratch
//
// Created by Yu Pengyang on 10/26/15.
// Copyright (c) 2015 Yu Pengyang. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
// Known BYR Errors
//let needParameter = (code: "1701", msg: "请求参数错误或丢失")
// code: 1702, msg: "非法的 oauth_token"
let BYRErrorDomain = "BYRErrorDomain"
let ErrorInvalidToken = 1702 //msg: "非法的 oauth_token"
let ErrorTokenExpired = 1703
enum API: URLRequestConvertible {
case Sections
case Section(name: String)
case Favorite(level: Int)
case Board(name: String, mode: BoardMode?, perPage: Int?, page: Int?)
case TopTen
case Thread(name: String, id: Int, uid: String?, perPage: Int?, page: Int?)
var URLRequest: NSMutableURLRequest {
var v = generateURLComponents()
if v.params == nil {
v.params = [String: AnyObject]()
}
v.params!["oauth_token"] = "\(AppSharedInfo.sharedInstance.userToken!)"
let request = NSMutableURLRequest(URL: baseURL.URLByAppendingPathComponent(v.path))
request.HTTPMethod = v.method.rawValue
return Alamofire.ParameterEncoding.URL.encode(request, parameters: v.params!).0
}
func handleResponse(callback: (NSURLRequest?, NSHTTPURLResponse?, JSON?, NSError?) -> ()) -> Request {
return request(URLRequest).responseJSON { (res) -> Void in
guard let json = res.result.value else {
callback(res.request, res.response, nil, res.result.error)
return
}
let sj = JSON(json)
// if the request is Successful, there will be no 'code' & 'msg' key in returned JSON.
// when we access 'code' or 'msg' key, there should be an error,
// so sj["code"].error & sj["msg"].error are not `nil`
guard sj["code"].error != nil && sj["msg"].error != nil else {
if sj["code"].intValue == ErrorInvalidToken || sj["code"].intValue == ErrorTokenExpired {
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.InvalidToken, object: nil)
} else {
callback(res.request, res.response, nil, NSError(domain: BYRErrorDomain, code: sj["code"].intValue, userInfo: [NSLocalizedDescriptionKey: sj["msg"].stringValue]))
}
return
}
callback(res.request, res.response, sj, nil)
}
}
private func generateURLComponents() -> (method: Alamofire.Method, path: String, params: [String: AnyObject]?) {
switch self {
case Sections:
return (.GET, "/section.json", nil)
case Section(let name):
return (.GET, "/section/\(name).json", nil)
case .Favorite(let level):
return (.GET, "/favorite/\(level).json", nil)
case .TopTen:
return (.GET, "/widget/topten.json", nil)
case .Board(let name, let mode, let perPage, let page):
return (.GET, "/board/\(name).json", API.filterParams(["mode": mode?.rawValue, "count": perPage, "page": page]))
case .Thread(let name, let id, let uid, let perPage, let page):
return (.GET, "/threads/\(name)/\(id).json", API.filterParams(["au": uid, "count": perPage, "page": page]))
}
}
static func filterParams(input: [String: AnyObject?]) -> [String: AnyObject] {
return input.flatMap { $0.1 == nil ? nil : ($0.0, $0.1!)}.reduce([String: AnyObject]()) {
var ret = $0
ret[$1.0] = $1.1
return ret
}
}
}
|
mit
|
91ed8ee36359d45f7d2368f1de94ff3f
| 38.989011 | 182 | 0.587136 | 4.138794 | false | false | false | false |
imod/HelloWorld
|
HelloWorld/SearchResultsViewController.swift
|
1
|
2019
|
//
// SearchResultsViewController.swift
// HelloWorld
//
// Created by Dominik on 08/06/14.
// Copyright (c) 2014 Dominik. All rights reserved.
//
import UIKit
class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIContollerProtocol {
@IBOutlet var appsTableView : UITableView
var data: NSMutableData = NSMutableData()
var tableData: NSArray = NSArray()
var api: APIController?
override func viewDidLoad() {
super.viewDidLoad()
api = APIController(delegate: self)
api!.searchItunesFor("Angry Birds")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// UITableViewDataSource
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
return tableData.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
cell.text = rowData["trackName"] as String
var urlString: NSString = rowData["artworkUrl60"] as NSString
var imgURL: NSURL = NSURL(string: urlString)
// get the image
var imgData: NSData = NSData(contentsOfURL: imgURL)
cell.image = UIImage(data: imgData)
var formattedPrice: NSString = rowData["formattedPrice"] as NSString
cell.detailTextLabel.text = formattedPrice
return cell
}
func didReceiveAPIResults(results: NSDictionary){
if results.count>0 {
self.tableData = results["results"] as NSArray
self.appsTableView.reloadData()
}
}
}
|
mit
|
df196998013c6384bfdeb2e454259347
| 28.26087 | 120 | 0.645864 | 5.577348 | false | false | false | false |
bindlechat/ZenText
|
ZenText/Classes/NSMutableAttributedString+Additions.swift
|
1
|
3427
|
import Foundation
public extension NSMutableAttributedString {
// Add style
public func addStyle(named styleName: String, regex: String) -> [NSTextCheckingResult]? {
let style = Style()
for styleName in ZenText.manager.styleNamesFromStyleString(styleName) {
if let s = ZenText.manager.config.styles?(styleName) {
style.append(s)
}
}
return addStyle(style, regex: regex)
}
public func addStyle(_ style: Style, regex: String, tokenized: Bool = true) -> [NSTextCheckingResult]? {
return self.style(style, regex: regex, tokenized: tokenized, replace: false)
}
public func setStyle(named styleName: String, regex: String, tokenized: Bool = true) -> [NSTextCheckingResult]? {
let style = Style()
for styleName in ZenText.manager.styleNamesFromStyleString(styleName) {
if let s = ZenText.manager.config.styles?(styleName) {
style.append(s)
}
}
return self.setStyle(style, regex: regex, tokenized: tokenized)
}
public func setStyle(_ style: Style, regex: String, tokenized: Bool = true) -> [NSTextCheckingResult]? {
return self.style(style, regex: regex, tokenized: tokenized, replace: true)
}
public func style(_ style: Style, regex: String, tokenized: Bool = true) -> [NSTextCheckingResult]? {
return self.style(style, regex: regex, tokenized: tokenized, replace: true)
}
// Set (replace) style
public func setStyle(named styleName: String, dataDetector: NSDataDetector, tokenized: Bool = true, replace: Bool = true) -> [NSTextCheckingResult]? {
let matches = dataDetector.matches(in: string, options: [], range: NSRange(location: 0, length: string.count))
let style = Style()
for styleName in ZenText.manager.styleNamesFromStyleString(styleName) {
if let s = ZenText.manager.config.styles?(styleName) {
style.append(s)
}
}
return self.style(style, matches: matches, tokenized: tokenized, replace: replace)
}
fileprivate func style(_ style: Style, matches: [NSTextCheckingResult], tokenized: Bool, replace: Bool) -> [NSTextCheckingResult]? {
for match in matches {
let range = (tokenized ? match.range(at: match.numberOfRanges-1) : match.range)
let attributes = ZenText.manager.attributesForStyle(style)
if replace {
self.setAttributes(attributes, range: range)
} else if let attributes = attributes {
self.addAttributes(attributes, range: range)
}
}
return matches
}
// MARK: - Private
fileprivate func style(_ style: Style, regex: String, tokenized: Bool, replace: Bool) -> [NSTextCheckingResult]? {
do {
let regularExpression = try NSRegularExpression(pattern: regex, options: NSRegularExpression.Options(rawValue: 0))
let range = NSRange(location: 0, length: self.length)
let matches = regularExpression.matches(in: self.string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range)
return self.style(style, matches: matches, tokenized: tokenized, replace: replace)
} catch _ {
}
return nil
}
}
|
mit
|
55d8f8709e6f8f07c74e0c2ffa4edc05
| 42.935897 | 154 | 0.623577 | 4.733425 | false | false | false | false |
mb2dev/BarnaBot
|
Barnabot/BBDialog.swift
|
1
|
2196
|
//
// BBDialog.swift
// MyBarnabot
//
// Created by VAUTRIN on 05/02/2017.
// Copyright © 2017 gabrielvv. All rights reserved.
//
import Foundation
/// Inspired by thread states
enum DialogState {
case pending
case new
case running
case terminated
}
//https://developer.apple.com/reference/swift/equatable
class BBDialog : Equatable {
let id : UUID
var counter : Int = 0
var state : DialogState {
get {
if(self.counter-1 >= waterfall.count){
return .terminated
}else if(self.counter == 0){
return .new
}else{
return .running
}
}
}
var waterfall : [BBNext]
// Pour pouvoir faire des comparaisons entre plusieurs instances de BBDialog
let path : String
var next : BBNext? {
get {
//print("next getter with counter = \(counter)")
counter += 1
return self.state == .terminated ? nil : waterfall[counter-1]
}
}
var beginDialog : BBNext {
get {
//print("beginDialog getter with counter = \(counter)")
return self.state == .running || self.state == .terminated ? waterfall[counter-1] : self.next!
}
}
func resume(_ session : BBSession){
if let next = self.next {
next(session)
}
}
convenience init(_ path : String, action : @escaping BBNext) {
self.init(path, waterfall: [BBNext]())
self.waterfall.append(action);
}
init(_ path : String, waterfall : [BBNext]){
// should force waterfall to have at least one element
self.path = path
self.waterfall = waterfall
self.id = UUID()
}
public var description: String{
var result = ""
result.append("BBDialog \n")
result.append("- steps : \(self.waterfall.count)")
return result
}
static func == (lhs: BBDialog, rhs: BBDialog) -> Bool {
//print("BBDialog comparison")
return lhs.path == rhs.path
}
func copy() -> BBDialog {
return BBDialog(path, waterfall : waterfall)
}
}
|
bsd-3-clause
|
6b7fef57a9bfca38d5f44b050f0ac319
| 24.523256 | 106 | 0.551708 | 4.064815 | false | false | false | false |
ProximityViz/Double-Take-3D
|
iOS/Double Take 3D/ShootVC.swift
|
1
|
3271
|
//
// ShootVC.swift
// Double Take 3D
//
// Created by Shawn on 9/17/15.
// Copyright © 2015 Proximity Viz LLC. All rights reserved.
//
import UIKit
import Photos
import Parse
import Bolts
class ShootVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagePicker = NonRotatingUIImagePickerController()
var imageBeingPicked = "left"
// NOTE: photos might only stay for 30 days if using iCloud
var leftImageLocation = ""
var rightImageLocation = ""
@IBOutlet weak var leftImageView: UIImageView!
@IBOutlet weak var rightImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
}
@IBAction func leftImageTapped(sender: AnyObject) {
imageBeingPicked = "left"
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func rightImageTapped(sender: AnyObject) {
imageBeingPicked = "right"
presentViewController(imagePicker, animated: true, completion: nil)
}
func saveImage(image: UIImage, position: String) {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
PHAssetChangeRequest.creationRequestForAssetFromImage(image)
}) { (success, error) -> Void in
if success {
print("Success")
if position == "left" {
} else if position == "right" {
}
} else {
print(error)
}
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if imageBeingPicked == "left" {
let leftImage = info[UIImagePickerControllerOriginalImage] as! UIImage
leftImageView.image = leftImage
// save image to camera roll
saveImage(leftImage, position: imageBeingPicked)
} else if imageBeingPicked == "right" {
let rightImage = info[UIImagePickerControllerOriginalImage] as! UIImage
rightImageView.image = rightImage
saveImage(rightImage, position: imageBeingPicked)
}
imagePicker.dismissViewControllerAnimated(true, completion: nil)
}
func saveToParse() {
let threeDPhoto = PFObject(className: "ThreeDPhoto")
// threeDPhoto["left"] = leftImageView.image
// threeDPhoto["right"] = rightImageView.image
threeDPhoto["user"] = "Shawn"
threeDPhoto.saveInBackgroundWithBlock { (success, error) -> Void in
if success == true {
print("save to parse successful")
} else {
print("failed to save to parse")
print(error)
}
}
}
@IBAction func saveButtonTapped(sender: AnyObject) {
// segue
// save image URLs
saveToParse()
leftImageView.image = nil
rightImageView.image = nil
}
}
|
mit
|
9232e5a60095f08d70b0e9deb6571a77
| 29 | 123 | 0.58318 | 5.523649 | false | false | false | false |
wltrup/Swift-WTUniquePrimitiveType
|
WTUniquePrimitiveType/Classes/WTUniquePrimitiveType.swift
|
1
|
1295
|
//
// WTUniquePrimitiveType.swift
// WTUniquePrimitiveTypes
//
// Created by Wagner Truppel on 31/05/2017.
// Copyright © 2017 wtruppel. All rights reserved.
//
// swiftlint:disable vertical_whitespace
// swiftlint:disable trailing_newline
import Foundation
public protocol WTUniquePrimitiveType: CustomStringConvertible, Equatable, Comparable, Hashable {
associatedtype PrimitiveType: CustomStringConvertible, Equatable, Comparable, Hashable
var value: PrimitiveType { get }
init(_ value: PrimitiveType)
}
// MARK: - CustomStringConvertible
extension WTUniquePrimitiveType {
public var description: String {
return "\(value.description)"
}
}
// MARK: - Equatable
extension WTUniquePrimitiveType {
public static func == <T: WTUniquePrimitiveType>(lhs: Self, rhs: T) -> Bool
where T.PrimitiveType == Self.PrimitiveType {
return lhs.value == rhs.value
}
}
// MARK: - Comparable
extension WTUniquePrimitiveType {
public static func < <T: WTUniquePrimitiveType>(lhs: Self, rhs: T) -> Bool
where T.PrimitiveType == Self.PrimitiveType {
return lhs.value < rhs.value
}
}
// MARK: - Hashable
extension WTUniquePrimitiveType {
public var hashValue: Int {
return value.hashValue
}
}
|
mit
|
24cdf434cbf936312dd665a91203f0e3
| 21.310345 | 97 | 0.698609 | 4.342282 | false | false | false | false |
KaushalElsewhere/AllHandsOn
|
KeyboardObserverTry/KeyboardObserverTry/Box/BoxType.swift
|
1
|
1245
|
// Copyright (c) 2014 Rob Rix. All rights reserved.
// MARK: BoxType
/// The type conformed to by all boxes.
public protocol BoxType {
/// The type of the wrapped value.
associatedtype Value
/// Initializes an intance of the type with a value.
init(_ value: Value)
/// The wrapped value.
var value: Value { get }
}
/// The type conformed to by mutable boxes.
public protocol MutableBoxType: BoxType {
/// The (mutable) wrapped value.
var value: Value { get set }
}
// MARK: Equality
/// Equality of `BoxType`s of `Equatable` types.
///
/// We cannot declare that e.g. `Box<T: Equatable>` conforms to `Equatable`, so this is a relatively ad hoc definition.
public func == <B: BoxType where B.Value: Equatable> (lhs: B, rhs: B) -> Bool {
return lhs.value == rhs.value
}
/// Inequality of `BoxType`s of `Equatable` types.
///
/// We cannot declare that e.g. `Box<T: Equatable>` conforms to `Equatable`, so this is a relatively ad hoc definition.
public func != <B: BoxType where B.Value: Equatable> (lhs: B, rhs: B) -> Bool {
return lhs.value != rhs.value
}
// MARK: Map
/// Maps the value of a box into a new box.
public func map<B: BoxType, C: BoxType>(v: B, @noescape f: B.Value -> C.Value) -> C {
return C(f(v.value))
}
|
mit
|
cd959bb2409979ca7da4694e903c9d09
| 26.065217 | 119 | 0.670683 | 3.28496 | false | false | false | false |
LipliStyle/Liplis-iOS
|
Liplis/LiplisKeyManager.swift
|
1
|
3622
|
//
// JsonListManager.swift
// Liplis
//
// Liplisウィジェットの保存キーの管理を行うクラス
//
//アップデート履歴
// 2015/04/27 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
// 2015/05/16 ver1.4.0 リファクタリング
//
// Created by sachin on 2015/04/27.
// Copyright (c) 2015年 sachin. All rights reserved.
//
//格納JSON
// {"keylist":["key1","key2","key3"]}
import Foundation
class LiplisKeyManager : ObjPreferenceBase
{
///=============================
/// キーリスト
internal var keyList : Array<String> = []
///=============================
/// 書き込みキー
internal let JSON_KEY = "keylist"
/**
コンストラクター
*/
internal override init()
{
//親の初期化
super.init()
//復活させる
self.getKeyList()
}
/**
キーを追加する
*/
internal func addKey(key : String)
{
var flgHit : Bool = false
//キーの存在チェック
for str in self.keyList
{
if str == key
{
flgHit = true
}
}
//該当キーがなければ追加する
if !flgHit
{
self.keyList.append(key)
self.saveKeyList()
}
}
/**
キーを削除する
*/
internal func delKey(pKey : String)
{
var idx : Int = 0
for key in self.keyList
{
if(key == pKey)
{
self.keyList.removeAtIndex(idx)
self.saveKeyList()
return
}
idx++
}
}
/**
キーを削除する
*/
internal func delAllKey()
{
self.keyList.removeAll(keepCapacity: false)
self.saveKeyList()
}
/**
キーリストを保存する
*/
internal func saveKeyList()
{
let jsonStr : StringBuilder = StringBuilder()
//開始かっこ
jsonStr.append("{\"")
jsonStr.append(JSON_KEY)
jsonStr.append("\":[")
if self.keyList.count >= 2
{
//最後の1個以外全部入れる
for idx in 0...keyList.count-2
{
jsonStr.append("\"" + self.keyList[idx] + "\",")
}
//最後の1個を入れる
jsonStr.append("\"" + self.keyList[keyList.count-1] + "\"")
}
else if keyList.count == 1
{
//要素が1個の場合
jsonStr.append("\"" + self.keyList[0] + "\"")
}
else
{
//要素0の場合何もしない
}
//とじかっこ
jsonStr.append("]}")
//JSONを保存する
wirtePreference(JSON_KEY, value: jsonStr.toString())
}
/**
キーリストをプリファレンスから復元し、取得する
*/
internal func getKeyList()
{
//キーリストの初期化
keyList = []
//キーリストの取得
var json : JSON = getJsonFromString(getSetting(JSON_KEY, defaultValue: ""))
print(json[JSON_KEY], terminator: "" )
//ヌルチェック
if json[JSON_KEY] != nil
{
//回して復元
for (_, subJson): (String, JSON) in json[JSON_KEY]
{
self.keyList.append(subJson.description)
}
}
}
}
|
mit
|
31817ca3690fba8e4fc65b335006212f
| 18.76875 | 83 | 0.43327 | 3.755344 | false | false | false | false |
yonat/MultiSlider
|
Sources/MultiSliderExtensions.swift
|
1
|
7482
|
//
// MultiSliderExtensions.swift
// MultiSlider
//
// Created by Yonat Sharon on 20.05.2018.
//
import SweeterSwift
import UIKit
extension CGFloat {
func truncated(_ step: CGFloat) -> CGFloat {
return step.isNormal ? self - remainder(dividingBy: step) : self
}
func rounded(_ step: CGFloat) -> CGFloat {
guard step.isNormal && isNormal else { return self }
return (self / step).rounded() * step
}
}
extension CGPoint {
func coordinate(in axis: NSLayoutConstraint.Axis) -> CGFloat {
switch axis {
case .vertical:
return y
default:
return x
}
}
}
extension CGRect {
func size(in axis: NSLayoutConstraint.Axis) -> CGFloat {
switch axis {
case .vertical:
return height
default:
return width
}
}
func bottom(in axis: NSLayoutConstraint.Axis) -> CGFloat {
switch axis {
case .vertical:
return maxY
default:
return minX
}
}
func top(in axis: NSLayoutConstraint.Axis) -> CGFloat {
switch axis {
case .vertical:
return minY
default:
return maxX
}
}
}
extension UIView {
var diagonalSize: CGFloat { return hypot(frame.width, frame.height) }
func removeFirstConstraint(where: (_: NSLayoutConstraint) -> Bool) {
if let constrainIndex = constraints.firstIndex(where: `where`) {
removeConstraint(constraints[constrainIndex])
}
}
func addShadow() {
layer.shadowColor = UIColor.gray.cgColor
layer.shadowOpacity = 0.25
layer.shadowOffset = CGSize(width: 0, height: 4)
layer.shadowRadius = 0.5
}
}
extension Array where Element: UIView {
mutating func removeViewsStartingAt(_ index: Int) {
guard index >= 0 && index < count else { return }
self[index ..< count].forEach { $0.removeFromSuperview() }
removeLast(count - index)
}
}
extension UIImageView {
func applyTint(color: UIColor?) {
image = image?.withRenderingMode(nil == color ? .alwaysOriginal : .alwaysTemplate)
tintColor = color
}
func blur(_ on: Bool) {
if on {
guard nil == viewWithTag(UIImageView.blurViewTag) else { return }
let blurImage = image?.withRenderingMode(.alwaysTemplate)
let blurView = UIImageView(image: blurImage)
blurView.tag = UIImageView.blurViewTag
blurView.tintColor = .white
blurView.alpha = 0.5
addConstrainedSubview(blurView, constrain: .top, .bottom, .left, .right)
layer.shadowOpacity /= 2
} else {
guard let blurView = viewWithTag(UIImageView.blurViewTag) else { return }
blurView.removeFromSuperview()
layer.shadowOpacity *= 2
}
}
static var blurViewTag: Int { return 898_989 } // swiftlint:disable:this numbers_smell
}
extension NSLayoutConstraint.Attribute {
var opposite: NSLayoutConstraint.Attribute {
switch self {
case .left: return .right
case .right: return .left
case .top: return .bottom
case .bottom: return .top
case .leading: return .trailing
case .trailing: return .leading
case .leftMargin: return .rightMargin
case .rightMargin: return .leftMargin
case .topMargin: return .bottomMargin
case .bottomMargin: return .topMargin
case .leadingMargin: return .trailingMargin
case .trailingMargin: return .leadingMargin
default: return self
}
}
var inwardSign: CGFloat {
switch self {
case .top, .topMargin: return 1
case .bottom, .bottomMargin: return -1
case .left, .leading, .leftMargin, .leadingMargin: return 1
case .right, .trailing, .rightMargin, .trailingMargin: return -1
default: return 1
}
}
var perpendicularCenter: NSLayoutConstraint.Attribute {
switch self {
case .left, .leading, .leftMargin, .leadingMargin, .right, .trailing, .rightMargin, .trailingMargin, .centerX:
return .centerY
default:
return .centerX
}
}
static func center(in axis: NSLayoutConstraint.Axis) -> NSLayoutConstraint.Attribute {
switch axis {
case .vertical:
return .centerY
default:
return .centerX
}
}
static func top(in axis: NSLayoutConstraint.Axis) -> NSLayoutConstraint.Attribute {
switch axis {
case .vertical:
return .top
default:
return .right
}
}
static func bottom(in axis: NSLayoutConstraint.Axis) -> NSLayoutConstraint.Attribute {
switch axis {
case .vertical:
return .bottom
default:
return .left
}
}
}
extension CACornerMask {
static func direction(_ attribute: NSLayoutConstraint.Attribute) -> CACornerMask {
switch attribute {
case .bottom:
return [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
case .top:
return [.layerMinXMinYCorner, .layerMaxXMinYCorner]
case .leading, .left:
return [.layerMinXMinYCorner, .layerMinXMaxYCorner]
case .trailing, .right:
return [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
default:
return []
}
}
}
extension UIImage {
static func circle(diameter: CGFloat = 29, width: CGFloat = 0.5, color: UIColor? = UIColor.lightGray.withAlphaComponent(0.5), fill: UIColor? = .white) -> UIImage? {
let circleLayer = CAShapeLayer()
circleLayer.fillColor = fill?.cgColor
circleLayer.strokeColor = color?.cgColor
circleLayer.lineWidth = width
let margin = width * 2
let circle = UIBezierPath(ovalIn: CGRect(x: margin, y: margin, width: diameter, height: diameter))
circleLayer.bounds = CGRect(x: 0, y: 0, width: diameter + margin * 2, height: diameter + margin * 2)
circleLayer.path = circle.cgPath
UIGraphicsBeginImageContextWithOptions(circleLayer.bounds.size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
circleLayer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension NSObject {
func addObserverForAllProperties(
observer: NSObject,
options: NSKeyValueObservingOptions = [],
context: UnsafeMutableRawPointer? = nil
) {
performForAllKeyPaths { keyPath in
addObserver(observer, forKeyPath: keyPath, options: options, context: context)
}
}
func removeObserverForAllProperties(
observer: NSObject,
context: UnsafeMutableRawPointer? = nil
) {
performForAllKeyPaths { keyPath in
removeObserver(observer, forKeyPath: keyPath, context: context)
}
}
func performForAllKeyPaths(_ action: (String) -> Void) {
var count: UInt32 = 0
guard let properties = class_copyPropertyList(object_getClass(self), &count) else { return }
defer { free(properties) }
for i in 0 ..< Int(count) {
let keyPath = String(cString: property_getName(properties[i]))
action(keyPath)
}
}
}
|
mit
|
98a822412e1fe1d32313e78c592b3e9e
| 29.663934 | 168 | 0.609329 | 4.887002 | false | false | false | false |
Mars182838/WJCycleScrollView
|
WJCycleScrollView/Extentions/NSDateExtensions.swift
|
2
|
4009
|
//
// NSDateExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension NSDate {
/// EZSE: Initializes NSDate from string and format
public convenience init?(fromString string: String, format: String) {
let formatter = NSDateFormatter()
formatter.dateFormat = format
if let date = formatter.dateFromString(string) {
self.init(timeInterval: 0, sinceDate: date)
} else {
self.init()
return nil
}
}
/// EZSE: Converts NSDate to String
public func toString(dateStyle dateStyle: NSDateFormatterStyle = .MediumStyle, timeStyle: NSDateFormatterStyle = .MediumStyle) -> String {
let formatter = NSDateFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
return formatter.stringFromDate(self)
}
/// EZSE: Converts NSDate to String, with format
public func toString(format format: String) -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(self)
}
/// EZSE: Calculates how many days passed from now to date
public func daysInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/86400)
return diff
}
/// EZSE: Calculates how many hours passed from now to date
public func hoursInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/3600)
return diff
}
/// EZSE: Calculates how many minutes passed from now to date
public func minutesInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff/60)
return diff
}
/// EZSE: Calculates how many seconds passed from now to date
public func secondsInBetweenDate(date: NSDate) -> Double {
var diff = self.timeIntervalSinceNow - date.timeIntervalSinceNow
diff = fabs(diff)
return diff
}
/// EZSE: Easy creation of time passed String. Can be Years, Months, days, hours, minutes or seconds
public func timePassed() -> String {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: self, toDate: date, options: [])
var str: String
if components.year >= 1 {
components.year == 1 ? (str = "year") : (str = "years")
return "\(components.year) \(str) ago"
} else if components.month >= 1 {
components.month == 1 ? (str = "month") : (str = "months")
return "\(components.month) \(str) ago"
} else if components.day >= 1 {
components.day == 1 ? (str = "day") : (str = "days")
return "\(components.day) \(str) ago"
} else if components.hour >= 1 {
components.hour == 1 ? (str = "hour") : (str = "hours")
return "\(components.hour) \(str) ago"
} else if components.minute >= 1 {
components.minute == 1 ? (str = "minute") : (str = "minutes")
return "\(components.minute) \(str) ago"
} else if components.second == 0 {
return "Just now"
} else {
return "\(components.second) seconds ago"
}
}
}
extension NSDate: Comparable {}
/// EZSE: Returns if dates are equal to each other
public func == (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
/// EZSE: Returns if one date is smaller than the other
public func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
public func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedDescending
}
|
mit
|
0680982c3c96ba6d94179d4155bb976a
| 35.779817 | 142 | 0.618858 | 4.509561 | false | false | false | false |
couchbase/couchbase-lite-ios
|
Swift/Defaults.swift
|
1
|
3487
|
//
// Defaults.swift
// CouchbaseLite
//
// Copyright (c) 2022-present Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// THIS IS AN AUTOGENERATED FILE, MANUAL CHANGES SHOULD BE EXPECTED TO
// BE OVERWRITTEN
import Foundation
public extension LogFileConfiguration {
/// [false] Plaintext is not used, and instead binary encoding is used in log files
static let defaultUsePlainText: Bool = kCBLDefaultLogFileUsePlainText.boolValue
/// [524288] 512 KiB for the size of a log file
static let defaultMaxSize: UInt64 = kCBLDefaultLogFileMaxSize
/// [1] 1 rotated file present (2 total, including the currently active log file)
static let defaultMaxRotateCount: Int = kCBLDefaultLogFileMaxRotateCount
}
public extension FullTextIndexConfiguration {
/// [false] Accents and ligatures are not ignored when indexing via full text search
static let defaultIgnoreAccents: Bool = kCBLDefaultFullTextIndexIgnoreAccents.boolValue
}
public extension ReplicatorConfiguration {
/// [ReplicatorType.pushAndPull] Perform bidirectional replication
static let defaultType: ReplicatorType = ReplicatorType.pushAndPull
/// [false] One-shot replication is used, and will stop once all initial changes are processed
static let defaultContinuous: Bool = kCBLDefaultReplicatorContinuous.boolValue
/// [false] Replication stops when an application enters background mode
static let defaultAllowReplicatingInBackground: Bool = kCBLDefaultReplicatorAllowReplicatingInBackground.boolValue
/// [300 seconds] A heartbeat messages is sent every 300 seconds to keep the connection alive
static let defaultHeartbeat: TimeInterval = kCBLDefaultReplicatorHeartbeat
/// [10] When replicator is not continuous, after 10 failed attempts give up on the replication
static let defaultMaxAttemptsSingleShot: UInt = kCBLDefaultReplicatorMaxAttemptsSingleShot
/// [UInt.max] When replicator is continuous, never give up unless explicitly stopped
static let defaultMaxAttemptsContinuous: UInt = kCBLDefaultReplicatorMaxAttemptsContinuous
/// [300 seconds] Max wait time between retry attempts in seconds
static let defaultMaxAttemptWaitTime: TimeInterval = kCBLDefaultReplicatorMaxAttemptWaitTime
/// [true] Purge documents when a user loses access
static let defaultEnableAutoPurge: Bool = kCBLDefaultReplicatorEnableAutoPurge.boolValue
}
#if COUCHBASE_ENTERPRISE
public extension URLEndpointListenerConfiguration {
/// [0] No port specified, the OS will assign one
static let defaultPort: UInt16 = kCBLDefaultListenerPort
/// [false] TLS is enabled on the connection
static let defaultDisableTls: Bool = kCBLDefaultListenerDisableTls.boolValue
/// [false] The listener will allow database writes
static let defaultReadOnly: Bool = kCBLDefaultListenerReadOnly.boolValue
/// [false] Delta sync is disabled for the listener
static let defaultEnableDeltaSync: Bool = kCBLDefaultListenerEnableDeltaSync.boolValue
}
#endif
|
apache-2.0
|
f2a0f5ca1c87c6ec8fa47e20aba76cf2
| 38.625 | 115 | 0.796673 | 4.31026 | false | false | false | false |
radazzouz/firefox-ios
|
Client/Frontend/Browser/FindInPageBar.swift
|
2
|
6451
|
/* 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
protocol FindInPageBarDelegate: class {
func findInPage(_ findInPage: FindInPageBar, didTextChange text: String)
func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String)
func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String)
func findInPageDidPressClose(_ findInPage: FindInPageBar)
}
private struct FindInPageUX {
static let ButtonColor = UIColor.black
static let MatchCountColor = UIColor.lightGray
static let MatchCountFont = UIConstants.DefaultChromeFont
static let SearchTextColor = UIColor(rgb: 0xe66000)
static let SearchTextFont = UIConstants.DefaultChromeFont
static let TopBorderColor = UIColor(rgb: 0xEEEEEE)
}
class FindInPageBar: UIView {
weak var delegate: FindInPageBarDelegate?
fileprivate let searchText = UITextField()
fileprivate let matchCountView = UILabel()
fileprivate let previousButton = UIButton()
fileprivate let nextButton = UIButton()
var currentResult = 0 {
didSet {
matchCountView.text = "\(currentResult)/\(totalResults)"
}
}
var totalResults = 0 {
didSet {
matchCountView.text = "\(currentResult)/\(totalResults)"
previousButton.isEnabled = totalResults > 1
nextButton.isEnabled = previousButton.isEnabled
}
}
var text: String? {
get {
return searchText.text
}
set {
searchText.text = newValue
SELdidTextChange(searchText)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
searchText.addTarget(self, action: #selector(FindInPageBar.SELdidTextChange(_:)), for: UIControlEvents.editingChanged)
searchText.textColor = FindInPageUX.SearchTextColor
searchText.font = FindInPageUX.SearchTextFont
searchText.autocapitalizationType = UITextAutocapitalizationType.none
searchText.autocorrectionType = UITextAutocorrectionType.no
searchText.inputAssistantItem.leadingBarButtonGroups = []
searchText.inputAssistantItem.trailingBarButtonGroups = []
searchText.enablesReturnKeyAutomatically = true
searchText.returnKeyType = .search
addSubview(searchText)
matchCountView.textColor = FindInPageUX.MatchCountColor
matchCountView.font = FindInPageUX.MatchCountFont
matchCountView.isHidden = true
addSubview(matchCountView)
previousButton.setImage(UIImage(named: "find_previous"), for: UIControlState())
previousButton.setTitleColor(FindInPageUX.ButtonColor, for: UIControlState())
previousButton.accessibilityLabel = NSLocalizedString("Previous in-page result", tableName: "FindInPage", comment: "Accessibility label for previous result button in Find in Page Toolbar.")
previousButton.addTarget(self, action: #selector(FindInPageBar.SELdidFindPrevious(_:)), for: UIControlEvents.touchUpInside)
addSubview(previousButton)
nextButton.setImage(UIImage(named: "find_next"), for: UIControlState())
nextButton.setTitleColor(FindInPageUX.ButtonColor, for: UIControlState())
nextButton.accessibilityLabel = NSLocalizedString("Next in-page result", tableName: "FindInPage", comment: "Accessibility label for next result button in Find in Page Toolbar.")
nextButton.addTarget(self, action: #selector(FindInPageBar.SELdidFindNext(_:)), for: UIControlEvents.touchUpInside)
addSubview(nextButton)
let closeButton = UIButton()
closeButton.setImage(UIImage(named: "find_close"), for: UIControlState())
closeButton.setTitleColor(FindInPageUX.ButtonColor, for: UIControlState())
closeButton.accessibilityLabel = NSLocalizedString("Done", tableName: "FindInPage", comment: "Done button in Find in Page Toolbar.")
closeButton.addTarget(self, action: #selector(FindInPageBar.SELdidPressClose(_:)), for: UIControlEvents.touchUpInside)
addSubview(closeButton)
let topBorder = UIView()
topBorder.backgroundColor = FindInPageUX.TopBorderColor
addSubview(topBorder)
searchText.snp.makeConstraints { make in
make.leading.top.bottom.equalTo(self).inset(UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0))
}
matchCountView.snp.makeConstraints { make in
make.leading.equalTo(searchText.snp.trailing)
make.centerY.equalTo(self)
}
previousButton.snp.makeConstraints { make in
make.leading.equalTo(matchCountView.snp.trailing)
make.size.equalTo(self.snp.height)
make.centerY.equalTo(self)
}
nextButton.snp.makeConstraints { make in
make.leading.equalTo(previousButton.snp.trailing)
make.size.equalTo(self.snp.height)
make.centerY.equalTo(self)
}
closeButton.snp.makeConstraints { make in
make.leading.equalTo(nextButton.snp.trailing)
make.size.equalTo(self.snp.height)
make.trailing.centerY.equalTo(self)
}
topBorder.snp.makeConstraints { make in
make.height.equalTo(1)
make.left.right.top.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult override func becomeFirstResponder() -> Bool {
searchText.becomeFirstResponder()
return super.becomeFirstResponder()
}
@objc fileprivate func SELdidFindPrevious(_ sender: UIButton) {
delegate?.findInPage(self, didFindPreviousWithText: searchText.text ?? "")
}
@objc fileprivate func SELdidFindNext(_ sender: UIButton) {
delegate?.findInPage(self, didFindNextWithText: searchText.text ?? "")
}
@objc fileprivate func SELdidTextChange(_ sender: UITextField) {
matchCountView.isHidden = searchText.text?.isEmpty ?? true
delegate?.findInPage(self, didTextChange: searchText.text ?? "")
}
@objc fileprivate func SELdidPressClose(_ sender: UIButton) {
delegate?.findInPageDidPressClose(self)
}
}
|
mpl-2.0
|
6e3549b230dd5de8c6bc5b7d71a9a3a1
| 39.829114 | 197 | 0.694311 | 5.231955 | false | false | false | false |
hsienchiaolee/Anchor
|
AnchorTests/AxisTests.swift
|
1
|
2406
|
import XCTest
import Nimble
import Anchor
class AxisTests: XCTestCase {
var window: UIWindow!
var view: UIView!
override func setUp() {
super.setUp()
window = UIWindow(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
view = UIView()
window.addSubview(view)
}
func testAxisAnchors() {
let anotherView = UIView()
let anchor = view.anchor().centerX(to: anotherView.centerX).centerY(to: anotherView.centerY)
expect(anchor.centerX?.firstItem).to(beIdenticalTo(view))
expect(anchor.centerX?.firstAttribute).to(equal(NSLayoutAttribute.CenterX))
expect(anchor.centerX?.secondItem).to(beIdenticalTo(anotherView))
expect(anchor.centerX?.secondAttribute).to(equal(NSLayoutAttribute.CenterX))
expect(anchor.centerX?.relation).to(equal(NSLayoutRelation.Equal))
expect(anchor.centerY?.firstItem).to(beIdenticalTo(view))
expect(anchor.centerY?.firstAttribute).to(equal(NSLayoutAttribute.CenterY))
expect(anchor.centerY?.secondItem).to(beIdenticalTo(anotherView))
expect(anchor.centerY?.secondAttribute).to(equal(NSLayoutAttribute.CenterY))
expect(anchor.centerY?.relation).to(equal(NSLayoutRelation.Equal))
}
func testSuperviewAxisAnchors() {
let anchor = view.anchor().centerXToSuperview().centerYToSuperview()
expect(anchor.centerX?.firstItem).to(beIdenticalTo(view))
expect(anchor.centerX?.firstAttribute).to(equal(NSLayoutAttribute.CenterX))
expect(anchor.centerX?.secondItem).to(beIdenticalTo(window))
expect(anchor.centerX?.secondAttribute).to(equal(NSLayoutAttribute.CenterX))
expect(anchor.centerX?.relation).to(equal(NSLayoutRelation.Equal))
expect(anchor.centerY?.firstItem).to(beIdenticalTo(view))
expect(anchor.centerY?.firstAttribute).to(equal(NSLayoutAttribute.CenterY))
expect(anchor.centerY?.secondItem).to(beIdenticalTo(window))
expect(anchor.centerY?.secondAttribute).to(equal(NSLayoutAttribute.CenterY))
expect(anchor.centerY?.relation).to(equal(NSLayoutRelation.Equal))
}
func testSuperviewAnchorCenter() {
let centerAnchor = view.anchor().centerToSuperview()
expect(centerAnchor.centerX).toNot(beNil())
expect(centerAnchor.centerY).toNot(beNil())
}
}
|
mit
|
1dce2460fc537129c3d9e396a2cc5215
| 42.745455 | 100 | 0.691189 | 4.635838 | false | true | false | false |
cailingyun2010/swift-weibo
|
微博-S/Classes/Main/BaseTableViewController.swift
|
1
|
1189
|
//
// BaseTableViewController.swift
// 微博-S
//
// Created by nimingM on 16/3/9.
// Copyright © 2016年 蔡凌云. All rights reserved.
//
import UIKit
class BaseTableViewController: UITableViewController, VisitorViewDelegate {
// var userLogin = false
// 定义属性保存未登录界面
var userLogin = UserAccount.userLogin()
var visitorView: VisitorView?
override func loadView() {
userLogin ? super.loadView() : setupVisitorView()
}
// MARK: - 内部控制方法
/**
创建未登录界面
*/
private func setupVisitorView()
{
// 1.初始化未登录界面
let customView = VisitorView()
customView.delegate = self
// customView.backgroundColor = UIColor.redColor()
view = customView
visitorView = customView
}
// MARK: - VisitorViewDelegate
func loginBtnWillClick() {
let nav = UINavigationController()
nav.addChildViewController(OAuthViewController())
presentViewController(nav, animated: true, completion: nil)
}
func registerBtnWillClick() {
print(__FUNCTION__)
}
}
|
apache-2.0
|
408b1c316fa23e4004ae80816b23c6ed
| 22.659574 | 75 | 0.616007 | 4.793103 | false | false | false | false |
taqun/HBR
|
HBR/Classes/Model/BookmarkItem.swift
|
1
|
1188
|
//
// BookmarkItem.swift
// HBR
//
// Created by taqun on 2014/09/15.
// Copyright (c) 2014年 envoixapp. All rights reserved.
//
import UIKit
class BookmarkItem: NSObject {
var data: AnyObject
var user: String!
var date: NSDate!
var dateString: String!
var comment: String!
var iconUrl: String!
/*
* Initialize
*/
init(data: AnyObject){
self.data = data
super.init()
self.parseData()
}
/*
* Private Method
*/
private func parseData(){
self.user = self.data["user"] as! String
self.comment = self.data["comment"] as! String
//2014/10/04 16:47:18
let dateString = self.data["timestamp"] as! String
self.date = DateUtil.dateFromDateString(dateString, inputFormat: "yyyy/MM/dd HH:mm:ss")
self.dateString = DateUtil.stringFromDateString(dateString, inputFormat: "yyyy/MM/dd HH:mm:ss")
let prefix = (self.user as NSString).substringToIndex(2)
self.iconUrl = "http://cdn1.www.st-hatena.com/users/" + prefix + "/" + self.user + "/profile.gif"
}
}
|
mit
|
07484c1f8181c0040bebaf87b71f07d6
| 22.72 | 105 | 0.568297 | 3.953333 | false | true | false | false |
Bouke/HAP
|
Sources/HAP/Base/Predefined/Characteristics/Characteristic.Active.swift
|
1
|
2039
|
import Foundation
public extension AnyCharacteristic {
static func active(
_ value: Enums.Active = .active,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Active",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.active(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func active(
_ value: Enums.Active = .active,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Active",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Enums.Active> {
GenericCharacteristic<Enums.Active>(
type: .active,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
|
mit
|
3f29d24b2793b21dfc8918fad6468937
| 32.42623 | 75 | 0.571849 | 5.282383 | false | false | false | false |
kickstarter/ios-oss
|
bin/StringsScript/Sources/StringsScriptCore/StringsScript.swift
|
1
|
1792
|
import Foundation
enum StringsScriptError: Error, LocalizedError {
case genericError(String)
case insufficientArguments
case writeToFileError(String)
var errorDescription: String? {
switch self {
case .genericError(let message):
return message
case .insufficientArguments:
return "Insufficient arguments"
case .writeToFileError(let message):
return "Failed to write to file with error: \(message)"
}
}
}
public final class StringsScript {
private let arguments: [String]
public init(arguments: [String] = CommandLine.arguments) {
self.arguments = arguments
}
public func run() throws {
guard self.arguments.count > 2 else {
throw StringsScriptError.insufficientArguments
}
let writePath = self.arguments[1]
let localesRootPath = self.arguments[2]
let strings = Strings()
let stringsByLocale = try strings.deserialize(strings.fetchStringsByLocale())
try strings.localePathsAndContents(with: localesRootPath, stringsByLocale: stringsByLocale)
.forEach { path, content in
do {
try content.write(toFile: path, atomically: true, encoding: .utf8)
print("✅ Localized strings written to: \(path)")
} catch {
throw StringsScriptError.writeToFileError("\(error.localizedDescription) \nLine: \(#line)")
}
}
do {
try strings.staticStringsFileContents(stringsByLocale: stringsByLocale).write(toFile: writePath,
atomically: true,
encoding: .utf8)
print("✅ Strings written to: \(writePath)")
} catch {
throw StringsScriptError.writeToFileError("\(error.localizedDescription) \nLine: \(#line)")
}
}
}
|
apache-2.0
|
b45750d06450c1a395382c588972de64
| 30.368421 | 102 | 0.652685 | 4.692913 | false | false | false | false |
narner/AudioKit
|
Examples/iOS/SongProcessor/SongProcessor/View Controllers/iTunes Library Access/ArtistsViewController.swift
|
1
|
1873
|
//
// ArtistsViewController.swift
// SongProcessor
//
// Created by Aurelius Prochazka on 6/22/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AVFoundation
import MediaPlayer
import UIKit
class ArtistsViewController: UITableViewController {
var artistList: [MPMediaItemCollection] = []
override func viewDidLoad() {
super.viewDidLoad()
if let list = MPMediaQuery.artists().collections {
artistList = list
tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return artistList.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "MusicCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) ??
UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
// Configure the cell...
let repItem = artistList[(indexPath as NSIndexPath).row].representativeItem!
let artistName = repItem.value(forProperty: MPMediaItemPropertyArtist) as? String
cell.textLabel?.text = artistName ?? ""
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AlbumsSegue" {
if let senderCell = sender as? UITableViewCell, let albumsVC = segue.destination as? AlbumsViewController {
albumsVC.artistName = senderCell.textLabel?.text
albumsVC.title = senderCell.textLabel?.text
}
}
}
}
|
mit
|
383e485432b701e0c43bca241126e8e5
| 27.8 | 119 | 0.642094 | 5.258427 | false | false | false | false |
ducyen/ClasHStamP
|
samples/CalcSub/swift/Main/CalcModel.swift
|
3
|
23236
|
import Foundation
import Main.Statemachine
import Main.CalcOperand
import Main.CalcView
class CalcModel : System.Object
{
public class OPER_PARAMS {
public var key: char
}
public class DIGIT_1_9_PARAMS {
public var digit: char
}
public enum TestNestedEnum {
case ONE
case TWO
case THREE
}
var _stm: Statemachine
var _intEntry: string
var _fracEntry: string
var _signEntry: char
var _operEntry: char
var _operand1: double
var _entry: string
var _operand_input: CalcOperand
var _testNestedEnumAttr: TestNestedEnum
var _testNestedEnumProb: TestNestedEnum
var _calcView: CalcView
UInt32 nOnHistory;
public init (
entry: string
) {
_stm = Value0
_intEntry = ""
_fracEntry = ""
_signEntry = ' '
_operEntry = ' '
_operand1 = 0f
_entry = entry
_operand_input = new CalcOperand(this)
_testNestedEnumAttr = TestNestedEnum.ONE
_testNestedEnumProb = TestNestedEnum.ONE
_calcView = new CalcView()
nOnHistory = ON;
}
public void insertInt( char digit) {
_intEntry = _intEntry + digit;
_calcView.Update(entry);
} // insertInt
public void insertFrac( char digit) {
_fracEntry = _fracEntry + digit;
_calcView.Update(entry);
} // insertFrac
public void negate() {
_signEntry = '-';
_calcView.Update(entry);
} // negate
public void set( char digit) {
_intEntry = digit.ToString();
_fracEntry = "";
_calcView.Update(entry);
} // set
public void clear() {
_signEntry = ' ';
set( '0' );
} // clear
public void setOper( char key) {
_operEntry = key;
_calcView.Update(entry);
} // setOper
public bool calculate() {
bool error = false;
switch (_operEntry) {
case '+': _operand1 = _operand1 + curOperand; break;
case '-': _operand1 = _operand1 - curOperand; break;
case '*': _operand1 = _operand1 * curOperand; break;
case '/':
if (curOperand == 0f) {
error = true;
} else {
_operand1 = _operand1 / curOperand;
}
break;
}
return error;
} // calculate
public void showResult() {
string result = _operand1.ToString("0.########");
int dotPos = result.IndexOf(".");
string intRslt = "0";
string fracRslt = "";
if (dotPos >= 0) {
intRslt = result.Substring(0, dotPos);
fracRslt = result.Substring(dotPos + 1);
} else {
intRslt = result.Substring(0);
}
_calcView.Update(intRslt + "." + fracRslt + _operEntry);
} // showResult
public void showError() {
_calcView.Update("Err" + _operEntry);
} // showError
public TestNestedEnumOper(x: TestNestedEnum): TestNestedEnum {
return x;
} // TestNestedEnumOper
public var stm: Statemachine {
get {
return _stm
}
set {
_stm = newValue
}
}
public var entry: string {
get {
return _entry
}
set {
_entry = newValue
}
}
public var curOperand: double {
XXX
}
public var testNestedEnumProb: TestNestedEnum {
get {
return _testNestedEnumProb
}
set {
_testNestedEnumProb = newValue
}
}
const UInt32 RESULT = 1;
const UInt32 BEGIN = 2;
const UInt32 ERROR = 4;
const UInt32 OP_ENTERED = 8;
const UInt32 OPERAND_INPUT1 = 16;
const UInt32 OPERAND_INPUT2 = 32;
const UInt32 POWER_SAVE = 64;
const UInt32 STM = UInt32.MaxValue;
const UInt32 ON = ( READY | ERROR | OP_ENTERED | OPERAND_INPUT1 | OPERAND_INPUT2 );
const UInt32 READY = ( RESULT | BEGIN );
internal enum CALC_MODEL_EVENT {
case AC
case CE
case DIGIT_0
case DIGIT_1_9
case EQUALS
case OFF
case OPER
case POINT
case PSAVE_OFF
case PSAVE_ON
}
void EndTrans( bool isFinished ){
_stm.nCurrentState = _stm.nTargetState;
_stm.bIsFinished = isFinished;
_stm.bIsExternTrans = false;
if( isFinished ){
return;
}
switch( _stm.nCurrentState ){
case ON: On_Entry(); break;
case READY: Ready_Entry(); break;
case RESULT: Result_Entry(); break;
case BEGIN: Begin_Entry(); break;
case ERROR: Error_Entry(); break;
case OP_ENTERED: OpEntered_Entry(); break;
case OPERAND_INPUT1: OperandInput1_Entry(); break;
case OPERAND_INPUT2: OperandInput2_Entry(); break;
case POWER_SAVE: PowerSave_Entry(); break;
default: break;
}
}
void BgnTrans( UInt32 sourceState, UInt32 targetState ){
_stm.nSourceState = sourceState;
_stm.nTargetState = targetState;
switch( _stm.nCurrentState ){
case ON: On_Exit(); break;
case READY: Ready_Exit(); break;
case RESULT: Result_Exit(); break;
case BEGIN: Begin_Exit(); break;
case ERROR: Error_Exit(); break;
case OP_ENTERED: OpEntered_Exit(); break;
case OPERAND_INPUT1: OperandInput1_Exit(); break;
case OPERAND_INPUT2: OperandInput2_Exit(); break;
case POWER_SAVE: PowerSave_Exit(); break;
default: break;
}
}
public bool RunToCompletion(){
bool bResult;
do{
if( Statemachine.IsComposite( _stm.nCurrentState ) && !_stm.bIsFinished ){
bResult = Start();
}else{
bResult = Done();
}
}while( bResult );
if (IsFinished() && _stm.pParentContext != null) {
_stm.pParentContext.runToCompletion();
}
return bResult;
}
public bool IsFinished() {
return _stm.bIsFinished && _stm.nCurrentState == STM;
}
public bool IsEventHandled( bool bReset ) {
_stm.bIsEventHandled &= !bReset;
return _stm.bIsEventHandled;
}
public bool Abort() {
BgnTrans( STM, STM );
EndTrans( true );
return true;
}
bool EventProc( UInt32 nEventId, Object pEventParams ){
bool bResult = false;
if (IsFinished()) {
return bResult;
}
bResult |= _operand_input.IsEventHandled( true );
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.CE:{
_operand_input.Ce( );
} break;
case CALC_MODEL_EVENT.DIGIT_0:{
_operand_input.Digit0( );
} break;
case CALC_MODEL_EVENT.DIGIT_1_9:{
CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams;
_operand_input.Digit19(e.digit );
} break;
case CALC_MODEL_EVENT.EQUALS:{
_operand_input.Equals( );
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
_operand_input.Oper(e.key );
} break;
case CALC_MODEL_EVENT.POINT:{
_operand_input.Point( );
} break;
default: break;
}
switch( _stm.nCurrentState ){
case ON: bResult = On_EventProc( nEventId, pEventParams ); break;
case READY: bResult = Ready_EventProc( nEventId, pEventParams ); break;
case RESULT: bResult = Result_EventProc( nEventId, pEventParams ); break;
case BEGIN: bResult = Begin_EventProc( nEventId, pEventParams ); break;
case ERROR: bResult = Error_EventProc( nEventId, pEventParams ); break;
case OP_ENTERED: bResult = OpEntered_EventProc( nEventId, pEventParams ); break;
case OPERAND_INPUT1: bResult = OperandInput1_EventProc( nEventId, pEventParams ); break;
case OPERAND_INPUT2: bResult = OperandInput2_EventProc( nEventId, pEventParams ); break;
case POWER_SAVE: bResult = PowerSave_EventProc( nEventId, pEventParams ); break;
default: break;
}
return bResult;
}
void On_Entry(){
if( Statemachine.IsIn( STM, _stm.nLCAState ) || _stm.nLCAState == 0 ){
_operand_input.Start();
_operand_input.RunToCompletion();
_stm.nLCAState = 0;
}
}
bool On_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.AC:{
_stm.bIsExternTrans = true;
BgnTrans( ON, ON );
_operEntry = ' ';
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.OFF:{
BgnTrans( ON, STM );
EndTrans( true );
bResult = true;
} break;
case CALC_MODEL_EVENT.PSAVE_ON:{
BgnTrans( ON, POWER_SAVE );
EndTrans( false );
bResult = true;
} break;
default: break;
}
bResult |= _operand_input.IsEventHandled( false );
return bResult;
}
void On_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, ON ) && Statemachine.IsIn( _stm.nTargetState, ON );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
_operand_input.Abort();
} else {
_stm.nLCAState = ON;
}
}
void Ready_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
_signEntry = ' ';
nOnHistory = READY;
_stm.nLCAState = 0;
}
}
bool Ready_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.DIGIT_0:{
BgnTrans( READY, OPERAND_INPUT1 );
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.DIGIT_1_9:{
CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams;
BgnTrans( READY, OPERAND_INPUT1 );
set(e.digit);
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.POINT:{
BgnTrans( READY, OPERAND_INPUT1 );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void Ready_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, READY ) && Statemachine.IsIn( _stm.nTargetState, READY );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = READY;
}
}
void Result_Entry(){
if( Statemachine.IsIn( READY, _stm.nLCAState ) || _stm.nLCAState == 0 ){
Ready_Entry();
_stm.nLCAState = 0;
}
}
bool Result_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
return bResult ? bResult : Ready_EventProc( nEventId, pEventParams );
}
void Result_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, RESULT ) && Statemachine.IsIn( _stm.nTargetState, RESULT );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
Ready_Exit();
} else {
_stm.nLCAState = RESULT;
}
}
void Begin_Entry(){
if( Statemachine.IsIn( READY, _stm.nLCAState ) || _stm.nLCAState == 0 ){
Ready_Entry();
clear();
_stm.nLCAState = 0;
}
}
bool Begin_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
if (e.key == '-') {
BgnTrans( BEGIN, OPERAND_INPUT1 );
EndTrans( false );
bResult = true;
}
} break;
default: break;
}
return bResult ? bResult : Ready_EventProc( nEventId, pEventParams );
}
void Begin_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, BEGIN ) && Statemachine.IsIn( _stm.nTargetState, BEGIN );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
Ready_Exit();
} else {
_stm.nLCAState = BEGIN;
}
}
void Error_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
showError();
nOnHistory = ERROR;
_stm.nLCAState = 0;
}
}
bool Error_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void Error_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, ERROR ) && Statemachine.IsIn( _stm.nTargetState, ERROR );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = ERROR;
}
}
void OpEntered_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
_signEntry = ' ';
nOnHistory = OP_ENTERED;
_stm.nLCAState = 0;
}
}
bool OpEntered_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.DIGIT_0:{
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.DIGIT_1_9:{
CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams;
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
set(e.digit);
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
if (e.key == '-') {
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
EndTrans( false );
bResult = true;
}
} break;
case CALC_MODEL_EVENT.POINT:{
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void OpEntered_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OP_ENTERED ) && Statemachine.IsIn( _stm.nTargetState, OP_ENTERED );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = OP_ENTERED;
}
}
void OperandInput1_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
nOnHistory = OPERAND_INPUT1;
_stm.nLCAState = 0;
}
}
bool OperandInput1_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.CE:{
BgnTrans( OPERAND_INPUT1, BEGIN );
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
BgnTrans( OPERAND_INPUT1, OP_ENTERED );
_operand1 = curOperand;
setOper( e.key );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void OperandInput1_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OPERAND_INPUT1 ) && Statemachine.IsIn( _stm.nTargetState, OPERAND_INPUT1 );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = OPERAND_INPUT1;
}
}
void OperandInput2_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
nOnHistory = OPERAND_INPUT2;
_stm.nLCAState = 0;
}
}
bool OperandInput2_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.CE:{
BgnTrans( OPERAND_INPUT2, OP_ENTERED );
clear();
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.EQUALS:{
bool error = calculate();
if (error) {
BgnTrans( OPERAND_INPUT2, ERROR );
EndTrans( false );
bResult = true;
} else {
BgnTrans( OPERAND_INPUT2, RESULT );
_operEntry = ' ';
showResult();
EndTrans( false );
bResult = true;
}
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
bool error = calculate();
setOper( e.key );
if (error) {
BgnTrans( OPERAND_INPUT2, ERROR );
EndTrans( false );
bResult = true;
} else {
BgnTrans( OPERAND_INPUT2, OP_ENTERED );
showResult();
EndTrans( false );
bResult = true;
}
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void OperandInput2_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OPERAND_INPUT2 ) && Statemachine.IsIn( _stm.nTargetState, OPERAND_INPUT2 );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = OPERAND_INPUT2;
}
}
void PowerSave_Entry(){
if( Statemachine.IsIn( STM, _stm.nLCAState ) || _stm.nLCAState == 0 ){
_stm.nLCAState = 0;
}
}
bool PowerSave_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.PSAVE_OFF:{
BgnTrans( POWER_SAVE, nOnHistory );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult;
}
void PowerSave_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, POWER_SAVE ) && Statemachine.IsIn( _stm.nTargetState, POWER_SAVE );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
} else {
_stm.nLCAState = POWER_SAVE;
}
}
public bool Start(
){
bool bResult = false;
_stm.bIsFinished = false;
switch( _stm.nCurrentState ){
case STM:{
BgnTrans( STM, ON );
_calcView.DrawFrame();
EndTrans( false );
bResult = true;
} break;
case ON:{
BgnTrans( ON, READY );
EndTrans( false );
bResult = true;
} break;
case READY:{
BgnTrans( READY, BEGIN );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult;
}
public void Ac(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.AC, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Ce(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.CE, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Digit0(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.DIGIT_0, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Digit19(
char digit
) {
Object pEventParams = null;
CalcModel.DIGIT_1_9_PARAMS eventParams = new CalcModel.DIGIT_1_9_PARAMS();
pEventParams = ( Object )eventParams;
eventParams.digit = digit;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.DIGIT_1_9, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Equals(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.EQUALS, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Off(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.OFF, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Oper(
char key
) {
Object pEventParams = null;
CalcModel.OPER_PARAMS eventParams = new CalcModel.OPER_PARAMS();
pEventParams = ( Object )eventParams;
eventParams.key = key;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.OPER, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Point(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.POINT, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void PsaveOff(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.PSAVE_OFF, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void PsaveOn(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.PSAVE_ON, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public bool Done(
){
bool bResult = false;
return bResult;
}
}
}
|
gpl-3.0
|
22e113263b62030771551efebad62eb7
| 31.816384 | 138 | 0.531764 | 3.719225 | false | false | false | false |
ahmad-atef/AutoScout24_Tech_Challenge
|
AutoScout24 Tech_Challenge/Helpers/Observer.swift
|
1
|
1329
|
//
// Observer.swift
// AutoScout24 Tech_Challenge
//
// Created by Ahmad Atef on 5/10/17.
// Copyright © 2017 Ahmad Atef. All rights reserved.
//
import Foundation
/// Subject is Responisnle for [ Notification & Managing Observers ].
protocol Subject {
func addObserver(observers : Observer...)
func removeObserver(observer : Observer)
func sendNotification(updatedCar: Car)
}
/// For All Observers that are waiting to get Notified when a change from Subject has been Changed
protocol Observer : class {
func didRecieveNotification(updatedCar: Car)
}
class SubjectBase: Subject {
var observers : [Observer] = []
private var collectionQueue = DispatchQueue(label: "colQ", attributes: .concurrent)
func addObserver(observers: Observer...) {
collectionQueue.sync {
for newObserver in observers{
self.observers.append(newObserver)
}
}
}
func removeObserver(observer: Observer) {
collectionQueue.sync {
self.observers = observers.filter({$0 !== observer})
}
}
func sendNotification(updatedCar car: Car) {
collectionQueue.sync {
for observer in observers{
observer.didRecieveNotification(updatedCar: car)
}
}
}
}
|
mit
|
e02a129ab2720790f963f1197f97eee3
| 24.056604 | 98 | 0.637801 | 4.57931 | false | false | false | false |
mirai418/leaflet-ios
|
leaflet/FecPoiView.swift
|
1
|
1073
|
//
// FecPoiView.swift
// leaflet
//
// Created by Mirai Akagawa on 4/6/15.
// Copyright (c) 2015 parks-and-rec. All rights reserved.
//
import UIKit
class FecPoiView: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
private var picture: UIImageView!
private var indicator: UIActivityIndicatorView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(frame: CGRect, albumCover: String) {
super.init(frame: frame)
backgroundColor = UIColor.blackColor()
picture = UIImageView(frame: CGRectMake(5, 5, frame.size.width - 10, frame.size.height - 10))
addSubview(picture)
indicator = UIActivityIndicatorView()
indicator.center = center
indicator.activityIndicatorViewStyle = .WhiteLarge
indicator.startAnimating()
addSubview(indicator)
}
}
|
mit
|
2f332febfe1fbb780bf213b6de6d05fb
| 25.825 | 101 | 0.655172 | 4.397541 | false | false | false | false |
notbenoit/PimpMyString
|
Source/iOS/Specific.swift
|
1
|
6082
|
//
// Copyright (c) 2015, Benoît Layer
// 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.
// * The name of the author may not be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE 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 BENOIT LAYER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
import UIKit
/**
Use this function to change the font for a range of text.
- parameter font: The font to apply.
- parameter range: An optional range where the font will be applied. No range means the whole string.
- returns: A StringTuner to tune the font.
*/
public func pms_font(fontP: UIFont, range: NSRange? = nil) -> StringTuner {
return font(fontP, range: range)
}
/**
Use this function to specify the color of the text during rendering.
- parameter color: The color to apply to the text.
- parameter range: An optional range where the color will be applied. No range means the whole string.
- returns: A StringTuner to tune the text color.
*/
public func pms_fgColor(color: UIColor, range: NSRange? = nil) -> StringTuner {
return fgColor(color, range: range)
}
/**
Use this function to specify the color of the background area behind the text.
- parameter color: The color to apply to the background.
- parameter range: An optional range where the background color will be applied. No range means the whole string.
- returns: A StringTuner to tune the background color.
*/
public func pms_bgColor(color: UIColor, range: NSRange? = nil) -> StringTuner {
return bgColor(color, range: range)
}
/**
This function sets the underline color, and whether the text is
underlined and corresponds to one of the constants described
in “Underline and Strikethrough Style Attributes”.
- parameter color: The color to use when the text is underlined.
- parameter style: The style of the underline.
- parameter range: An optional range where the attributes will be applied. No range means the whole string.
- returns: A StringTuner to underline the text.
*/
public func pms_underline(color: UIColor, style: NSUnderlineStyle, range: NSRange? = nil) -> StringTuner {
return underline(color, style: style, range: range)
}
/**
This function sets the color of the strike and whether the text
has a line through it and corresponds to one of the constants
described in “Underline and Strikethrough Style Attributes”.
- parameter color: The color to use when the text is striked.
- parameter style: The style of the strikethrough.
- parameter range: An optional range where the attributes will be applied. No range means the whole string.
- returns: A StringTuner to strike the text.
*/
public func pms_strikeThrough(color: UIColor, style: NSUnderlineStyle, range: NSRange? = nil) -> StringTuner {
return strike(color, style: style, range: range)
}
/**
This functions sets the stroke color, and stroke width of
the text to draw.
- parameter color: The color of the stroke.
- parameter width: The width of the stroke as a Float value.
- parameter range: An optional range where the attributes will be applied. No range means the whole string.
- returns: A StringTuner to stroke the text.
*/
public func pms_stroke(color: UIColor, width: Float, range: NSRange? = nil) -> StringTuner {
return stroke(color, width: width, range: range)
}
/**
This function indicates whether the text is underlined
and corresponds to one of the constants described in
“Underline and Strikethrough Style Attributes”
- parameter color: The color used to underline
- parameter style: The style used to underline (single, double...)
- parameter range: An optional range where the attributes will be applied. No range means the whole string.
- returns: A StringTuner to underline the text.
*/
func underline(color: Color, style: NSUnderlineStyle, range: NSRange? = nil) -> StringTuner {
return {
ats in
var ret = addAttribute(ats, attr: NSUnderlineColorAttributeName, value: color, range: range)
ret = addAttribute(ret, attr: NSUnderlineStyleAttributeName, value: style.rawValue, range: range)
return ret
}
}
/**
This function indicates whether the text has a line
through it and corresponds to one of the constants
described in “Underline and Strikethrough Style Attributes”.
- parameter color: The color used to strike the text.
- parameter style: The style used to strike the text (single, double...)
- parameter range: An optional range where the attributes will be applied. No range means the whole string.
- returns: A StringTuner to strike the text.
*/
func strike(color: Color, style: NSUnderlineStyle, range: NSRange? = nil) -> StringTuner {
return {
ats in
var ret = addAttribute(ats, attr: NSStrikethroughColorAttributeName, value: color, range: range)
ret = addAttribute(ret, attr: NSStrikethroughStyleAttributeName, value: style.rawValue, range: range)
return ret
}
}
|
bsd-3-clause
|
e0794e30d1d958f67a7313c98e279bec
| 39.704698 | 113 | 0.752679 | 4.31059 | false | false | false | false |
RoninSTi/swift-code-sample
|
AHPhotoTextCell.swift
|
1
|
1464
|
//
// AHPhotoTextCell.swift
// airhoot
//
// Created by Craig Cronin on 6/2/17.
// Copyright © 2017 130R Studios. All rights reserved.
//
import Cartography
import SDWebImage
import UIKit
class AHPhotoTextCell: AHFeedBaseCell {
private lazy var hootTextLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "SFUIText-Regular", size: 20.0)
label.numberOfLines = 0
label.textColor = .white
return label
}()
private lazy var hootImageView:UIImageView = {
let imageView = UIImageView()
return imageView
}()
override func constrainViews() {
super.constrainViews()
self.contentContainer.addSubview(self.hootImageView)
self.contentContainer.addSubview(self.hootTextLabel)
constrain(self.contentContainer, self.hootImageView, self.hootTextLabel) { (content, image, label) in
image.top == image.superview!.top
image.leading == image.superview!.leading
image.trailing == image.superview!.trailing
image.height == image.width
image.bottom == label.top - 15
label.leading == label.superview!.leading + 15
label.trailing == label.superview!.trailing - 15
label.bottom == label.superview!.bottom - 15
}
}
override func configure(withHoot hoot:Hoot) {
super.configure(withHoot: hoot)
self.hootTextLabel.text = hoot.text
if let url = hoot.photo {
self.hootImageView.sd_setImage(with: url)
}
}
}
|
mit
|
263df3e8c60000812f8db458f4fb6671
| 26.092593 | 105 | 0.677375 | 3.890957 | false | false | false | false |
exchangegroup/calayer-with-tint-colored-image
|
calayer-with-tint-colored-image/ViewController.swift
|
2
|
1192
|
//
// ViewController.swift
// calayer-with-tint-colored-image
//
// Created by Evgenii Neumerzhitckii on 17/11/2014.
// Copyright (c) 2014 The Exchange Group Pty Ltd. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var viewForCALayer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
viewForCALayer.backgroundColor = nil
if let currentImage = UIImage(named: "star.png") {
ViewController.setImageViewImage(imageView, image: currentImage)
ViewController.setCALayerImage(viewForCALayer.layer, image: currentImage)
}
}
private class func setImageViewImage(imageView: UIImageView, image: UIImage) {
imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
}
private class func setCALayerImage(layer: CALayer, image: UIImage) {
let tintedImage = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
layer.contents = tintedImage.CGImage
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
e6fe879dc1f6fe618f0ae9d8ff5bb898
| 27.380952 | 87 | 0.744128 | 4.638132 | false | false | false | false |
wybosys/n2
|
src.swift/ui/N2View.swift
|
1
|
1056
|
protocol IView
{
func onlayout(rect:CGRect)
}
extension UIView
{
func rectForLayout() -> CGRect
{
return self.bounds
}
final
func __swcb_layoutsubviews()
{
var rc = self.rectForLayout()
if self.respondsToSelector(Selector("onlayout:")) {
let sf:AnyObject = self
sf.onlayout(rc)
}
}
}
class View : UIView, ObjectExt, IView
{
convenience init()
{
self.init(frame: CGRect.zeroRect)
self.oninit()
}
deinit
{
self.onfin()
}
func oninit()
{
}
func onfin()
{
}
// 边缘的留空
var paddingEdge: CGPadding = CGPadding.zeroPadding
// 内容的偏移
var offsetEdge: CGPoint = CGPoint.zeroPoint
override func rectForLayout() -> CGRect
{
var ret = self.bounds
ret.apply(self.paddingEdge)
ret.offset(self.offsetEdge)
return ret
}
func onlayout(rect: CGRect)
{
}
}
|
bsd-3-clause
|
0f41f5d092beaf9da6d388093ee0a5b2
| 14.69697 | 59 | 0.517375 | 4.015504 | false | false | false | false |
sovereignshare/fly-smuthe
|
Fly Smuthe/Fly Smuthe/PageViewController.swift
|
1
|
5093
|
//
// PageViewController.swift
// Fly Smuthe
//
// Created by Adam M Rivera on 8/26/15.
// Copyright (c) 2015 Adam M Rivera. All rights reserved.
//
import Foundation
import UIKit
class PageViewController : UIViewController, UIPageViewControllerDataSource, QuickSettingsViewControllerDelegate {
@IBOutlet weak var quickSettingsContainerView: UIView!
@IBOutlet weak var quickSettingsContainerViewBottomConstraint: NSLayoutConstraint!
let findSmoothAirIdx = 0;
let reportAirConditionIdx = 1;
var currentIdx = 0;
var totalPages = 1;
var pageViewController: UIPageViewController!;
var includeInaccurateResults: Bool = true;
var radius: Int = 3;
var hoursUntilStale: Int = 3;
var intervalMin: Int = 5;
var optionsAreHidden = true;
override func viewDidLoad() {
super.viewDidLoad();
let pageControl = UIPageControl.appearance();
pageControl.pageIndicatorTintColor = UIColor.lightGrayColor();
pageControl.currentPageIndicatorTintColor = UIColor.blackColor();
pageControl.backgroundColor = UIColor.whiteColor();
pageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("PagedViewControllerContainer") as! UIPageViewController;
pageViewController.dataSource = self;
let firstPage = self.viewControllerAtIndex(0);
let pageArr = [firstPage!];
pageViewController.setViewControllers(pageArr, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil);
pageViewController.view.frame = CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height);
self.addChildViewController(pageViewController);
self.view.insertSubview(pageViewController.view, belowSubview: quickSettingsContainerView);
pageViewController.didMoveToParentViewController(self);
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var idx = (viewController as! PagedViewControllerBase).pageIndex!;
if(idx == 0) {
return nil;
}
idx--;
return self.viewControllerAtIndex(idx);
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var idx = (viewController as! PagedViewControllerBase).pageIndex!;
idx++;
if(idx == totalPages) {
return nil;
}
return self.viewControllerAtIndex(idx);
}
func settingsButtonPressed(){
toggleOptionsMenu(false);
}
func settingsDismissed() {
toggleOptionsMenu(true);
}
func toggleOptionsMenu(hide: Bool){
let height = CGRectGetHeight(quickSettingsContainerView.bounds);
var constant = quickSettingsContainerViewBottomConstraint.constant;
constant = hide ? (constant - height) : (constant + height);
view.layoutIfNeeded();
UIView.animateWithDuration(0.2, delay: 0, usingSpringWithDamping: 0.95, initialSpringVelocity: 1, options: [.AllowUserInteraction, .BeginFromCurrentState], animations: {
self.quickSettingsContainerViewBottomConstraint.constant = constant;
self.view.layoutIfNeeded();
}, completion: nil);
}
func viewControllerAtIndex(index: Int) -> PagedViewControllerBase! {
currentIdx = index;
var pageViewController: PagedViewControllerBase!;
//pageViewController.delegate = self;
switch(index){
case findSmoothAirIdx:
pageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("FindSmoothAirViewController") as! PagedViewControllerBase;
(pageViewController as! FindSmoothAirViewController).delegate = self;
break;
case reportAirConditionIdx:
pageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ReportConditionsViewController") as! PagedViewControllerBase;
break;
default:
pageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("FindSmoothAirViewController") as! PagedViewControllerBase;
break;
}
pageViewController.pageIndex = index;
return pageViewController;
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return totalPages;
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return currentIdx;
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "quickSettingsEmbedSegue"){
(segue.destinationViewController as! QuickSettingsViewController).delegate = self;
}
}
}
|
gpl-3.0
|
be88ae2bcb6217505583228cbb112349
| 37.877863 | 177 | 0.689967 | 5.9777 | false | false | false | false |
zhiquan911/CHKLineChart
|
CHKLineChart/Example/Example/Demo/ChartFullViewController.swift
|
1
|
3536
|
//
// ChartFullViewController.swift
// CHKLineChart
//
// Created by Chance on 2017/6/19.
// Copyright © 2017年 atall.io. All rights reserved.
//
import UIKit
import CHKLineChartKit
class ChartFullViewController: UIViewController {
@IBOutlet var chartView: CHKLineChartView!
@IBOutlet var loadingView: UIActivityIndicatorView!
var klineDatas = [KlineChartData]()
override func viewDidLoad() {
super.viewDidLoad()
self.chartView.delegate = self
self.chartView.style = .simpleLineDark
self.fetchChartDatas(symbol: "BTC-USD", type: "15min")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 拉取数据
func fetchChartDatas(symbol: String, type: String) {
self.loadingView.startAnimating()
self.loadingView.isHidden = false
ChartDatasFetcher.shared.getRemoteChartData(
symbol: symbol,
timeType: type,
size: 70) {
[weak self](flag, chartsData) in
if flag && chartsData.count > 0 {
self?.klineDatas = chartsData
self?.chartView.reloadData(toPosition: .end)
}
self?.loadingView.stopAnimating()
self?.loadingView.isHidden = true
}
}
}
// MARK: - 实现K线图表的委托方法
extension ChartFullViewController: CHKLineChartDelegate {
func numberOfPointsInKLineChart(chart: CHKLineChartView) -> Int {
return self.klineDatas.count
}
func kLineChart(chart: CHKLineChartView, valueForPointAtIndex index: Int) -> CHChartItem {
let data = self.klineDatas[index]
let item = CHChartItem()
item.time = data.time
item.closePrice = CGFloat(data.closePrice)
return item
}
func kLineChart(chart: CHKLineChartView, labelOnYAxisForValue value: CGFloat, atIndex index: Int, section: CHSection) -> String {
let strValue = value.ch_toString(maxF: section.decimal)
return strValue
}
func kLineChart(chart: CHKLineChartView, labelOnXAxisForIndex index: Int) -> String {
let data = self.klineDatas[index]
let timestamp = data.time
var time = Date.ch_getTimeByStamp(timestamp, format: "HH:mm")
if time == "00:00" {
time = Date.ch_getTimeByStamp(timestamp, format: "MM-dd")
}
return time
}
/// 调整每个分区的小数位保留数
///
/// - parameter chart:
/// - parameter section:
///
/// - returns:
func kLineChart(chart: CHKLineChartView, decimalAt section: Int) -> Int {
return 2
}
/// 调整Y轴标签宽度
///
/// - parameter chart:
///
/// - returns:
func widthForYAxisLabelInKLineChart(in chart: CHKLineChartView) -> CGFloat {
return chart.kYAxisLabelWidth
}
func heightForXAxisInKLineChart(in chart: CHKLineChartView) -> CGFloat {
return 16
}
/// 点击图标返回点击的位置和数据对象
///
/// - Parameters:
/// - chart:
/// - index:
/// - item:
func kLineChart(chart: CHKLineChartView, didSelectAt index: Int, item: CHChartItem) {
NSLog("selected index = \(index)")
NSLog("selected item closePrice = \(item.closePrice)")
}
}
|
mit
|
6bbef1834b390dfe7e81d994879fa747
| 26.910569 | 133 | 0.595398 | 4.412596 | false | false | false | false |
justindarc/firefox-ios
|
Client/Frontend/Browser/URLBarView.swift
|
1
|
33279
|
/* 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 Shared
import SnapKit
private struct URLBarViewUX {
static let TextFieldBorderColor = UIColor.Photon.Grey40
static let TextFieldActiveBorderColor = UIColor.Photon.Blue40
static let LocationLeftPadding: CGFloat = 8
static let Padding: CGFloat = 10
static let LocationHeight: CGFloat = 40
static let ButtonHeight: CGFloat = 44
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 8
static let TextFieldBorderWidth: CGFloat = 0
static let TextFieldBorderWidthSelected: CGFloat = 4
static let ProgressBarHeight: CGFloat = 3
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(equalInset: Padding)
}
protocol URLBarDelegate: AnyObject {
func urlBarDidPressTabs(_ urlBar: URLBarView)
func urlBarDidPressReaderMode(_ urlBar: URLBarView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool
func urlBarDidPressStop(_ urlBar: URLBarView)
func urlBarDidPressReload(_ urlBar: URLBarView)
func urlBarDidEnterOverlayMode(_ urlBar: URLBarView)
func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView)
func urlBarDidLongPressLocation(_ urlBar: URLBarView)
func urlBarDidPressQRButton(_ urlBar: URLBarView)
func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton)
func urlBarDidTapShield(_ urlBar: URLBarView, from button: UIButton)
func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(_ urlBar: URLBarView)
func urlBar(_ urlBar: URLBarView, didRestoreText text: String)
func urlBar(_ urlBar: URLBarView, didEnterText text: String)
func urlBar(_ urlBar: URLBarView, didSubmitText text: String)
// Returns either (search query, true) or (url, false).
func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool)
func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton)
func urlBarDidBeginDragInteraction(_ urlBar: URLBarView)
}
class URLBarView: UIView {
// Additional UIAppearance-configurable properties
@objc dynamic var locationBorderColor: UIColor = URLBarViewUX.TextFieldBorderColor {
didSet {
if !inOverlayMode {
locationContainer.layer.borderColor = locationBorderColor.cgColor
}
}
}
@objc dynamic var locationActiveBorderColor: UIColor = URLBarViewUX.TextFieldActiveBorderColor {
didSet {
if inOverlayMode {
locationContainer.layer.borderColor = locationActiveBorderColor.cgColor
}
}
}
weak var delegate: URLBarDelegate?
weak var tabToolbarDelegate: TabToolbarDelegate?
var helper: TabToolbarHelper?
var isTransitioning: Bool = false {
didSet {
if isTransitioning {
// Cancel any pending/in-progress animations related to the progress bar
self.progressBar.setProgress(1, animated: false)
self.progressBar.alpha = 0.0
}
}
}
var toolbarIsShowing = false
var topTabsIsShowing = false
fileprivate var locationTextField: ToolbarTextField?
/// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown,
/// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode
/// is *not* tied to the location text field's editing state; for instance, when selecting
/// a panel, the first responder will be resigned, yet the overlay mode UI is still active.
var inOverlayMode = false
lazy var locationView: TabLocationView = {
let locationView = TabLocationView()
locationView.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationView.translatesAutoresizingMaskIntoConstraints = false
locationView.readerModeState = ReaderModeState.unavailable
locationView.delegate = self
return locationView
}()
lazy var locationContainer: UIView = {
let locationContainer = TabLocationContainerView()
locationContainer.translatesAutoresizingMaskIntoConstraints = false
locationContainer.backgroundColor = .clear
return locationContainer
}()
let line = UIView()
lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton.tabTrayButton()
tabsButton.accessibilityIdentifier = "URLBarView.tabsButton"
return tabsButton
}()
fileprivate lazy var progressBar: GradientProgressBar = {
let progressBar = GradientProgressBar()
progressBar.clipsToBounds = false
return progressBar
}()
fileprivate lazy var cancelButton: UIButton = {
let cancelButton = InsetButton()
cancelButton.setImage(UIImage.templateImageNamed("goBack"), for: .normal)
cancelButton.accessibilityIdentifier = "urlBar-cancel"
cancelButton.accessibilityLabel = Strings.BackTitle
cancelButton.addTarget(self, action: #selector(didClickCancel), for: .touchUpInside)
cancelButton.alpha = 0
return cancelButton
}()
fileprivate lazy var showQRScannerButton: InsetButton = {
let button = InsetButton()
button.setImage(UIImage.templateImageNamed("menu-ScanQRCode"), for: .normal)
button.accessibilityIdentifier = "urlBar-scanQRCode"
cancelButton.accessibilityLabel = Strings.ScanQRCodeViewTitle
button.clipsToBounds = false
button.addTarget(self, action: #selector(showQRScanner), for: .touchUpInside)
button.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
button.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
return button
}()
fileprivate lazy var scrollToTopButton: UIButton = {
let button = UIButton()
// This button interferes with accessibility of the URL bar as it partially overlays it, and keeps getting the VoiceOver focus instead of the URL bar.
// @TODO: figure out if there is an iOS standard way to do this that works with accessibility.
button.isAccessibilityElement = false
button.addTarget(self, action: #selector(tappedScrollToTopArea), for: .touchUpInside)
return button
}()
var menuButton = ToolbarButton()
var libraryButton = ToolbarButton()
var bookmarkButton = ToolbarButton()
var forwardButton = ToolbarButton()
var stopReloadButton = ToolbarButton()
var backButton: ToolbarButton = {
let backButton = ToolbarButton()
backButton.accessibilityIdentifier = "URLBarView.backButton"
return backButton
}()
lazy var actionButtons: [Themeable & UIButton] = [self.tabsButton, self.libraryButton, self.menuButton, self.forwardButton, self.backButton, self.stopReloadButton]
var currentURL: URL? {
get {
return locationView.url as URL?
}
set(newURL) {
locationView.url = newURL
if let url = newURL, InternalURL(url)?.isAboutHomeURL ?? false {
line.isHidden = true
} else {
line.isHidden = false
}
}
}
fileprivate let privateModeBadge = BadgeWithBackdrop(imageName: "privateModeBadge", backdropCircleColor: UIColor.Defaults.MobilePrivatePurple)
fileprivate let hideImagesBadge = BadgeWithBackdrop(imageName: "menuBadge")
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
locationContainer.addSubview(locationView)
[scrollToTopButton, line, tabsButton, progressBar, cancelButton, showQRScannerButton,
libraryButton, menuButton, forwardButton, backButton, stopReloadButton, locationContainer].forEach {
addSubview($0)
}
privateModeBadge.add(toParent: self)
hideImagesBadge.add(toParent: self)
helper = TabToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-overlay mode.
updateViewsForOverlayModeAndToolbarChanges()
}
fileprivate func setupConstraints() {
line.snp.makeConstraints { make in
make.bottom.leading.trailing.equalTo(self)
make.height.equalTo(1)
}
scrollToTopButton.snp.makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp.makeConstraints { make in
make.top.equalTo(self.snp.bottom).inset(URLBarViewUX.ProgressBarHeight / 2)
make.height.equalTo(URLBarViewUX.ProgressBarHeight)
make.left.right.equalTo(self)
}
locationView.snp.makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp.makeConstraints { make in
make.leading.equalTo(self.safeArea.leading)
make.centerY.equalTo(self.locationContainer)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
backButton.snp.makeConstraints { make in
make.leading.equalTo(self.safeArea.leading).offset(URLBarViewUX.Padding)
make.centerY.equalTo(self)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
forwardButton.snp.makeConstraints { make in
make.leading.equalTo(self.backButton.snp.trailing)
make.centerY.equalTo(self)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
stopReloadButton.snp.makeConstraints { make in
make.leading.equalTo(self.forwardButton.snp.trailing)
make.centerY.equalTo(self)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
libraryButton.snp.makeConstraints { make in
make.trailing.equalTo(self.menuButton.snp.leading)
make.centerY.equalTo(self)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
menuButton.snp.makeConstraints { make in
make.trailing.equalTo(self.safeArea.trailing).offset(-URLBarViewUX.Padding)
make.centerY.equalTo(self)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
tabsButton.snp.makeConstraints { make in
make.trailing.equalTo(self.menuButton.snp.leading)
make.centerY.equalTo(self)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
showQRScannerButton.snp.makeConstraints { make in
make.trailing.equalTo(self.safeArea.trailing)
make.centerY.equalTo(self.locationContainer)
make.size.equalTo(URLBarViewUX.ButtonHeight)
}
privateModeBadge.layout(onButton: tabsButton)
hideImagesBadge.layout(onButton: menuButton)
}
override func updateConstraints() {
super.updateConstraints()
if inOverlayMode {
// In overlay mode, we always show the location view full width
self.locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidthSelected
self.locationContainer.snp.remakeConstraints { make in
let height = URLBarViewUX.LocationHeight + (URLBarViewUX.TextFieldBorderWidthSelected * 2)
make.height.equalTo(height)
make.trailing.equalTo(self.showQRScannerButton.snp.leading)
make.leading.equalTo(self.cancelButton.snp.trailing)
make.centerY.equalTo(self)
}
self.locationView.snp.remakeConstraints { make in
make.edges.equalTo(self.locationContainer).inset(UIEdgeInsets(equalInset: URLBarViewUX.TextFieldBorderWidthSelected))
}
self.locationTextField?.snp.remakeConstraints { make in
make.edges.equalTo(self.locationView).inset(UIEdgeInsets(top: 0, left: URLBarViewUX.LocationLeftPadding, bottom: 0, right: URLBarViewUX.LocationLeftPadding))
}
} else {
self.locationContainer.snp.remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.leading.equalTo(self.stopReloadButton.snp.trailing).offset(URLBarViewUX.Padding)
if self.topTabsIsShowing {
make.trailing.equalTo(self.libraryButton.snp.leading).offset(-URLBarViewUX.Padding)
} else {
make.trailing.equalTo(self.tabsButton.snp.leading).offset(-URLBarViewUX.Padding)
}
} else {
// Otherwise, left align the location view
make.leading.trailing.equalTo(self).inset(UIEdgeInsets(top: 0, left: URLBarViewUX.LocationLeftPadding-1, bottom: 0, right: URLBarViewUX.LocationLeftPadding-1))
}
make.height.equalTo(URLBarViewUX.LocationHeight+2)
make.centerY.equalTo(self)
}
self.locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
self.locationView.snp.remakeConstraints { make in
make.edges.equalTo(self.locationContainer).inset(UIEdgeInsets(equalInset: URLBarViewUX.TextFieldBorderWidth))
}
}
}
@objc func showQRScanner() {
self.delegate?.urlBarDidPressQRButton(self)
}
func createLocationTextField() {
guard locationTextField == nil else { return }
locationTextField = ToolbarTextField()
guard let locationTextField = locationTextField else { return }
locationTextField.clipsToBounds = true
locationTextField.translatesAutoresizingMaskIntoConstraints = false
locationTextField.autocompleteDelegate = self
locationTextField.keyboardType = .webSearch
locationTextField.autocorrectionType = .no
locationTextField.autocapitalizationType = .none
locationTextField.returnKeyType = .go
locationTextField.clearButtonMode = .whileEditing
locationTextField.textAlignment = .left
locationTextField.font = UIConstants.DefaultChromeFont
locationTextField.accessibilityIdentifier = "address"
locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationTextField.attributedPlaceholder = self.locationView.placeholder
locationContainer.addSubview(locationTextField)
locationTextField.snp.remakeConstraints { make in
make.edges.equalTo(self.locationView)
}
locationTextField.applyTheme()
locationTextField.backgroundColor = UIColor.theme.textField.backgroundInOverlay
}
override func becomeFirstResponder() -> Bool {
return self.locationTextField?.becomeFirstResponder() ?? false
}
func removeLocationTextField() {
locationTextField?.removeFromSuperview()
locationTextField = nil
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(_ shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
// when we transition from portrait to landscape, calling this here causes
// the constraints to be calculated too early and there are constraint errors
if !toolbarIsShowing {
updateConstraintsIfNeeded()
}
updateViewsForOverlayModeAndToolbarChanges()
}
func updateAlphaForSubviews(_ alpha: CGFloat) {
locationContainer.alpha = alpha
self.alpha = alpha
}
func updateProgressBar(_ progress: Float) {
progressBar.alpha = 1
progressBar.isHidden = false
progressBar.setProgress(progress, animated: !isTransitioning)
}
func hideProgressBar() {
progressBar.isHidden = true
progressBar.setProgress(0, animated: false)
}
func updateReaderModeState(_ state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(_ suggestion: String?) {
locationTextField?.setAutocompleteSuggestion(suggestion)
}
func setLocation(_ location: String?, search: Bool) {
guard let text = location, !text.isEmpty else {
locationTextField?.text = location
return
}
if search {
locationTextField?.text = text
// Not notifying when empty agrees with AutocompleteTextField.textDidChange.
delegate?.urlBar(self, didRestoreText: text)
} else {
locationTextField?.setTextWithoutSearching(text)
}
}
func enterOverlayMode(_ locationText: String?, pasted: Bool, search: Bool) {
createLocationTextField()
// Show the overlay mode UI, which includes hiding the locationView and replacing it
// with the editable locationTextField.
animateToOverlayState(overlayMode: true)
delegate?.urlBarDidEnterOverlayMode(self)
applyTheme()
// Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens
// won't take the initial frame of the label into consideration, which makes the label
// look squished at the start of the animation and expand to be correct. As a workaround,
// we becomeFirstResponder as the next event on UI thread, so the animation starts before we
// set a first responder.
if pasted {
// Clear any existing text, focus the field, then set the actual pasted text.
// This avoids highlighting all of the text.
self.locationTextField?.text = ""
DispatchQueue.main.async {
self.locationTextField?.becomeFirstResponder()
self.setLocation(locationText, search: search)
}
} else {
DispatchQueue.main.async {
self.locationTextField?.becomeFirstResponder()
// Need to set location again so text could be immediately selected.
self.setLocation(locationText, search: search)
self.locationTextField?.selectAll(nil)
}
}
}
func leaveOverlayMode(didCancel cancel: Bool = false) {
locationTextField?.resignFirstResponder()
animateToOverlayState(overlayMode: false, didCancel: cancel)
delegate?.urlBarDidLeaveOverlayMode(self)
applyTheme()
}
func prepareOverlayAnimation() {
// Make sure everything is showing during the transition (we'll hide it afterwards).
bringSubviewToFront(self.locationContainer)
cancelButton.isHidden = false
showQRScannerButton.isHidden = false
progressBar.isHidden = false
menuButton.isHidden = !toolbarIsShowing
libraryButton.isHidden = !toolbarIsShowing || !topTabsIsShowing
forwardButton.isHidden = !toolbarIsShowing
backButton.isHidden = !toolbarIsShowing
tabsButton.isHidden = !toolbarIsShowing || topTabsIsShowing
stopReloadButton.isHidden = !toolbarIsShowing
}
func transitionToOverlay(_ didCancel: Bool = false) {
locationView.contentView.alpha = inOverlayMode ? 0 : 1
cancelButton.alpha = inOverlayMode ? 1 : 0
showQRScannerButton.alpha = inOverlayMode ? 1 : 0
progressBar.alpha = inOverlayMode || didCancel ? 0 : 1
tabsButton.alpha = inOverlayMode ? 0 : 1
menuButton.alpha = inOverlayMode ? 0 : 1
libraryButton.alpha = inOverlayMode ? 0 : 1
forwardButton.alpha = inOverlayMode ? 0 : 1
backButton.alpha = inOverlayMode ? 0 : 1
stopReloadButton.alpha = inOverlayMode ? 0 : 1
let borderColor = inOverlayMode ? locationActiveBorderColor : locationBorderColor
locationContainer.layer.borderColor = borderColor.cgColor
if inOverlayMode {
line.isHidden = inOverlayMode
// Make the editable text field span the entire URL bar, covering the lock and reader icons.
locationTextField?.snp.remakeConstraints { make in
make.edges.equalTo(self.locationView)
}
} else {
// Shrink the editable text field back to the size of the location view before hiding it.
locationTextField?.snp.remakeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
}
func updateViewsForOverlayModeAndToolbarChanges() {
// This ensures these can't be selected as an accessibility element when in the overlay mode.
locationView.overrideAccessibility(enabled: !inOverlayMode)
cancelButton.isHidden = !inOverlayMode
showQRScannerButton.isHidden = !inOverlayMode
progressBar.isHidden = inOverlayMode
menuButton.isHidden = !toolbarIsShowing || inOverlayMode
libraryButton.isHidden = !toolbarIsShowing || inOverlayMode || !topTabsIsShowing
forwardButton.isHidden = !toolbarIsShowing || inOverlayMode
backButton.isHidden = !toolbarIsShowing || inOverlayMode
tabsButton.isHidden = !toolbarIsShowing || inOverlayMode || topTabsIsShowing
stopReloadButton.isHidden = !toolbarIsShowing || inOverlayMode
// badge isHidden is tied to private mode on/off, use alpha to hide in this case
[privateModeBadge, hideImagesBadge].forEach {
$0.badge.alpha = (!toolbarIsShowing || inOverlayMode) ? 0 : 1
$0.backdrop.alpha = (!toolbarIsShowing || inOverlayMode) ? 0 : BadgeWithBackdrop.backdropAlpha
}
}
func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) {
prepareOverlayAnimation()
layoutIfNeeded()
inOverlayMode = overlay
if !overlay {
removeLocationTextField()
}
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: {
self.transitionToOverlay(cancel)
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
}, completion: { _ in
self.updateViewsForOverlayModeAndToolbarChanges()
})
}
func didClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
@objc func didClickCancel() {
leaveOverlayMode(didCancel: true)
}
@objc func tappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: TabToolbarProtocol {
func privateModeBadge(visible: Bool) {
if UIDevice.current.userInterfaceIdiom != .pad {
privateModeBadge.show(visible)
}
}
func hideImagesBadge(visible: Bool) {
hideImagesBadge.show(visible)
}
func updateBackStatus(_ canGoBack: Bool) {
backButton.isEnabled = canGoBack
}
func updateForwardStatus(_ canGoForward: Bool) {
forwardButton.isEnabled = canGoForward
}
func updateTabCount(_ count: Int, animated: Bool = true) {
tabsButton.updateTabCount(count, animated: animated)
}
func updateReloadStatus(_ isLoading: Bool) {
helper?.updateReloadStatus(isLoading)
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, for: .normal)
} else {
stopReloadButton.setImage(helper?.ImageReload, for: .normal)
}
}
func updatePageStatus(_ isWebPage: Bool) {
stopReloadButton.isEnabled = isWebPage
}
var access: [Any]? {
get {
if inOverlayMode {
guard let locationTextField = locationTextField else { return nil }
return [locationTextField, cancelButton]
} else {
if toolbarIsShowing {
return [backButton, forwardButton, stopReloadButton, locationView, tabsButton, libraryButton, menuButton, progressBar]
} else {
return [locationView, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: TabLocationViewDelegate {
func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView) {
guard let (locationText, isSearchQuery) = delegate?.urlBarDisplayTextForURL(locationView.url as URL?) else { return }
var overlayText = locationText
// Make sure to use the result from urlBarDisplayTextForURL as it is responsible for extracting out search terms when on a search page
if let text = locationText, let url = URL(string: text), let host = url.host, AppConstants.MOZ_PUNYCODE {
overlayText = url.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8())
}
enterOverlayMode(overlayText, pasted: false, search: isSearchQuery)
}
func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func tabLocationViewDidTapReload(_ tabLocationView: TabLocationView) {
delegate?.urlBarDidPressReload(self)
}
func tabLocationViewDidTapStop(_ tabLocationView: TabLocationView) {
delegate?.urlBarDidPressStop(self)
}
func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func tabLocationViewDidTapPageOptions(_ tabLocationView: TabLocationView, from button: UIButton) {
delegate?.urlBarDidPressPageOptions(self, from: tabLocationView.pageOptionsButton)
}
func tabLocationViewDidLongPressPageOptions(_ tabLocationView: TabLocationView) {
delegate?.urlBarDidLongPressPageOptions(self, from: tabLocationView.pageOptionsButton)
}
func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
func tabLocationViewDidBeginDragInteraction(_ tabLocationView: TabLocationView) {
delegate?.urlBarDidBeginDragInteraction(self)
}
func tabLocationViewDidTapShield(_ tabLocationView: TabLocationView) {
delegate?.urlBarDidTapShield(self, from: tabLocationView.trackingProtectionButton)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool {
guard let text = locationTextField?.text else { return true }
if !text.trimmingCharacters(in: .whitespaces).isEmpty {
delegate?.urlBar(self, didSubmitText: text)
return true
} else {
return false
}
}
func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
func autocompleteTextFieldDidCancel(_ autocompleteTextField: AutocompleteTextField) {
leaveOverlayMode(didCancel: true)
}
func autocompletePasteAndGo(_ autocompleteTextField: AutocompleteTextField) {
if let pasteboardContents = UIPasteboard.general.string {
self.delegate?.urlBar(self, didSubmitText: pasteboardContents)
}
}
}
// MARK: UIAppearance
extension URLBarView {
@objc dynamic var cancelTintColor: UIColor? {
get { return cancelButton.tintColor }
set { return cancelButton.tintColor = newValue }
}
@objc dynamic var showQRButtonTintColor: UIColor? {
get { return showQRScannerButton.tintColor }
set { return showQRScannerButton.tintColor = newValue }
}
}
extension URLBarView: Themeable {
func applyTheme() {
locationView.applyTheme()
locationTextField?.applyTheme()
actionButtons.forEach { $0.applyTheme() }
tabsButton.applyTheme()
cancelTintColor = UIColor.theme.browser.tint
showQRButtonTintColor = UIColor.theme.browser.tint
backgroundColor = UIColor.theme.browser.background
line.backgroundColor = UIColor.theme.browser.urlBarDivider
locationBorderColor = UIColor.theme.urlbar.border
locationView.backgroundColor = inOverlayMode ? UIColor.theme.textField.backgroundInOverlay : UIColor.theme.textField.background
locationContainer.backgroundColor = UIColor.theme.textField.background
privateModeBadge.badge.tintBackground(color: UIColor.theme.browser.background)
hideImagesBadge.badge.tintBackground(color: UIColor.theme.browser.background)
}
}
extension URLBarView: PrivateModeUI {
func applyUIMode(isPrivate: Bool) {
if UIDevice.current.userInterfaceIdiom != .pad {
privateModeBadge.show(isPrivate)
}
locationActiveBorderColor = UIColor.theme.urlbar.activeBorder(isPrivate)
progressBar.setGradientColors(startColor: UIColor.theme.loadingBar.start(isPrivate), endColor: UIColor.theme.loadingBar.end(isPrivate))
ToolbarTextField.applyUIMode(isPrivate: isPrivate)
applyTheme()
}
}
// We need a subclass so we can setup the shadows correctly
// This subclass creates a strong shadow on the URLBar
class TabLocationContainerView: UIView {
private struct LocationContainerUX {
static let CornerRadius: CGFloat = 8
}
override init(frame: CGRect) {
super.init(frame: frame)
let layer = self.layer
layer.cornerRadius = LocationContainerUX.CornerRadius
layer.masksToBounds = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ToolbarTextField: AutocompleteTextField {
@objc dynamic var clearButtonTintColor: UIColor? {
didSet {
// Clear previous tinted image that's cache and ask for a relayout
tintedClearImage = nil
setNeedsLayout()
}
}
fileprivate var tintedClearImage: UIImage?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
guard let image = UIImage.templateImageNamed("topTabs-closeTabs") else { return }
if tintedClearImage == nil {
if let clearButtonTintColor = clearButtonTintColor {
tintedClearImage = image.tinted(withColor: clearButtonTintColor)
} else {
tintedClearImage = image
}
}
// Since we're unable to change the tint color of the clear image, we need to iterate through the
// subviews, find the clear button, and tint it ourselves.
// https://stackoverflow.com/questions/55046917/clear-button-on-text-field-not-accessible-with-voice-over-swift
if let clearButton = value(forKey: "_clearButton") as? UIButton {
clearButton.setImage(tintedClearImage, for: [])
}
}
// The default button size is 19x19, make this larger
override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
let r = super.clearButtonRect(forBounds: bounds)
let grow: CGFloat = 16
let r2 = CGRect(x: r.minX - grow/2, y:r.minY - grow/2, width: r.width + grow, height: r.height + grow)
return r2
}
}
extension ToolbarTextField: Themeable {
func applyTheme() {
backgroundColor = UIColor.theme.textField.backgroundInOverlay
textColor = UIColor.theme.textField.textAndTint
clearButtonTintColor = textColor
tintColor = AutocompleteTextField.textSelectionColor.textFieldMode
}
// ToolbarTextField is created on-demand, so the textSelectionColor is a static prop for use when created
static func applyUIMode(isPrivate: Bool) {
textSelectionColor = UIColor.theme.urlbar.textSelectionHighlight(isPrivate)
}
}
|
mpl-2.0
|
d179e40c9be2c5b2a961ea4e4b362931
| 38.807416 | 198 | 0.678927 | 5.553905 | false | false | false | false |
rgcottrell/ReactiveStreams
|
Examples/Sources/Unicast/SyncSubscriber.swift
|
1
|
4625
|
/*
* Copyright 2016 Robert Cottrell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import ReactiveStreams
/// This is an implementation of Reactive Streams `Subscriber`. It runs
/// synchronously (on the publisher's thread) and requests one element
/// at a time and invokes a user defined method to process each element.
public class SyncSubscriber<Element> : Subscriber {
public typealias SubscribeType = Element
/// The subscription returned when subscribing to the publisher.
/// Obeying rule 3.1, we make this private.
private var subscription: Subscription?
/// Indicates whether we are done processing elements.
private var done = false
/// This will be called for each element emitted by the processor.
/// - parameter element: The element emitted by the publisher.
/// - returns: Whether more elements are desired or not.
private let whenNext: (Element) throws -> Bool
/// Create a new instance of `SyncSubscriber`.
///
/// - parameter whenNext: The function to process each element received
/// from the publisher and to indicate whether more elements are
/// desired.
public init(whenNext: (Element) throws -> Bool) {
self.whenNext = whenNext
}
public func onSubscribe(subscription: Subscription) {
// If someone has made a mistake and added this Subscriber multiple
// times, let's handle it gracefully.
guard self.subscription == nil else {
subscription.cancel()
return
}
// We have to assign it locally before we used it, if we want to be a
// synchronous `Subscriber`. According to rule 3.10, the subscription
// is allowed to call `onNext(element:)` synchronously from within
// `request(count:)`.
self.subscription = subscription
// If we want elements, according to rule 2.1 we need to call
// `request(count:)`. And, according to rule 3.2 we are allowed to
// call this synchronously from within the `onSubscribe(subscription:)`
// method.
subscription.request(count: 1)
}
public func onNext(element: Element) {
assert(subscription != nil, "Publisher violated the Reactive Streams rule 1.09 by signaling onNext prior to onSubscribe")
guard !done else {
return
}
do {
if try whenNext(element) {
subscription?.request(count: 1)
} else {
finish()
}
} catch {
finish()
onError(error: error)
}
}
public func onError(error: ErrorProtocol) {
assert(subscription != nil, "Publisher violated the Reactive Streams rule 1.09 by signaling onComplete prior to onSubscribe")
// As per rule 2.3, we are not allowed to call any methods on the
// `Subscription` or `Publisher`.
//
// As per rule 2.4, the `Subscription` should be considered canceled
// if this method is called.
subscription = nil
}
public func onComplete() {
assert(subscription != nil, "Publisher violated the Reactive Streams rule 1.09 by signaling onComplete prior to onSubscribe")
// As per rule 2.3, we are not allowed to call any methods on the
// `Subscription` or `Publisher`.
//
// As per rule 2.4, the `Subscription` should be considered canceled
// if this method is called.
subscription = nil
}
/// Showcases a convenience method to idempotently mark the `Subscriber`
/// as "done" so no more elements are processed. This also cancels the
/// subscription.
private func finish() {
// As per rule 3.7, calls to `Subscription.cancel()` are idempotent,
// so the guard is not needed.
guard !done else {
return
}
done = true
subscription?.cancel()
// The `Subscription` is no longer needed.
subscription = nil
}
}
|
apache-2.0
|
20b5b8472abb0b1a41ddd474d670327c
| 36.306452 | 133 | 0.634378 | 4.883844 | false | false | false | false |
wcharysz/BJSS-iOS-basket-assignment-source-code
|
ShoppingList/ExternalLibraries/ObjectMapper/Map.swift
|
2
|
2784
|
//
// Map.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-10-09.
// Copyright © 2015 hearst. All rights reserved.
//
import Foundation
/// A class used for holding mapping data
public final class Map {
public let mappingType: MappingType
var JSONDictionary: [String : AnyObject] = [:]
var currentValue: AnyObject?
var currentKey: String?
var keyIsNested = false
/// Counter for failing cases of deserializing values to `let` properties.
private var failedCount: Int = 0
public init(mappingType: MappingType, JSONDictionary: [String : AnyObject]) {
self.mappingType = mappingType
self.JSONDictionary = JSONDictionary
}
/// Sets the current mapper value and key.
/// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
public subscript(key: String) -> Map {
// save key and value associated to it
return self[key, nested: true]
}
public subscript(key: String, nested nested: Bool) -> Map {
// save key and value associated to it
currentKey = key
keyIsNested = nested
// check if a value exists for the current key
if nested == false {
currentValue = JSONDictionary[key]
} else {
// break down the components of the key that are separated by .
currentValue = valueFor(ArraySlice(key.componentsSeparatedByString(".")), dictionary: JSONDictionary)
}
return self
}
// MARK: Immutable Mapping
public func value<T>() -> T? {
return currentValue as? T
}
public func valueOr<T>(@autoclosure defaultValue: () -> T) -> T {
return value() ?? defaultValue()
}
/// Returns current JSON value of type `T` if it is existing, or returns a
/// unusable proxy value for `T` and collects failed count.
public func valueOrFail<T>() -> T {
if let value: T = value() {
return value
} else {
// Collects failed count
failedCount++
// Returns dummy memory as a proxy for type `T`
let pointer = UnsafeMutablePointer<T>.alloc(0)
pointer.dealloc(0)
return pointer.memory
}
}
/// Returns whether the receiver is success or failure.
public var isValid: Bool {
return failedCount == 0
}
}
/// Fetch value from JSON dictionary, loop through them until we reach the desired object.
private func valueFor(keyPathComponents: ArraySlice<String>, dictionary: [String : AnyObject]) -> AnyObject? {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return nil
}
if let object: AnyObject = dictionary[keyPathComponents.first!] {
if object is NSNull {
return nil
} else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
} else {
return object
}
}
return nil
}
|
apache-2.0
|
23fa3a745b6172baba65b83ea82ffeac
| 26.029126 | 110 | 0.698527 | 3.849239 | false | false | false | false |
ps2/rileylink_ios
|
OmniKit/OmnipodCommon/PodInsulinMeasurements.swift
|
1
|
1341
|
//
// PodInsulinMeasurements.swift
// OmniKit
//
// Created by Pete Schwamb on 9/5/18.
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import Foundation
public struct PodInsulinMeasurements: RawRepresentable, Equatable {
public typealias RawValue = [String: Any]
public let validTime: Date
public let delivered: Double
public let reservoirLevel: Double?
public init(insulinDelivered: Double, reservoirLevel: Double?, validTime: Date) {
self.validTime = validTime
self.delivered = insulinDelivered
self.reservoirLevel = reservoirLevel
}
// RawRepresentable
public init?(rawValue: RawValue) {
guard
let validTime = rawValue["validTime"] as? Date,
let delivered = rawValue["delivered"] as? Double
else {
return nil
}
self.validTime = validTime
self.delivered = delivered
self.reservoirLevel = rawValue["reservoirLevel"] as? Double
}
public var rawValue: RawValue {
var rawValue: RawValue = [
"validTime": validTime,
"delivered": delivered
]
if let reservoirLevel = reservoirLevel {
rawValue["reservoirLevel"] = reservoirLevel
}
return rawValue
}
}
|
mit
|
5facbf119f31858555b4d40c285dcb7a
| 25.8 | 85 | 0.610448 | 5.037594 | false | false | false | false |
QuarkX/Quark
|
Sources/Mustache/Common/Common.swift
|
1
|
6000
|
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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.
// =============================================================================
// MARK: - ContentType
/**
GRMustache distinguishes Text from HTML.
Content type applies to both *templates*, and *renderings*:
- In a HTML template, `{{name}}` tags escape Text renderings, but do not escape
HTML renderings.
- In a Text template, `{{name}}` tags do not escape anything.
The content type of a template comes from `Configuration.contentType` or
`{{% CONTENT_TYPE:... }}` pragma tags. See the documentation of
`Configuration.contentType` for a full discussion.
The content type of rendering is discussed with the `Rendering` type.
See also:
- Configuration.contentType
- Rendering
*/
public enum ContentType {
case Text
case HTML
}
// =============================================================================
// MARK: - Errors
/// The errors thrown by Mustache.swift
public struct MustacheError: Error {
/// MustacheError types
public enum Kind : Int {
case TemplateNotFound
case ParseError
case RenderError
}
/// The error type
public let kind: Kind
/// Eventual error message
public let message: String?
/// TemplateID of the eventual template at the origin of the error
public let templateID: String?
/// Eventual line number where the error occurred.
public let lineNumber: Int?
/// Eventual underlying error
public let underlyingError: Error?
// Not public
public init(kind: Kind, message: String? = nil, templateID: TemplateID? = nil, lineNumber: Int? = nil, underlyingError: Error? = nil) {
self.kind = kind
self.message = message
self.templateID = templateID
self.lineNumber = lineNumber
self.underlyingError = underlyingError
}
func errorWith(message: String? = nil, templateID: TemplateID? = nil, lineNumber: Int? = nil, underlyingError: Error? = nil) -> MustacheError {
return MustacheError(
kind: self.kind,
message: message ?? self.message,
templateID: templateID ?? self.templateID,
lineNumber: lineNumber ?? self.lineNumber,
underlyingError: underlyingError ?? self.underlyingError)
}
}
extension MustacheError : CustomStringConvertible {
var locationDescription: String? {
if let templateID = templateID {
if let lineNumber = lineNumber {
return "line \(lineNumber) of template \(templateID)"
} else {
return "template \(templateID)"
}
} else {
if let lineNumber = lineNumber {
return "line \(lineNumber)"
} else {
return nil
}
}
}
/// A textual representation of `self`.
public var description: String {
var description: String
switch kind {
case .TemplateNotFound:
description = ""
case .ParseError:
if let locationDescription = locationDescription {
description = "Parse error at \(locationDescription)"
} else {
description = "Parse error"
}
case .RenderError:
if let locationDescription = locationDescription {
description = "Rendering error at \(locationDescription)"
} else {
description = "Rendering error"
}
}
if let message = message {
if description.characters.count > 0 {
description += ": \(message)"
} else {
description = message
}
}
if let underlyingError = underlyingError {
description += " (\(underlyingError))"
}
return description
}
}
// =============================================================================
// MARK: - Tag delimiters
/**
A pair of tag delimiters, such as `("{{", "}}")`.
:see Configuration.tagDelimiterPair
:see Tag.tagDelimiterPair
*/
public typealias TagDelimiterPair = (String, String)
// =============================================================================
// MARK: - HTML escaping
/**
HTML-escapes a string by replacing `<`, `> `, `&`, `'` and `"` with HTML entities.
- parameter string: A string.
- returns: The HTML-escaped string.
*/
public func escapeHTML(_ string: String) -> String {
let escapeTable: [Character: String] = [
"<": "<",
">": ">",
"&": "&",
"'": "'",
"\"": """,
]
var escaped = ""
for c in string.characters {
if let escapedString = escapeTable[c] {
escaped += escapedString
} else {
escaped.append(c)
}
}
return escaped
}
|
mit
|
28f22e158e0c8dbf89a6a6d8a0908a65
| 29.607143 | 147 | 0.583097 | 5.10119 | false | false | false | false |
jopamer/swift
|
stdlib/public/core/LazySequence.swift
|
1
|
7723
|
//===--- LazySequence.swift -----------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A sequence on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Lazy sequences can be used to avoid needless storage allocation
/// and computation, because they use an underlying sequence for
/// storage and compute their elements on demand. For example,
///
/// [1, 2, 3].lazy.map { $0 * 2 }
///
/// is a sequence containing { `2`, `4`, `6` }. Each time an element
/// of the lazy sequence is accessed, an element of the underlying
/// array is accessed and transformed by the closure.
///
/// Sequence operations taking closure arguments, such as `map` and
/// `filter`, are normally eager: they use the closure immediately and
/// return a new array. Using the `lazy` property gives the standard
/// library explicit permission to store the closure and the sequence
/// in the result, and defer computation until it is needed.
///
/// To add new lazy sequence operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazySequenceProtocol`s. For example, given an eager `scan`
/// method defined as follows
///
/// extension Sequence {
/// /// Returns an array containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// (1..<6).scan(0, +) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(n)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: (ResultElement, Element) -> ResultElement
/// ) -> [ResultElement] {
/// var result = [initial]
/// for x in self {
/// result.append(nextPartialResult(result.last!, x))
/// }
/// return result
/// }
/// }
///
/// we can build a sequence that lazily computes the elements in the
/// result of `scan`:
///
/// struct LazyScanIterator<Base : IteratorProtocol, ResultElement>
/// : IteratorProtocol {
/// mutating func next() -> ResultElement? {
/// return nextElement.map { result in
/// nextElement = base.next().map { nextPartialResult(result, $0) }
/// return result
/// }
/// }
/// private var nextElement: ResultElement? // The next result of next().
/// private var base: Base // The underlying iterator.
/// private let nextPartialResult: (ResultElement, Base.Element) -> ResultElement
/// }
///
/// struct LazyScanSequence<Base: Sequence, ResultElement>
/// : LazySequenceProtocol // Chained operations on self are lazy, too
/// {
/// func makeIterator() -> LazyScanIterator<Base.Iterator, ResultElement> {
/// return LazyScanIterator(
/// nextElement: initial, base: base.makeIterator(), nextPartialResult)
/// }
/// private let initial: ResultElement
/// private let base: Base
/// private let nextPartialResult:
/// (ResultElement, Base.Element) -> ResultElement
/// }
///
/// and finally, we can give all lazy sequences a lazy `scan` method:
///
/// extension LazySequenceProtocol {
/// /// Returns a sequence containing the results of
/// ///
/// /// p.reduce(initial, nextPartialResult)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// Array((1..<6).lazy.scan(0, +)) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(1)
/// func scan<ResultElement>(
/// _ initial: ResultElement,
/// _ nextPartialResult: (ResultElement, Element) -> ResultElement
/// ) -> LazyScanSequence<Self, ResultElement> {
/// return LazyScanSequence(
/// initial: initial, base: self, nextPartialResult)
/// }
/// }
///
/// - See also: `LazySequence`, `LazyCollectionProtocol`, `LazyCollection`
///
/// - Note: The explicit permission to implement further operations
/// lazily applies only in contexts where the sequence is statically
/// known to conform to `LazySequenceProtocol`. Thus, side-effects such
/// as the accumulation of `result` below are never unexpectedly
/// dropped or deferred:
///
/// extension Sequence where Element == Int {
/// func sum() -> Int {
/// var result = 0
/// _ = self.map { result += $0 }
/// return result
/// }
/// }
///
/// [We don't recommend that you use `map` this way, because it
/// creates and discards an array. `sum` would be better implemented
/// using `reduce`].
public protocol LazySequenceProtocol : Sequence {
/// A `Sequence` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements: Sequence = Self where Elements.Element == Element
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing an extra
/// `LazySequence` layer. For example,
///
/// _prext_ example needed
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements { get }
}
/// When there's no special associated `Elements` type, the `elements`
/// property is provided.
extension LazySequenceProtocol where Elements == Self {
/// Identical to `self`.
@inlinable // protocol-only
public var elements: Self { return self }
}
extension LazySequenceProtocol {
@inlinable // protocol-only
public var lazy: LazySequence<Elements> {
return elements.lazy
}
}
extension LazySequenceProtocol where Elements: LazySequenceProtocol {
@inlinable // protocol-only
public var lazy: Elements {
return elements
}
}
/// A sequence containing the same elements as a `Base` sequence, but
/// on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`
@_fixed_layout // FIXME(sil-serialize-all)
public struct LazySequence<Base : Sequence>: _SequenceWrapper {
public var _base: Base
/// Creates a sequence that has the same elements as `base`, but on
/// which some operations such as `map` and `filter` are implemented
/// lazily.
@inlinable // FIXME(sil-serialize-all)
internal init(_base: Base) {
self._base = _base
}
}
extension LazySequence: LazySequenceProtocol {
public typealias Elements = Base
/// The `Base` (presumably non-lazy) sequence from which `self` was created.
@inlinable // FIXME(sil-serialize-all)
public var elements: Elements { return _base }
}
extension Sequence {
/// A sequence containing the same elements as this sequence,
/// but on which some operations, such as `map` and `filter`, are
/// implemented lazily.
@inlinable // protocol-only
public var lazy: LazySequence<Self> {
return LazySequence(_base: self)
}
}
|
apache-2.0
|
9d14dd4d9156c8cd9f5f4c6515f3c5cc
| 36.129808 | 87 | 0.62398 | 4.329036 | false | false | false | false |
huonw/swift
|
test/Interpreter/casts.swift
|
10
|
1589
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import StdlibUnittest
import Foundation
protocol P : class { }
protocol C : class { }
class Foo : NSObject {}
var Casts = TestSuite("Casts")
@inline(never)
func castit<ObjectType>(_ o: NSObject?, _ t: ObjectType.Type) -> ObjectType? {
return o as? ObjectType
}
@inline(never)
func castitExistential<ObjectType>(_ o: C?, _ t: ObjectType.Type) -> ObjectType? {
return o as? ObjectType
}
Casts.test("cast optional<nsobject> to protocol") {
if let obj = castit(nil, P.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<nsobject> to protocol meta") {
if let obj = castit(nil, P.Type.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to protocol") {
if let obj = castitExistential(nil, P.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to class") {
if let obj = castitExistential(nil, Foo.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to protocol meta") {
if let obj = castitExistential(nil, P.Type.self) {
expectUnreachable()
print("fail")
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to class meta") {
if let obj = castitExistential(nil, Foo.Type.self) {
expectUnreachable()
print("fail")
} else {
print("success")
}
}
runAllTests()
|
apache-2.0
|
32bc97c4c47943146a26b36aec454126
| 19.371795 | 82 | 0.650094 | 3.439394 | false | true | false | false |
huonw/swift
|
test/stdlib/IndexOfRenaming.swift
|
2
|
188
|
// RUN: %target-typecheck-verify-swift
let a = [10, 20, 30, 40, 50, 60]
_ = a.index(of: 30)
_ = a.firstIndex(of: 30)
_ = a.index(where: { $0 > 30 })
_ = a.firstIndex(where: { $0 > 30 })
|
apache-2.0
|
a0bf4766e11b6fbba3b87eb92c4d8473
| 22.5 | 38 | 0.547872 | 2.26506 | false | false | false | false |
networkextension/SFSocket
|
SFSocket/HTTPProxyServer/HTTPStreamScanner.swift
|
1
|
1687
|
import Foundation
class HTTPStreamScanner {
enum ReadAction {
case readHeader, readContent(Int), stop
}
var nextAction: ReadAction = .readHeader
var remainContentLength: Int = 0
var currentHeader: HTTPHeader!
var isConnect: Bool = false
func input(_ data: Data) -> (HTTPHeader?, Data?) {
switch nextAction {
case .readHeader:
guard let header = HTTPHeader(headerData: data) else {
nextAction = .stop
return (nil, nil)
}
if currentHeader == nil {
if header.isConnect {
isConnect = true
remainContentLength = -1
} else {
isConnect = false
remainContentLength = header.contentLength
}
} else {
remainContentLength = header.contentLength
}
currentHeader = header
setNextAction()
return (header, nil)
case .readContent:
remainContentLength -= data.count
if !isConnect && remainContentLength < 0 {
nextAction = .stop
return (nil, nil)
}
setNextAction()
return (nil, data)
case .stop:
return (nil, nil)
}
}
fileprivate func setNextAction() {
switch remainContentLength {
case 0:
nextAction = .readHeader
case -1:
nextAction = .readContent(-1)
default:
nextAction = .readContent(min(remainContentLength, Opt.MAXHTTPContentBlockLength))
}
}
}
|
bsd-3-clause
|
8189f256b94f4d5059d69773efab23f1
| 24.560606 | 94 | 0.510373 | 5.389776 | false | false | false | false |
Alua-Kinzhebayeva/iOS-PDF-Reader
|
Sources/Classes/TiledView.swift
|
1
|
3208
|
//
// TiledView.swift
// PDFReader
//
// Created by ALUA KINZHEBAYEVA on 4/22/15.
// Copyright (c) 2015 AK. All rights reserved.
//
import UIKit
import QuartzCore
extension Int {
var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
/// Tiled representation of a portion of a rendered pdf page
internal final class TiledView: UIView {
/// Page of the PDF to be tiled
private var leftPdfPage: CGPDFPage?
/// Current PDF scale
private let myScale: CGFloat
/// Initializes a fresh tiled view
///
/// - parameter frame: desired frame of the tiled view
/// - parameter scale: scale factor
/// - parameter newPage: new page representation
init(frame: CGRect, scale: CGFloat, newPage: CGPDFPage) {
myScale = scale
leftPdfPage = newPage
super.init(frame: frame)
// levelsOfDetail and levelsOfDetailBias determine how the layer is
// rendered at different zoom levels. This only matters while the view
// is zooming, because once the the view is done zooming a new TiledPDFView
// is created at the correct size and scale.
let tiledLayer = self.layer as? CATiledLayer
tiledLayer?.levelsOfDetail = 16
tiledLayer?.levelsOfDetailBias = 15
tiledLayer?.tileSize = CGSize(width: 1024, height: 1024)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override class var layerClass : AnyClass {
return CATiledLayer.self
}
// Draw the CGPDFPage into the layer at the correct scale.
override func draw(_ layer: CALayer, in con: CGContext) {
guard let leftPdfPage = leftPdfPage else { return }
// Fill the background with white.
con.setFillColor(red: 1, green: 1, blue: 1, alpha: 1)
con.fill(layer.bounds)
con.saveGState()
// Flip the context so that the PDF page is rendered right side up.
let rotationAngle: CGFloat
switch leftPdfPage.rotationAngle {
case 90:
rotationAngle = 270
con.translateBy(x: layer.bounds.width, y: layer.bounds.height)
case 180:
rotationAngle = 180
con.translateBy(x: 0, y: layer.bounds.height)
case 270:
rotationAngle = 90
con.translateBy(x: layer.bounds.width, y: layer.bounds.height)
default:
rotationAngle = 0
con.translateBy(x: 0, y: layer.bounds.height)
}
con.scaleBy(x: 1, y: -1)
con.rotate(by: rotationAngle.degreesToRadians)
// Scale the context so that the PDF page is rendered at the correct size for the zoom level.
con.scaleBy(x: myScale, y: myScale)
con.drawPDFPage(leftPdfPage)
con.restoreGState()
}
// Stops drawLayer
deinit {
leftPdfPage = nil
layer.contents = nil
layer.delegate = nil
layer.removeFromSuperlayer()
}
}
|
mit
|
8404a29783008c351177030f879e6e3e
| 31.08 | 101 | 0.620636 | 4.418733 | false | false | false | false |
karwa/swift-corelibs-foundation
|
Foundation/NSByteCountFormatter.swift
|
3
|
6411
|
// 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
//
public struct NSByteCountFormatterUnits : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
// This causes default units appropriate for the platform to be used. Specifying any units explicitly causes just those units to be used in showing the number.
public static let UseDefault = NSByteCountFormatterUnits(rawValue: 0)
// Specifying any of the following causes the specified units to be used in showing the number.
public static let UseBytes = NSByteCountFormatterUnits(rawValue: 1 << 0)
public static let UseKB = NSByteCountFormatterUnits(rawValue: 1 << 1)
public static let UseMB = NSByteCountFormatterUnits(rawValue: 1 << 2)
public static let UseGB = NSByteCountFormatterUnits(rawValue: 1 << 3)
public static let UseTB = NSByteCountFormatterUnits(rawValue: 1 << 4)
public static let UsePB = NSByteCountFormatterUnits(rawValue: 1 << 5)
public static let UseEB = NSByteCountFormatterUnits(rawValue: 1 << 6)
public static let UseZB = NSByteCountFormatterUnits(rawValue: 1 << 7)
public static let UseYBOrHigher = NSByteCountFormatterUnits(rawValue: 0x0FF << 8)
// Can use any unit in showing the number.
public static let UseAll = NSByteCountFormatterUnits(rawValue: 0x0FFFF)
}
public enum NSByteCountFormatterCountStyle : Int {
// Specifies display of file or storage byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the decimal style, but that may change over time.
case File
// Specifies display of memory byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the binary style, but that may change over time.
case Memory
// The following two allow specifying the number of bytes for KB explicitly. It's better to use one of the above values in most cases.
case Decimal // 1000 bytes are shown as 1 KB
case Binary // 1024 bytes are shown as 1 KB
}
public class NSByteCountFormatter : NSFormatter {
public override init() {
super.init()
}
public required init?(coder: NSCoder) {
NSUnimplemented()
}
/* Shortcut for converting a byte count into a string without creating an NSByteCountFormatter and an NSNumber. If you need to specify options other than countStyle, create an instance of NSByteCountFormatter first.
*/
public class func stringFromByteCount(_ byteCount: Int64, countStyle: NSByteCountFormatterCountStyle) -> String { NSUnimplemented() }
/* Convenience method on stringForObjectValue:. Convert a byte count into a string without creating an NSNumber.
*/
public func stringFromByteCount(_ byteCount: Int64) -> String { NSUnimplemented() }
/* Specify the units that can be used in the output. If NSByteCountFormatterUseDefault, uses platform-appropriate settings; otherwise will only use the specified units. This is the default value. Note that ZB and YB cannot be covered by the range of possible values, but you can still choose to use these units to get fractional display ("0.0035 ZB" for instance).
*/
public var allowedUnits: NSByteCountFormatterUnits = .UseDefault
/* Specify how the count is displayed by indicating the number of bytes to be used for kilobyte. The default setting is NSByteCountFormatterFileCount, which is the system specific value for file and storage sizes.
*/
public var countStyle: NSByteCountFormatterCountStyle = .File
/* Choose whether to allow more natural display of some values, such as zero, where it may be displayed as "Zero KB," ignoring all other flags or options (with the exception of NSByteCountFormatterUseBytes, which would generate "Zero bytes"). The result is appropriate for standalone output. Default value is YES. Special handling of certain values such as zero is especially important in some languages, so it's highly recommended that this property be left in its default state.
*/
public var allowsNonnumericFormatting: Bool = true
/* Choose whether to include the number or the units in the resulting formatted string. (For example, instead of 723 KB, returns "723" or "KB".) You can call the API twice to get both parts, separately. But note that putting them together yourself via string concatenation may be wrong for some locales; so use this functionality with care. Both of these values are YES by default. Setting both to NO will unsurprisingly result in an empty string.
*/
public var includesUnit: Bool = true
public var includesCount: Bool = true
/* Choose whether to parenthetically (localized as appropriate) display the actual number of bytes as well, for instance "723 KB (722,842 bytes)". This will happen only if needed, that is, the first part is already not showing the exact byte count. If includesUnit or includesCount are NO, then this setting has no effect. Default value is NO.
*/
public var includesActualByteCount: Bool = false
/* Choose the display style. The "adaptive" algorithm is platform specific and uses a different number of fraction digits based on the magnitude (in 10.8: 0 fraction digits for bytes and KB; 1 fraction digits for MB; 2 for GB and above). Otherwise the result always tries to show at least three significant digits, introducing fraction digits as necessary. Default is YES.
*/
public var adaptive: Bool = true
/* Choose whether to zero pad fraction digits so a consistent number of fraction digits are displayed, causing updating displays to remain more stable. For instance, if the adaptive algorithm is used, this option formats 1.19 and 1.2 GB as "1.19 GB" and "1.20 GB" respectively, while without the option the latter would be displayed as "1.2 GB". Default value is NO.
*/
public var zeroPadsFractionDigits: Bool = false
/* Specify the formatting context for the formatted string. Default is NSFormattingContextUnknown.
*/
public var formattingContext: NSFormattingContext = .Unknown
}
|
apache-2.0
|
5fa16c81f9851252cd45ac089e4e391a
| 68.684783 | 484 | 0.749493 | 4.805847 | false | false | false | false |
Pearapps/SampleTodoApp
|
frontend/frontend/TodoViewControllerFactory.swift
|
1
|
911
|
//
// ViewController.swift
// frontend
//
// Created by Kenneth Parker Ackerson on 8/30/16.
// Copyright © 2016 Kenneth Ackerson. All rights reserved.
//
import UIKit
struct TodoViewControllerFactory {
private let tableView: UITableView
init(tableView: UITableView) {
self.tableView = tableView
}
func viewController() -> UIViewController {
let viewController = UIViewController()
viewController.view.backgroundColor = .greenColor()
viewController.view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.heightAnchor.constraintEqualToAnchor(viewController.view.heightAnchor, multiplier: 1.0).active = true
tableView.widthAnchor.constraintEqualToAnchor(viewController.view.widthAnchor, multiplier: 1.0).active = true
return viewController
}
}
|
apache-2.0
|
8e0fb947f4e9e79e82e5a288efd0d5cf
| 29.333333 | 119 | 0.702198 | 5.481928 | false | false | false | false |
noehou/TWB
|
TWB/TWB/Classes/Main/Visitor/UserAccountViewModel.swift
|
1
|
1127
|
//
// UserAccountTool.swift
// TWB
//
// Created by Tommaso on 2017/5/12.
// Copyright © 2017年 Tommaso. All rights reserved.
//
import UIKit
class UserAccountViewModel {
//MARK:- 将类设计成单例
static let shareIntance : UserAccountViewModel = UserAccountViewModel()
//MARK:- 定义属性
var account : UserAccount?
//MARK:- 计算属性
var accountPath : String {
let accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
return (accountPath! as NSString).strings(byAppendingPaths: ["accout.plist"]).first!
}
var isLogin : Bool {
if account == nil {
return false
}
guard let expiresDate = account?.expires_date else {
return false
}
return expiresDate.compare(Date()) == ComparisonResult.orderedDescending
}
//MARK:- 重写init()函数
init() {
//1、从沙盒中读取归档的信息
account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? UserAccount
}
}
|
mit
|
b19f9007ecc3281062d1eb36246d24f1
| 24.190476 | 110 | 0.619093 | 4.723214 | false | false | false | false |
nnsnodnb/nowplaying-ios
|
NowPlaying/Sources/Routers/Setting/SettingRouter.swift
|
1
|
2163
|
//
// SettingRouter.swift
// NowPlaying
//
// Created by Yuya Oka on 2022/05/04.
//
import RxCocoa
import RxSwift
import UIKit
protocol SettingRoutable: Routable {
var dismiss: PublishRelay<Void> { get }
var twitter: PublishRelay<Void> { get }
var mastodon: PublishRelay<Void> { get }
var safari: PublishRelay<URL> { get }
var appStore: PublishRelay<Void> { get }
}
final class SettingRouter: SettingRoutable {
// MARK: - Properties
private(set) weak var viewController: UIViewController?
let dismiss: PublishRelay<Void> = .init()
let twitter: PublishRelay<Void> = .init()
let mastodon: PublishRelay<Void> = .init()
let safari: PublishRelay<URL> = .init()
let appStore: PublishRelay<Void> = .init()
private let disposeBag = DisposeBag()
// MARK: - Initialize
init() {
// 閉じる
dismiss.asSignal()
.emit(with: self, onNext: { strongSelf, _ in
strongSelf.viewController?.dismiss(animated: true)
})
.disposed(by: disposeBag)
// Twitter設定
twitter.asSignal()
.emit(with: self, onNext: { strongSelf, _ in
// TODO: 画面遷移
})
.disposed(by: disposeBag)
// Mastodon設定
mastodon.asSignal()
.emit(with: self, onNext: { strongSelf, _ in
// TODO: 画面遷移
})
.disposed(by: disposeBag)
// SFSafariViewController
safari.asSignal()
.emit(with: self, onNext: { strongSelf, url in
strongSelf.viewController?.presentSafariViewController(url: url)
})
.disposed(by: disposeBag)
// AppStore
appStore.asSignal()
.emit(with: self, onNext: { strongSelf, _ in
let url = URL(string: "\(URL.appStore.absoluteString)&action=write-review")!
strongSelf.viewController?.presentSafariViewController(url: url)
})
.disposed(by: disposeBag)
}
func inject(_ viewController: UIViewController) {
self.viewController = viewController
}
}
|
mit
|
5ad15aac58c866f7e166228094024686
| 29.471429 | 92 | 0.584623 | 4.519068 | false | false | false | false |
katsumeshi/PhotoInfo
|
PhotoInfo/Classes/Place.swift
|
1
|
1014
|
//
// Place.swift
// photoinfo
//
// Created by Yuki Matsushita on 11/9/15.
// Copyright © 2015 Yuki Matsushita. All rights reserved.
//
import Photos
class Place {
var address:String
var postalCode:String
init (_ placemark:CLPlacemark?){
postalCode = placemark?.getPostalCode() ?? "N/A"
address = placemark?.getAddress() ?? "N/A"
}
}
extension CLPlacemark {
func getPostalCode() -> String? {
return self.postalCode ?? nil
}
func getAddress() -> String? {
var address = String.empty
address += getMainAreaName()
address += getSubAreaName()
address += getLocalAreaName()
return address.isEmpty ? nil : address
}
private func getMainAreaName() -> String {
return administrativeArea ?? subAdministrativeArea ?? String.empty
}
private func getSubAreaName() -> String {
return locality ?? subLocality ?? String.empty
}
private func getLocalAreaName() -> String {
return thoroughfare ?? subThoroughfare ?? String.empty
}
}
|
mit
|
67c73839b59830c585a2c380dc917c82
| 21.043478 | 70 | 0.662389 | 4.134694 | false | false | false | false |
aucl/YandexDiskKit
|
TinyDisk/TinyDisk/ItemViewController.swift
|
1
|
6499
|
//
// ItemViewController.swift
//
// Copyright (c) 2014-2015, Clemens Auer
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
import YandexDiskKit
public class ItemViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var disk: YandexDisk!
var item: YandexDiskResource!
@IBOutlet var preview: UIImageView!
@IBOutlet var tableview: UITableView!
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public convenience init?(disk: YandexDisk, resource: YandexDiskResource) {
self.init(nibName: "ItemViewController", bundle: NSBundle(forClass: ItemViewController.self))
self.disk = disk
self.item = resource
title = item.name
}
private var bundle : NSBundle {
return NSBundle(forClass: DirectoryViewController.self)
}
override public func viewDidLoad() {
super.viewDidLoad()
if item.public_url != nil {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: Selector("action:"))
}
var image : UIImage!
if item.type == .Directory {
image = UIImage(named: "Folder_icon", inBundle:self.bundle, compatibleWithTraitCollection:nil)
} else {
image = UIImage(named: "File_icon", inBundle:self.bundle, compatibleWithTraitCollection:nil)
}
dispatch_async(dispatch_get_main_queue()) {
if let iv = self.preview {
iv.image = image
iv.setNeedsDisplay()
}
}
if let preview = item.preview {
disk.session.dataTaskWithURL(NSURL(string: preview)!) {
(data, response, error) -> Void in
let res = response as? NSHTTPURLResponse
let image = UIImage(data: data)
dispatch_async(dispatch_get_main_queue()) {
if let iv = self.preview {
iv.image = image
iv.setNeedsDisplay()
}
}
}.resume()
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func action(sender:AnyObject?) {
let activityItems = [ item.public_url! ]
let activityView = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityView.modalPresentationStyle = .Popover
if let popoverController = activityView.popoverPresentationController {
if let view = sender?.valueForKey("view") as? UIView {
popoverController.sourceView = view
popoverController.sourceRect = view.bounds
}
popoverController.permittedArrowDirections = .Any
}
presentViewController(activityView, animated: true) { }
}
// #pragma mark - Table view data source
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 11
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "TinyDiskItemCell"
var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellIdentifier)
}
var name : String?
var value : String?
switch indexPath.row {
case 0:
name = "Name";
value = item.name;
case 1:
name = "Type";
value = item.type == .Directory ? "directory" : item.mime_type
case 2:
name = "Size";
value = item.size != nil ? "\(item.size!) bytes" : "-"
case 3:
name = "M-Time"
value = "\(item.modified)"
case 4:
name = "C-Time"
value = "\(item.created)"
case 5:
name = "MD5"
value = item.md5 ?? "-"
case 6:
name = "Public URL"
value = item.public_url ?? "-"
case 7:
name = "Public key"
value = item.public_key ?? "-"
case 8:
name = "Origin path"
value = item.origin_path ?? "-"
case 9:
name = "MIME Type"
value = item.mime_type ?? "-"
case 10:
name = "Media Type"
value = item.media_type ?? "-"
default:
break;
}
cell.textLabel?.text = value
cell.detailTextLabel?.text = name
return cell
}
public func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
}
|
bsd-2-clause
|
94939cc4a7133c1f8ab5a1c2a90d8a38
| 33.205263 | 141 | 0.618864 | 4.987721 | false | false | false | false |
vishakhajadhav/CheckConnectivity
|
CheckConnectivity/CheckConnectivitySwift.swift
|
1
|
1519
|
//
// CheckConnectivitySwift.swift
// FIMS
//
// Created by Piyush Rathi on 23/01/17.
// Copyright © 2017 Kahuna Systems. All rights reserved.
//
import UIKit
//import sys/socket.h
//import netinet/in.h>
//#import <SystemConfiguration/SystemConfiguration.h>
public class CheckConnectivitySwift: NSObject {
public static let sharedInstance: CheckConnectivitySwift = {
let instance = CheckConnectivitySwift()
return instance
}()
override init() {
super.init()
}
/* =============================================================
// Connectivity testing code
=============================================================== */
public class func hasConnectivity() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}
|
mit
|
c88d58e7f24aa05922c7fd49b04f89c0
| 27.111111 | 82 | 0.59025 | 4.993421 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/RxSwift/RxSwift/Observables/Optional.swift
|
4
|
3256
|
//
// Optional.swift
// RxSwift
//
// Created by tarunon on 2016/12/13.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
public static func from(optional: E?) -> Observable<E> {
return ObservableOptional(optional: optional)
}
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- parameter scheduler: Scheduler to send the optional element on.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
public static func from(optional: E?, scheduler: ImmediateSchedulerType) -> Observable<E> {
return ObservableOptionalScheduled(optional: optional, scheduler: scheduler)
}
}
final private class ObservableOptionalScheduledSink<O: ObserverType>: Sink<O> {
typealias E = O.E
typealias Parent = ObservableOptionalScheduled<E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return self._parent._scheduler.schedule(self._parent._optional) { (optional: E?) -> Disposable in
if let next = optional {
self.forwardOn(.next(next))
return self._parent._scheduler.schedule(()) { _ in
self.forwardOn(.completed)
self.dispose()
return Disposables.create()
}
} else {
self.forwardOn(.completed)
self.dispose()
return Disposables.create()
}
}
}
}
final private class ObservableOptionalScheduled<E>: Producer<E> {
fileprivate let _optional: E?
fileprivate let _scheduler: ImmediateSchedulerType
init(optional: E?, scheduler: ImmediateSchedulerType) {
self._optional = optional
self._scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final private class ObservableOptional<E>: Producer<E> {
private let _optional: E?
init(optional: E?) {
self._optional = optional
}
override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
if let element = self._optional {
observer.on(.next(element))
}
observer.on(.completed)
return Disposables.create()
}
}
|
apache-2.0
|
103d1b3516a944a6c09a331e929acbe5
| 33.263158 | 139 | 0.643011 | 4.731105 | false | false | false | false |
rpistorello/rp-game-engine
|
rp-game-engine-src/Util/SKTUtils/CGPoint+Extensions.swift
|
4
|
6559
|
/*
* Copyright (c) 2013-2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import CoreGraphics
import SpriteKit
public extension CGPoint {
/**
* Creates a new CGPoint given a CGVector.
*/
public init(vector: CGVector) {
self.init(x: vector.dx, y: vector.dy)
}
/**
* Given an angle in radians, creates a vector of length 1.0 and returns the
* result as a new CGPoint. An angle of 0 is assumed to point to the right.
*/
public init(angle: CGFloat) {
self.init(x: cos(angle), y: sin(angle))
}
/**
* Adds (dx, dy) to the point.
*/
public mutating func offset(dx dx: CGFloat, dy: CGFloat) -> CGPoint {
x += dx
y += dy
return self
}
/**
* Returns the length (magnitude) of the vector described by the CGPoint.
*/
public func length() -> CGFloat {
return sqrt(x*x + y*y)
}
/**
* Returns the squared length of the vector described by the CGPoint.
*/
public func lengthSquared() -> CGFloat {
return x*x + y*y
}
/**
* Normalizes the vector described by the CGPoint to length 1.0 and returns
* the result as a new CGPoint.
*/
func normalized() -> CGPoint {
let len = length()
return len>0 ? self / len : CGPoint.zero
}
/**
* Normalizes the vector described by the CGPoint to length 1.0.
*/
public mutating func normalize() -> CGPoint {
self = normalized()
return self
}
/**
* Calculates the distance between two CGPoints. Pythagoras!
*/
public func distanceTo(point: CGPoint) -> CGFloat {
return (self - point).length()
}
/**
* Returns the angle in radians of the vector described by the CGPoint.
* The range of the angle is -π to π; an angle of 0 points to the right.
*/
public var angle: CGFloat {
return atan2(y, x)
}
}
/**
* Adds two CGPoint values and returns the result as a new CGPoint.
*/
public func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
/**
* Increments a CGPoint with the value of another.
*/
public func += (inout left: CGPoint, right: CGPoint) {
left = left + right
}
/**
* Adds a CGVector to this CGPoint and returns the result as a new CGPoint.
*/
public func + (left: CGPoint, right: CGVector) -> CGPoint {
return CGPoint(x: left.x + right.dx, y: left.y + right.dy)
}
/**
* Increments a CGPoint with the value of a CGVector.
*/
public func += (inout left: CGPoint, right: CGVector) {
left = left + right
}
/**
* Subtracts two CGPoint values and returns the result as a new CGPoint.
*/
public func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
/**
* Decrements a CGPoint with the value of another.
*/
public func -= (inout left: CGPoint, right: CGPoint) {
left = left - right
}
/**
* Subtracts a CGVector from a CGPoint and returns the result as a new CGPoint.
*/
public func - (left: CGPoint, right: CGVector) -> CGPoint {
return CGPoint(x: left.x - right.dx, y: left.y - right.dy)
}
/**
* Decrements a CGPoint with the value of a CGVector.
*/
public func -= (inout left: CGPoint, right: CGVector) {
left = left - right
}
/**
* Multiplies two CGPoint values and returns the result as a new CGPoint.
*/
public func * (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
/**
* Multiplies a CGPoint with another.
*/
public func *= (inout left: CGPoint, right: CGPoint) {
left = left * right
}
/**
* Multiplies the x and y fields of a CGPoint with the same scalar value and
* returns the result as a new CGPoint.
*/
public func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
/**
* Multiplies the x and y fields of a CGPoint with the same scalar value.
*/
public func *= (inout point: CGPoint, scalar: CGFloat) {
point = point * scalar
}
/**
* Multiplies a CGPoint with a CGVector and returns the result as a new CGPoint.
*/
public func * (left: CGPoint, right: CGVector) -> CGPoint {
return CGPoint(x: left.x * right.dx, y: left.y * right.dy)
}
/**
* Multiplies a CGPoint with a CGVector.
*/
public func *= (inout left: CGPoint, right: CGVector) {
left = left * right
}
/**
* Divides two CGPoint values and returns the result as a new CGPoint.
*/
public func / (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
/**
* Divides a CGPoint by another.
*/
public func /= (inout left: CGPoint, right: CGPoint) {
left = left / right
}
/**
* Divides the x and y fields of a CGPoint by the same scalar value and returns
* the result as a new CGPoint.
*/
public func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
/**
* Divides the x and y fields of a CGPoint by the same scalar value.
*/
public func /= (inout point: CGPoint, scalar: CGFloat) {
point = point / scalar
}
/**
* Divides a CGPoint by a CGVector and returns the result as a new CGPoint.
*/
public func / (left: CGPoint, right: CGVector) -> CGPoint {
return CGPoint(x: left.x / right.dx, y: left.y / right.dy)
}
/**
* Divides a CGPoint by a CGVector.
*/
public func /= (inout left: CGPoint, right: CGVector) {
left = left / right
}
/**
* Performs a linear interpolation between two CGPoint values.
*/
public func lerp(start start: CGPoint, end: CGPoint, t: CGFloat) -> CGPoint {
return start + (end - start) * t
}
|
mit
|
484827794478bc7e44bd14a7b87fc838
| 25.763265 | 80 | 0.667836 | 3.675448 | false | false | false | false |
sysatom/RubyChina-iOS
|
RubyChina/NodeTableViewController.swift
|
1
|
3792
|
//
// NodeTableViewController.swift
// RubyChina
//
// Created by yuan on 15/11/6.
// Copyright © 2015年 yuan. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import MBProgressHUD
class NodeTableViewController: UITableViewController {
// MARK: Properties
var nodes: JSON = []
override func viewDidLoad() {
super.viewDidLoad()
loadNodes()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadNodes() {
let progressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: false)
Provider.sharedProvider.request(.Nodes, completion: { (data, status, resonse, error) -> () in
if error == nil {
let json = JSON(data: data!)
let _nodes = json["nodes"]
if !_nodes.isEmpty {
self.nodes = json["nodes"]
print("nodes count: ", self.nodes.count)
self.tableView.reloadData()
progressHUD.hide(true)
} else {
progressHUD.labelText = "加载数据失败"
progressHUD.mode = .Text
progressHUD.hide(true, afterDelay: 2)
}
} else {
progressHUD.labelText = "网络错误"
progressHUD.mode = .Text
progressHUD.hide(true, afterDelay: 2)
print("request /nodes.josn error: ", error)
}
})
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nodes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("nodeCell", forIndexPath: indexPath)
let node = nodes[indexPath.row]
cell.accessoryType = .DisclosureIndicator
cell.textLabel?.text = node["name"].stringValue
cell.detailTextLabel?.text = "发贴数: " + node["topics_count"].stringValue
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let node_id = nodes[indexPath.row]["id"].stringValue
print("selected node_id: " + node_id)
let userDefaults = NSUserDefaults(suiteName: "group.sysatom.sharedDefaults")
userDefaults?.setObject(node_id, forKey: "node_id")
userDefaults?.synchronize()
// 发出更新广播
NSNotificationCenter.defaultCenter().postNotificationName("topicsUpdateData", object: nil)
dismissViewControllerAnimated(true, completion: nil)
}
/*
// 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.
}
*/
@IBAction func backHome(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func allNodes(sender: AnyObject) {
let userDefaults = NSUserDefaults(suiteName: "group.sysatom.sharedDefaults")
userDefaults?.removeObjectForKey("node_id")
userDefaults?.synchronize()
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
554b3bb6231c5196a118b75d3b01eee6
| 32.491071 | 118 | 0.619568 | 5.238827 | false | false | false | false |
nfls/nflsers
|
app/v2/Model/Blackboard/Blackboard.swift
|
1
|
705
|
//
// Blackboard.swift
// NFLSers-iOS
//
// Created by Qingyang Hu on 2018/8/11.
// Copyright © 2018 胡清阳. All rights reserved.
//
import Foundation
import ObjectMapper
class Blackboard: Model {
required init(map: Map) throws {
self.id = UUID(uuidString: try map.value("id"))!
self.title = try map.value("title")
self.announcement = try? map.value("announcement")
self.students = try? map.value("students")
self.teachers = try? map.value("teachers")
self.code = try? map.value("code")
}
let id: UUID
let title: String
let announcement: String?
let students: [User]?
let teachers: [User]?
let code: String?
}
|
apache-2.0
|
2c02481b9fe6672638ef4d3ca86e9c60
| 23.928571 | 58 | 0.620344 | 3.673684 | false | false | false | false |
luizlopezm/ios-Luis-Trucking
|
Pods/SwiftForms/SwiftForms/controllers/FormOptionsSelectorController.swift
|
1
|
5343
|
//
// FormOptionsSelectorController.swift
// SwiftForms
//
// Created by Miguel Ángel Ortuño Ortuño on 23/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormOptionsSelectorController: UITableViewController, FormSelector {
// MARK: FormSelector
public var formCell: FormBaseCell!
// MARK: Init
public init() {
super.init(style: .Grouped)
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = formCell.rowDescriptor.title
}
// MARK: UITableViewDataSource
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let options = formCell.rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as? NSArray {
return options.count
}
return 0
}
public override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = NSStringFromClass(self.dynamicType)
var cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: reuseIdentifier)
}
let options = formCell.rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as! NSArray
let optionValue = options[indexPath.row] as! NSObject
cell!.textLabel!.text = formCell.rowDescriptor.titleForOptionValue(optionValue)
if let selectedOptions = formCell.rowDescriptor.value as? [NSObject] {
if (selectedOptions.indexOf(optionValue as NSObject) != nil) {
if let checkMarkAccessoryView = formCell.rowDescriptor.configuration[FormRowDescriptor.Configuration.CheckmarkAccessoryView] as? UIView {
cell!.accessoryView = checkMarkAccessoryView
}
else {
cell!.accessoryType = .Checkmark
}
}
else {
cell!.accessoryType = .None
}
}
else if let selectedOption = formCell.rowDescriptor.value {
if optionValue == selectedOption {
cell!.accessoryType = .Checkmark
}
else {
cell!.accessoryType = .None
}
}
return cell!
}
// MARK: UITableViewDelegate
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
var allowsMultipleSelection = false
if let allowsMultipleSelectionValue = formCell.rowDescriptor.configuration[FormRowDescriptor.Configuration.AllowsMultipleSelection] as? Bool {
allowsMultipleSelection = allowsMultipleSelectionValue
}
let options = formCell.rowDescriptor.configuration[FormRowDescriptor.Configuration.Options] as! NSArray
let optionValue = options[indexPath.row] as! NSObject
if allowsMultipleSelection {
if formCell.rowDescriptor.value == nil {
formCell.rowDescriptor.value = NSMutableArray()
}
if let selectedOptions = formCell.rowDescriptor.value as? NSMutableArray {
if selectedOptions.containsObject(optionValue) {
selectedOptions.removeObject(optionValue)
cell?.accessoryType = .None
}
else {
selectedOptions.addObject(optionValue)
if let checkmarkAccessoryView = formCell.rowDescriptor.configuration[FormRowDescriptor.Configuration.CheckmarkAccessoryView] as? UIView {
cell?.accessoryView = checkmarkAccessoryView
}
else {
cell?.accessoryType = .Checkmark
}
}
if selectedOptions.count > 0 {
formCell.rowDescriptor.value = selectedOptions
}
else {
formCell.rowDescriptor.value = nil
}
}
}
else {
formCell.rowDescriptor.value = NSMutableArray(object: optionValue)
}
formCell.update()
if allowsMultipleSelection {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
else {
self.navigationController?.popViewControllerAnimated(true)
}
}
}
|
mit
|
0cc31963a9eaf916c0f99925be774fa6
| 34.593333 | 157 | 0.599176 | 6.281176 | false | true | false | false |
MaxHasADHD/TraktKit
|
Common/Wrapper/Resources/ExploreResource.swift
|
1
|
2186
|
//
// ExploreResource.swift
// TraktKit
//
// Created by Maxamilian Litteral on 6/14/21.
// Copyright © 2021 Maximilian Litteral. All rights reserved.
//
import Foundation
public struct ExploreResource {
public let traktManager: TraktManager
public lazy var trending = Trending(traktManager: traktManager)
public init(traktManager: TraktManager = .sharedManager) {
self.traktManager = traktManager
}
public struct Trending {
public let traktManager: TraktManager
public init(traktManager: TraktManager = .sharedManager) {
self.traktManager = traktManager
}
public func shows() -> Route<[TraktTrendingShow]> {
Route(path: "shows/trending", method: .GET, traktManager: traktManager)
}
public func movies() -> Route<[TraktTrendingMovie]> {
Route(path: "movies/trending", method: .GET, traktManager: traktManager)
}
}
public func trending(_ mediaType: MediaType) -> Route<[TraktTrendingShow]> {
Route(path: "\(mediaType)/trending", method: .GET, traktManager: traktManager)
}
public func popular(_ mediaType: MediaType) -> Route<[TraktShow]> {
Route(path: "\(mediaType)/popular", method: .GET, traktManager: traktManager)
}
public func recommended(_ mediaType: MediaType) -> Route<[TraktTrendingShow]> {
Route(path: "\(mediaType)/recommended", method: .GET, traktManager: traktManager)
}
public func played(_ mediaType: MediaType) -> Route<[TraktMostShow]> {
Route(path: "\(mediaType)/played", method: .GET, traktManager: traktManager)
}
public func watched(_ mediaType: MediaType) -> Route<[TraktMostShow]> {
Route(path: "\(mediaType)/watched", method: .GET, traktManager: traktManager)
}
public func collected(_ mediaType: MediaType) -> Route<[TraktTrendingShow]> {
Route(path: "\(mediaType)/collected", method: .GET, traktManager: traktManager)
}
public func anticipated(_ mediaType: MediaType) -> Route<[TraktAnticipatedShow]> {
Route(path: "\(mediaType)/anticipated", method: .GET, traktManager: traktManager)
}
}
|
mit
|
cb6505c70d0a357119a316221fbc4c8c
| 34.241935 | 89 | 0.659497 | 4.609705 | false | false | false | false |
yariksmirnov/Observable-Swift
|
Observable-Swift/ObservableChainingProxy.swift
|
8
|
4731
|
//
// Chaining.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 23/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
public class ObservableChainingProxy<O1: AnyObservable, O2: AnyObservable>: OwnableObservable {
public typealias ValueType = O2.ValueType?
public var value : ValueType { return nil }
internal weak var _beforeChange : EventReference<ValueChange<ValueType>>? = nil
internal weak var _afterChange : EventReference<ValueChange<ValueType>>? = nil
public var beforeChange : EventReference<ValueChange<ValueType>> {
if let event = _beforeChange {
return event
} else {
let event = OwningEventReference<ValueChange<ValueType>>()
event.owned = self
_beforeChange = event
return event
}
}
public var afterChange : EventReference<ValueChange<ValueType>> {
if let event = _afterChange {
return event
} else {
let event = OwningEventReference<ValueChange<ValueType>>()
event.owned = self
_afterChange = event
return event
}
}
internal let base: O1
internal let path: O1.ValueType -> O2?
private func targetChangeToValueChange(vc: ValueChange<O2.ValueType>) -> ValueChange<ValueType> {
let oldValue = Optional.Some(vc.oldValue)
let newValue = Optional.Some(vc.newValue)
return ValueChange(oldValue, newValue)
}
private func objectChangeToValueChange(oc: ValueChange<O1.ValueType>) -> ValueChange<ValueType> {
let oldValue = path(oc.oldValue)?.value
let newValue = path(oc.newValue)?.value
return ValueChange(oldValue, newValue)
}
init(base: O1, path: O1.ValueType -> O2?) {
self.base = base
self.path = path
let beforeSubscription = EventSubscription(owner: self) { [weak self] in
self!.beforeChange.notify(self!.targetChangeToValueChange($0))
}
let afterSubscription = EventSubscription(owner: self) { [weak self] in
self!.afterChange.notify(self!.targetChangeToValueChange($0))
}
base.beforeChange.add(owner: self) { [weak self] oc in
let oldTarget = path(oc.oldValue)
oldTarget?.beforeChange.remove(beforeSubscription)
oldTarget?.afterChange.remove(afterSubscription)
self!.beforeChange.notify(self!.objectChangeToValueChange(oc))
}
base.afterChange.add(owner: self) { [weak self] oc in
self!.afterChange.notify(self!.objectChangeToValueChange(oc))
let newTarget = path(oc.newValue)
newTarget?.beforeChange.add(beforeSubscription)
newTarget?.afterChange.add(afterSubscription)
}
}
public func to<O3: AnyObservable>(path f: O2.ValueType -> O3?) -> ObservableChainingProxy<ObservableChainingProxy<O1, O2>, O3> {
func cascadeNil(oOrNil: ValueType) -> O3? {
if let o = oOrNil {
return f(o)
} else {
return nil
}
}
return ObservableChainingProxy<ObservableChainingProxy<O1, O2>, O3>(base: self, path: cascadeNil)
}
public func to<O3: AnyObservable>(path f: O2.ValueType -> O3) -> ObservableChainingProxy<ObservableChainingProxy<O1, O2>, O3> {
func cascadeNil(oOrNil: ValueType) -> O3? {
if let o = oOrNil {
return f(o)
} else {
return nil
}
}
return ObservableChainingProxy<ObservableChainingProxy<O1, O2>, O3>(base: self, path: cascadeNil)
}
}
public struct ObservableChainingBase<O1: AnyObservable> {
internal let base: O1
public func to<O2: AnyObservable>(path: O1.ValueType -> O2?) -> ObservableChainingProxy<O1, O2> {
return ObservableChainingProxy(base: base, path: path)
}
public func to<O2: AnyObservable>(path: O1.ValueType -> O2) -> ObservableChainingProxy<O1, O2> {
return ObservableChainingProxy(base: base, path: { .Some(path($0)) })
}
}
public func chain<O: AnyObservable>(o: O) -> ObservableChainingBase<O> {
return ObservableChainingBase(base: o)
}
public func / <O1: AnyObservable, O2: AnyObservable, O3: AnyObservable> (o: ObservableChainingProxy<O1, O2>, f: O2.ValueType -> O3?) -> ObservableChainingProxy<ObservableChainingProxy<O1, O2>, O3> {
return o.to(path: f)
}
public func / <O1: AnyObservable, O2: AnyObservable> (o: O1, f: O1.ValueType -> O2?) -> ObservableChainingProxy<O1, O2> {
return ObservableChainingProxy(base: o, path: f)
}
|
mit
|
848775513f26987638dbb344e247fc38
| 36.5 | 198 | 0.628571 | 4.177719 | false | false | false | false |
mgmart/mobileorg
|
MobileOrgTests/WebDavTests.swift
|
1
|
5753
|
//
// WebDavTests.swift
// MobileOrg
//
// Created by Mario Martelli on 27.04.17.
// Copyright © 2017 Sean Escriva. All rights reserved.
//
import XCTest
import CoreData
@testable import MobileOrg
class WebDavTests: XCTestCase {
var moc:NSManagedObjectContext?
override func setUp() {
super.setUp()
let context = setUpInMemoryManagedObjectContext()
moc = context
PersistenceStack.shared.moc = moc!
Settings.instance().serverMode = ServerModeWebDav
Settings.instance().username = "schnuddelhuddel"
Settings.instance().password = "schnuddelhuddel"
Settings.instance().indexUrl = URL(string: "https://mobileOrgWebDav.schnuddelhuddel.de:32773/index.org")
Settings.instance().encryptionPassword = "SchnuddelHuddel"
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testWebDAVSync() {
let syncExpectation = expectation(description: "Sync")
SyncManager.instance().sync()
let dispatchTime = DispatchTime.now() + Double(4000000000) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter (deadline: dispatchTime,
execute: {
(Void) -> (Void) in
do {
let fetchRequest = NSFetchRequest<Node>(entityName: "Node")
// fetchRequest.predicate = NSPredicate (format: "heading == %@", "on Level 1.1.1.5")
let nodes = try self.moc!.fetch(fetchRequest)
syncExpectation.fulfill()
XCTAssertEqual(nodes.count, 136)
} catch _ { XCTFail() }
})
waitForExpectations(timeout: 4, handler: nil)
}
func testSyncChangesOnMobile() {
let syncExpectation = expectation(description: "Sync")
SyncManager.instance().sync()
let dispatchTime = DispatchTime.now() + Double(4000000000) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter (deadline: dispatchTime,
execute: {
(Void) -> (Void) in
do {
let fetchRequest = NSFetchRequest<Node>(entityName: "Node")
fetchRequest.predicate = NSPredicate (format: "heading == %@", "Seamless integration of Cloud services")
let nodes = try self.moc!.fetch(fetchRequest)
print(nodes.count)
// Make local changes and sync again
let tagEditController = TagEditController(node: nodes.first!)
tagEditController?.recentTagString = "Test456"
tagEditController?.commitNewTag()
Save()
SyncManager.instance().sync()
syncExpectation.fulfill()
XCTAssertEqual(nodes.first?.tags, ":Test456:")
} catch _ { XCTFail() }
})
waitForExpectations(timeout: 4, handler: nil)
}
func testSyncChangesOnMobileReverse() {
let syncExpectation = expectation(description: "Sync")
SyncManager.instance().sync()
let dispatchTime = DispatchTime.now() + Double(4000000000) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter (deadline: dispatchTime,
execute: {
(Void) -> (Void) in
do {
let fetchRequest = NSFetchRequest<Node>(entityName: "Node")
fetchRequest.predicate = NSPredicate (format: "heading == %@", "Seamless integration of Cloud services")
let nodes = try self.moc!.fetch(fetchRequest)
// Make local changes and sync again
let tagEditController = TagEditController(node: nodes.first!)
tagEditController?.recentTagString = ""
tagEditController?.commitNewTag()
Save()
SyncManager.instance().sync()
syncExpectation.fulfill()
XCTAssertEqual(nodes.first?.tags, "::")
} catch _ { XCTFail() }
})
waitForExpectations(timeout: 4, handler: nil)
}
func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
let path = Bundle.main.path(forResource: "MobileOrg2", ofType: "momd")
let momURL = URL.init(fileURLWithPath: path!)
let managedObjectModel = NSManagedObjectModel.init(contentsOf: momURL)
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel!)
try! persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}
}
|
gpl-2.0
|
15ef0d976bbc859e653d040aa51069ea
| 37.864865 | 142 | 0.529381 | 5.875383 | false | true | false | false |
bluepi0j/BPPopCardTransition
|
Source/BPPopCardTransitionsDelegate.swift
|
1
|
1485
|
//
// BPPopCardTransitionsDelegate.swift
// BPPopCardTransition
//
// Created by Vic on 2017-08-12.
// Copyright © 2017 bluepi0j. All rights reserved.
//
import Foundation
public final class BPPopCardTransitionsDelegate: NSObject, UIViewControllerTransitioningDelegate {
public weak var delegate: BPPopCardAnimtionDelegate?
// MARK:- UIViewControllerTransitioningDelegate
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let presentedAnimator: BPPopCardPresentingAnimationController = BPPopCardPresentingAnimationController()
presentedAnimator.delegate = delegate
return presentedAnimator
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let dismissedAnimator: BPPopCardDismissingAnimationController = BPPopCardDismissingAnimationController()
dismissedAnimator.delegate = delegate
return dismissedAnimator
}
public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let presentationController: BPPopCardPresentationController = BPPopCardPresentationController(presentedViewController: presented, presenting: presenting)
return presentationController
}
}
|
mit
|
8adedfca63437d0fb0542741aa4d0ca8
| 43.969697 | 177 | 0.78841 | 6.314894 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.