repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
paulofaria/swift-apex
|
Sources/Apex/POSIX/POSIX.swift
|
1
|
13551
|
#if os(Linux)
@_exported import Glibc
#else
@_exported import Darwin.C
#endif
public enum SystemError : Error {
case operationNotPermitted
case noSuchFileOrDirectory
case noSuchProcess
case interruptedSystemCall
case inputOutputError
case deviceNotConfigured
case argumentListTooLong
case executableFormatError
case badFileDescriptor
case noChildProcesses
case resourceDeadlockAvoided
case cannotAllocateMemory
case permissionDenied
case badAddress
case blockDeviceRequired
case deviceOrResourceBusy
case fileExists
case crossDeviceLink
case operationNotSupportedByDevice
case notADirectory
case isADirectory
case invalidArgument
case tooManyOpenFilesInSystem
case tooManyOpenFiles
case inappropriateInputOutputControlForDevice
case textFileBusy
case fileTooLarge
case noSpaceLeftOnDevice
case illegalSeek
case readOnlyFileSystem
case tooManyLinks
case brokenPipe
/* math software */
case numericalArgumentOutOfDomain
case resultTooLarge
/* non-blocking and interrupt i/o */
case resourceTemporarilyUnavailable
case operationWouldBlock
case operationNowInProgress
case operationAlreadyInProgress
/* ipc/network software -- argument errors */
case socketOperationOnNonSocket
case destinationAddressRequired
case messageTooLong
case protocolWrongTypeForSocket
case protocolNotAvailable
case protocolNotSupported
case socketTypeNotSupported
case operationNotSupported
case protocolFamilyNotSupported
case addressFamilyNotSupportedByProtocolFamily
case addressAlreadyInUse
case cannotAssignRequestedAddress
/* ipc/network software -- operational errors */
case networkIsDown
case networkIsUnreachable
case networkDroppedConnectionOnReset
case softwareCausedConnectionAbort
case connectionResetByPeer
case noBufferSpaceAvailable
case socketIsAlreadyConnected
case socketIsNotConnected
case cannotSendAfterSocketShutdown
case tooManyReferences
case operationTimedOut
case connectionRefused
case tooManyLevelsOfSymbolicLinks
case fileNameTooLong
case hostIsDown
case noRouteToHost
case directoryNotEmpty
/* quotas & mush */
case tooManyUsers
case diskQuotaExceeded
/* Network File System */
case staleFileHandle
case objectIsRemote
case noLocksAvailable
case functionNotImplemented
case valueTooLargeForDefinedDataType
case operationCanceled
case identifierRemoved
case noMessageOfDesiredType
case illegalByteSequence
case badMessage
case multihopAttempted
case noDataAvailable
case linkHasBeenSevered
case outOfStreamsResources
case deviceNotAStream
case protocolError
case timerExpired
case stateNotRecoverable
case previousOwnerDied
case other(errorNumber: Int32)
}
extension SystemError {
public init?(errorNumber: Int32) {
switch errorNumber {
case 0: return nil
case EPERM: self = .operationNotPermitted
case ENOENT: self = .noSuchFileOrDirectory
case ESRCH: self = .noSuchProcess
case EINTR: self = .interruptedSystemCall
case EIO: self = .inputOutputError
case ENXIO: self = .deviceNotConfigured
case E2BIG: self = .argumentListTooLong
case ENOEXEC: self = .executableFormatError
case EBADF: self = .badFileDescriptor
case ECHILD: self = .noChildProcesses
case EDEADLK: self = .resourceDeadlockAvoided
case ENOMEM: self = .cannotAllocateMemory
case EACCES: self = .permissionDenied
case EFAULT: self = .badAddress
case ENOTBLK: self = .blockDeviceRequired
case EBUSY: self = .deviceOrResourceBusy
case EEXIST: self = .fileExists
case EXDEV: self = .crossDeviceLink
case ENODEV: self = .operationNotSupportedByDevice
case ENOTDIR: self = .notADirectory
case EISDIR: self = .isADirectory
case EINVAL: self = .invalidArgument
case ENFILE: self = .tooManyOpenFilesInSystem
case EMFILE: self = .tooManyOpenFiles
case ENOTTY: self = .inappropriateInputOutputControlForDevice
case ETXTBSY: self = .textFileBusy
case EFBIG: self = .fileTooLarge
case ENOSPC: self = .noSpaceLeftOnDevice
case ESPIPE: self = .illegalSeek
case EROFS: self = .readOnlyFileSystem
case EMLINK: self = .tooManyLinks
case EPIPE: self = .brokenPipe
/* math software */
case EDOM: self = .numericalArgumentOutOfDomain
case ERANGE: self = .resultTooLarge
/* non-blocking and interrupt i/o */
case EAGAIN: self = .resourceTemporarilyUnavailable
case EWOULDBLOCK: self = .operationWouldBlock
case EINPROGRESS: self = .operationNowInProgress
case EALREADY: self = .operationAlreadyInProgress
/* ipc/network software -- argument errors */
case ENOTSOCK: self = .socketOperationOnNonSocket
case EDESTADDRREQ: self = .destinationAddressRequired
case EMSGSIZE: self = .messageTooLong
case EPROTOTYPE: self = .protocolWrongTypeForSocket
case ENOPROTOOPT: self = .protocolNotAvailable
case EPROTONOSUPPORT: self = .protocolNotSupported
case ESOCKTNOSUPPORT: self = .socketTypeNotSupported
case ENOTSUP: self = .operationNotSupported
case EPFNOSUPPORT: self = .protocolFamilyNotSupported
case EAFNOSUPPORT: self = .addressFamilyNotSupportedByProtocolFamily
case EADDRINUSE: self = .addressAlreadyInUse
case EADDRNOTAVAIL: self = .cannotAssignRequestedAddress
/* ipc/network software -- operational errors */
case ENETDOWN: self = .networkIsDown
case ENETUNREACH: self = .networkIsUnreachable
case ENETRESET: self = .networkDroppedConnectionOnReset
case ECONNABORTED: self = .softwareCausedConnectionAbort
case ECONNRESET: self = .connectionResetByPeer
case ENOBUFS: self = .noBufferSpaceAvailable
case EISCONN: self = .socketIsAlreadyConnected
case ENOTCONN: self = .socketIsNotConnected
case ESHUTDOWN: self = .cannotSendAfterSocketShutdown
case ETOOMANYREFS: self = .tooManyReferences
case ETIMEDOUT: self = .operationTimedOut
case ECONNREFUSED: self = .connectionRefused
case ELOOP: self = .tooManyLevelsOfSymbolicLinks
case ENAMETOOLONG: self = .fileNameTooLong
case EHOSTDOWN: self = .hostIsDown
case EHOSTUNREACH: self = .noRouteToHost
case ENOTEMPTY: self = .directoryNotEmpty
/* quotas & mush */
case EUSERS: self = .tooManyUsers
case EDQUOT: self = .diskQuotaExceeded
/* Network File System */
case ESTALE: self = .staleFileHandle
case EREMOTE: self = .objectIsRemote
case ENOLCK: self = .noLocksAvailable
case ENOSYS: self = .functionNotImplemented
case EOVERFLOW: self = .valueTooLargeForDefinedDataType
case ECANCELED: self = .operationCanceled
case EIDRM: self = .identifierRemoved
case ENOMSG: self = .noMessageOfDesiredType
case EILSEQ: self = .illegalByteSequence
case EBADMSG: self = .badMessage
case EMULTIHOP: self = .multihopAttempted
case ENODATA: self = .noDataAvailable
case ENOLINK: self = .linkHasBeenSevered
case ENOSR: self = .outOfStreamsResources
case ENOSTR: self = .deviceNotAStream
case EPROTO: self = .protocolError
case ETIME: self = .timerExpired
case ENOTRECOVERABLE: self = .stateNotRecoverable
case EOWNERDEAD: self = .previousOwnerDied
default: self = .other(errorNumber: errorNumber)
}
}
}
extension SystemError {
public var errorNumber: Int32 {
switch self {
case .operationNotPermitted: return EPERM
case .noSuchFileOrDirectory: return ENOENT
case .noSuchProcess: return ESRCH
case .interruptedSystemCall: return EINTR
case .inputOutputError: return EIO
case .deviceNotConfigured: return ENXIO
case .argumentListTooLong: return E2BIG
case .executableFormatError: return ENOEXEC
case .badFileDescriptor: return EBADF
case .noChildProcesses: return ECHILD
case .resourceDeadlockAvoided: return EDEADLK
case .cannotAllocateMemory: return ENOMEM
case .permissionDenied: return EACCES
case .badAddress: return EFAULT
case .blockDeviceRequired: return ENOTBLK
case .deviceOrResourceBusy: return EBUSY
case .fileExists: return EEXIST
case .crossDeviceLink: return EXDEV
case .operationNotSupportedByDevice: return ENODEV
case .notADirectory: return ENOTDIR
case .isADirectory: return EISDIR
case .invalidArgument: return EINVAL
case .tooManyOpenFilesInSystem: return ENFILE
case .tooManyOpenFiles: return EMFILE
case .inappropriateInputOutputControlForDevice: return ENOTTY
case .textFileBusy: return ETXTBSY
case .fileTooLarge: return EFBIG
case .noSpaceLeftOnDevice: return ENOSPC
case .illegalSeek: return ESPIPE
case .readOnlyFileSystem: return EROFS
case .tooManyLinks: return EMLINK
case .brokenPipe: return EPIPE
/* math software */
case .numericalArgumentOutOfDomain: return EDOM
case .resultTooLarge: return ERANGE
/* non-blocking and interrupt i/o */
case .resourceTemporarilyUnavailable: return EAGAIN
case .operationWouldBlock: return EWOULDBLOCK
case .operationNowInProgress: return EINPROGRESS
case .operationAlreadyInProgress: return EALREADY
/* ipc/network software -- argument errors */
case .socketOperationOnNonSocket: return ENOTSOCK
case .destinationAddressRequired: return EDESTADDRREQ
case .messageTooLong: return EMSGSIZE
case .protocolWrongTypeForSocket: return EPROTOTYPE
case .protocolNotAvailable: return ENOPROTOOPT
case .protocolNotSupported: return EPROTONOSUPPORT
case .socketTypeNotSupported: return ESOCKTNOSUPPORT
case .operationNotSupported: return ENOTSUP
case .protocolFamilyNotSupported: return EPFNOSUPPORT
case .addressFamilyNotSupportedByProtocolFamily: return EAFNOSUPPORT
case .addressAlreadyInUse: return EADDRINUSE
case .cannotAssignRequestedAddress: return EADDRNOTAVAIL
/* ipc/network software -- operational errors */
case .networkIsDown: return ENETDOWN
case .networkIsUnreachable: return ENETUNREACH
case .networkDroppedConnectionOnReset: return ENETRESET
case .softwareCausedConnectionAbort: return ECONNABORTED
case .connectionResetByPeer: return ECONNRESET
case .noBufferSpaceAvailable: return ENOBUFS
case .socketIsAlreadyConnected: return EISCONN
case .socketIsNotConnected: return ENOTCONN
case .cannotSendAfterSocketShutdown: return ESHUTDOWN
case .tooManyReferences: return ETOOMANYREFS
case .operationTimedOut: return ETIMEDOUT
case .connectionRefused: return ECONNREFUSED
case .tooManyLevelsOfSymbolicLinks: return ELOOP
case .fileNameTooLong: return ENAMETOOLONG
case .hostIsDown: return EHOSTDOWN
case .noRouteToHost: return EHOSTUNREACH
case .directoryNotEmpty: return ENOTEMPTY
/* quotas & mush */
case .tooManyUsers: return EUSERS
case .diskQuotaExceeded: return EDQUOT
/* Network File System */
case .staleFileHandle: return ESTALE
case .objectIsRemote: return EREMOTE
case .noLocksAvailable: return ENOLCK
case .functionNotImplemented: return ENOSYS
case .valueTooLargeForDefinedDataType: return EOVERFLOW
case .operationCanceled: return ECANCELED
case .identifierRemoved: return EIDRM
case .noMessageOfDesiredType: return ENOMSG
case .illegalByteSequence: return EILSEQ
case .badMessage: return EBADMSG
case .multihopAttempted: return EMULTIHOP
case .noDataAvailable: return ENODATA
case .linkHasBeenSevered: return ENOLINK
case .outOfStreamsResources: return ENOSR
case .deviceNotAStream: return ENOSTR
case .protocolError: return EPROTO
case .timerExpired: return ETIME
case .stateNotRecoverable: return ENOTRECOVERABLE
case .previousOwnerDied: return EOWNERDEAD
case .other(let errorNumber): return errorNumber
}
}
}
extension SystemError : Equatable {}
public func == (lhs: SystemError, rhs: SystemError) -> Bool {
return lhs.errorNumber == rhs.errorNumber
}
extension SystemError {
public static func description(for errorNumber: Int32) -> String {
return String(cString: strerror(errorNumber))
}
}
extension SystemError : CustomStringConvertible {
public var description: String {
return SystemError.description(for: errorNumber)
}
}
extension SystemError {
public static var lastOperationError: SystemError? {
return SystemError(errorNumber: errno)
}
}
public func ensureLastOperationSucceeded() throws {
if let error = SystemError.lastOperationError {
throw error
}
}
|
mit
|
2d88fe4a2fac96bb10d64a1cb20a3537
| 31.811138 | 76 | 0.707033 | 5.553689 | false | false | false | false |
pmtao/SwiftUtilityFramework
|
SwiftUtilityFramework/Foundation/Formatter/NumberFormatter.swift
|
1
|
3094
|
//
// NumberFormatter.swift
// SwiftUtilityFramework
//
// Created by 阿涛 on 17-8-16.
// Copyright © 2017年 SinkingSoul. All rights reserved.
//
import UIKit
/// 数字格式化(Double类型数字)
///
/// - Parameter with: 待格式化的数据
/// - Returns: 格式化结果字符串
public func SUF_numberFormat(with: Double) -> String {
let format = NumberFormatter()
var numberFormated: String
format.numberStyle = .decimal
format.maximumFractionDigits = 9 //最长9位小数
numberFormated = format.string(from: NSNumber(value: with))!
return numberFormated
}
/// 数字格式化(Int64 类型数字)
///
/// - Parameter with: 待格式化的数据
/// - Returns: 格式化结果字符串
public func SUF_numberFormat(with: Int64) -> String {
let format = NumberFormatter()
var numberFormated: String
format.numberStyle = .decimal
numberFormated = format.string(from: NSNumber(value: with))!
return numberFormated
}
/// 数字格式化(Int 类型数字)
///
/// - Parameter with: 待格式化的数据
/// - Returns: 格式化结果字符串
public func SUF_numberFormat(with: Int) -> String {
let format = NumberFormatter()
var numberFormated: String
format.numberStyle = .decimal
numberFormated = format.string(from: NSNumber(value: with))!
return numberFormated
}
/// 数字格式化(String类型数字)
///
/// - Parameter with: 待格式化的数据
/// - Returns: 格式化结果字符串
public func SUF_numberFormat(with: String) -> String {
let format = NumberFormatter()
var numberFormated: String
format.numberStyle = .decimal
numberFormated = format.string(from: format.number(from: with)!)!
return numberFormated
}
/// 数字格式化(String类型数字)
///
/// - Parameter with: 待格式化的数据
/// - Returns: 格式化结果
public func SUF_stringToNumber(with: String) -> Double? {
let format = NumberFormatter()
var numberFormated: Double?
// format.numberStyle = .decimal
numberFormated = format.number(from: with)?.doubleValue
return numberFormated
}
/// 将 Double 值转为字符串,并进行格式化(添加千分位,如果等同于整数,则去掉小数部分)
///
/// - Parameter value: 要转换的值
/// - Returns: 转换后的字符串
public func SUF_doubleToFormatedString(value: Double) -> String {
let intValue = Int64(value)
var doubleString = ""
if Double(intValue) == value {
doubleString = SUF_numberFormat(with: intValue)
} else {
doubleString = SUF_numberFormat(with: value)
}
return doubleString
}
/// 将一个能转为大小相同的 Double 值转为 Int 值
///
/// - Parameter value: 要转换的值
/// - Returns: 转换后的 Int 值,转换不成功则为 nil。
public func SUF_doubleToEqualInt(value: Double) -> Int? {
var intValue: Int? = Int(value)
if Double(intValue!) < value {
intValue = nil
}
return intValue
}
|
mit
|
62816f23f142b889efef54cde7967a4e
| 20.07874 | 69 | 0.649608 | 3.602961 | false | false | false | false |
snepo/ios-networking
|
ios-garment-manager/GarmentManager/GarmentManager/Garment.swift
|
1
|
560
|
//
// Garment.swift
// nadix
//
// Created by james on 13/3/17.
// Copyright © 2017 Snepo. All rights reserved.
//
import Foundation
import CoreData
enum GarmentType: Int16 {
case unknown
case pants
static let allKnownTypes = [pants]
}
extension Garment {
static func == (garment1: Garment, garment2: Garment) -> Bool {
return garment1.uuid == garment2.uuid
}
var garmentType : GarmentType {
if let result = GarmentType(rawValue:type) {
return result
}
return .unknown
}
}
|
mit
|
3d11aab28f801e45aa9ef157fb88cbaa
| 17.032258 | 67 | 0.615385 | 3.429448 | false | false | false | false |
mitochrome/complex-gestures-demo
|
apps/GestureInput/Carthage/Checkouts/RxDataSources/Tests/s.swift
|
3
|
2207
|
//
// s.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 11/26/16.
// Copyright © 2016 kzaher. All rights reserved.
//
import Foundation
import RxDataSources
/**
Test section. Name is so short for readability sake.
*/
struct s {
let identity: Int
let items: [i]
}
extension s {
init(_ identity: Int, _ items: [i]) {
self.identity = identity
self.items = items
}
}
extension s: AnimatableSectionModelType {
typealias Item = i
init(original: s, items: [Item]) {
self.identity = original.identity
self.items = items
}
}
extension s: Equatable {
}
func == (lhs: s, rhs: s) -> Bool {
return lhs.identity == rhs.identity && lhs.items == rhs.items
}
extension s: CustomDebugStringConvertible {
var debugDescription: String {
let itemDescriptions = items.map { "\n \($0)," }.joined(separator: "")
return "s(\(identity),\(itemDescriptions)\n)"
}
}
struct sInvalidInitializerImplementation1 {
let identity: Int
let items: [i]
init(_ identity: Int, _ items: [i]) {
self.identity = identity
self.items = items
}
}
func == (lhs: sInvalidInitializerImplementation1, rhs: sInvalidInitializerImplementation1) -> Bool {
return lhs.identity == rhs.identity && lhs.items == rhs.items
}
extension sInvalidInitializerImplementation1: AnimatableSectionModelType, Equatable {
typealias Item = i
init(original: sInvalidInitializerImplementation1, items: [Item]) {
self.identity = original.identity
self.items = items + items
}
}
struct sInvalidInitializerImplementation2 {
let identity: Int
let items: [i]
init(_ identity: Int, _ items: [i]) {
self.identity = identity
self.items = items
}
}
extension sInvalidInitializerImplementation2: AnimatableSectionModelType, Equatable {
typealias Item = i
init(original: sInvalidInitializerImplementation2, items: [Item]) {
self.identity = -1
self.items = items
}
}
func == (lhs: sInvalidInitializerImplementation2, rhs: sInvalidInitializerImplementation2) -> Bool {
return lhs.identity == rhs.identity && lhs.items == rhs.items
}
|
mit
|
68f79bce77bbc40f3efe147dd23ecd8c
| 22.221053 | 100 | 0.655485 | 4.217973 | false | false | false | false |
XiaoChenYung/GitSwift
|
GitSwift/Common/Common.swift
|
1
|
397
|
//
// Common.swift
// GitSwift
//
// Created by tm on 2017/7/31.
// Copyright © 2017年 tm. All rights reserved.
//
import Foundation
import UIKit
let APPDELEGATE = UIApplication.shared.delegate
let BaseColorString = "546f7a" //主色调
let BaseGrayColor = UIColor(hex: "999999") //底部导航正常色
let BaseColor = UIColor(hex: BaseColorString)
let UnderLineHeight: CGFloat = 0.5
|
mit
|
856263281dcf8acdef30b8893d2d2eb7
| 17.7 | 52 | 0.721925 | 3.224138 | false | false | false | false |
xmartlabs/XLForm
|
Examples/Swift/SwiftExample/RealExamples/NativeEventFormViewController.swift
|
1
|
11188
|
//
// NativeEventNavigationViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
class NativeEventFormViewController : XLFormViewController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeForm()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Add Event")
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Title
row = XLFormRowDescriptor(tag: "title", rowType: XLFormRowDescriptorTypeText)
row.cellConfigAtConfigure["textField.placeholder"] = "Title"
row.isRequired = true
section.addFormRow(row)
// Location
row = XLFormRowDescriptor(tag: "location", rowType: XLFormRowDescriptorTypeText)
row.cellConfigAtConfigure["textField.placeholder"] = "Location"
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// All-day
row = XLFormRowDescriptor(tag: "all-day", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "All-day")
section.addFormRow(row)
// Starts
row = XLFormRowDescriptor(tag: "starts", rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Starts")
row.value = Date(timeIntervalSinceNow: 60*60*24)
section.addFormRow(row)
// Ends
row = XLFormRowDescriptor(tag: "ends", rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Ends")
row.value = Date(timeIntervalSinceNow: 60*60*25)
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Repeat
row = XLFormRowDescriptor(tag: "repeat", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Repeat")
row.value = XLFormOptionsObject(value: 0, displayText: "Never")
row.selectorTitle = "Repeat"
row.selectorOptions = [XLFormOptionsObject(value: 0, displayText: "Never")!,
XLFormOptionsObject(value: 1, displayText: "Every Day")!,
XLFormOptionsObject(value: 2, displayText: "Every Week")!,
XLFormOptionsObject(value: 3, displayText: "Every 2 Weeks")!,
XLFormOptionsObject(value: 4, displayText: "Every Month")!,
XLFormOptionsObject(value: 5, displayText: "Every Year")!]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Alert
row = XLFormRowDescriptor(tag: "alert", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Alert")
row.value = XLFormOptionsObject(value: 0, displayText: "None")
row.selectorTitle = "Event Alert"
row.selectorOptions = [
XLFormOptionsObject(value: 0, displayText: "None")!,
XLFormOptionsObject(value: 1, displayText: "At time of event")!,
XLFormOptionsObject(value: 2, displayText: "5 minutes before")!,
XLFormOptionsObject(value: 3, displayText: "15 minutes before")!,
XLFormOptionsObject(value: 4, displayText: "30 minutes before")!,
XLFormOptionsObject(value: 5, displayText: "1 hour before")!,
XLFormOptionsObject(value: 6, displayText: "2 hours before")!,
XLFormOptionsObject(value: 7, displayText: "1 day before")!,
XLFormOptionsObject(value: 8, displayText: "2 days before")!]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// Show As
row = XLFormRowDescriptor(tag: "showAs", rowType:XLFormRowDescriptorTypeSelectorPush, title:"Show As")
row.value = XLFormOptionsObject(value: 0, displayText: "Busy")
row.selectorTitle = "Show As"
row.selectorOptions = [XLFormOptionsObject(value: 0, displayText:"Busy")!,
XLFormOptionsObject(value: 1, displayText:"Free")!]
section.addFormRow(row)
section = XLFormSectionDescriptor.formSection()
form.addFormSection(section)
// URL
row = XLFormRowDescriptor(tag: "url", rowType:XLFormRowDescriptorTypeURL)
row.cellConfigAtConfigure["textField.placeholder"] = "URL"
section.addFormRow(row)
// Notes
row = XLFormRowDescriptor(tag: "notes", rowType:XLFormRowDescriptorTypeTextView)
row.cellConfigAtConfigure["textView.placeholder"] = "Notes"
section.addFormRow(row)
self.form = form
}
override func viewDidLoad(){
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(NativeEventFormViewController.cancelPressed(_:)))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(NativeEventFormViewController.savePressed(_:)))
}
// MARK: XLFormDescriptorDelegate
override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
if formRow.tag == "alert" {
if !((formRow.value! as AnyObject).valueData() as AnyObject).isEqual(0) && ((oldValue as AnyObject).valueData() as AnyObject).isEqual(0) {
let newRow = formRow.copy() as! XLFormRowDescriptor
newRow.tag = "secondAlert"
newRow.title = "Second Alert"
form.addFormRow(newRow, afterRow:formRow)
}
else if !((oldValue as AnyObject).valueData() as AnyObject).isEqual(0) && ((newValue as AnyObject).valueData() as AnyObject).isEqual(0) {
form.removeFormRow(withTag: "secondAlert")
}
}
else if formRow.tag == "all-day" {
let startDateDescriptor = form.formRow(withTag: "starts")!
let endDateDescriptor = form.formRow(withTag: "ends")!
let dateStartCell: XLFormDateCell = startDateDescriptor.cell(forForm: self) as! XLFormDateCell
let dateEndCell: XLFormDateCell = endDateDescriptor.cell(forForm: self) as! XLFormDateCell
if (formRow.value! as AnyObject).valueData() as? Bool == true {
startDateDescriptor.valueTransformer = DateValueTrasformer.self
endDateDescriptor.valueTransformer = DateValueTrasformer.self
dateStartCell.formDatePickerMode = .date
dateEndCell.formDatePickerMode = .date
}
else{
startDateDescriptor.valueTransformer = DateTimeValueTrasformer.self
endDateDescriptor.valueTransformer = DateTimeValueTrasformer.self
dateStartCell.formDatePickerMode = .dateTime
dateEndCell.formDatePickerMode = .dateTime
}
updateFormRow(startDateDescriptor)
updateFormRow(endDateDescriptor)
}
else if formRow.tag == "starts" {
let startDateDescriptor = form.formRow(withTag: "starts")!
let endDateDescriptor = form.formRow(withTag: "ends")!
if (startDateDescriptor.value! as AnyObject).compare(endDateDescriptor.value as! Date) == .orderedDescending {
// startDateDescriptor is later than endDateDescriptor
endDateDescriptor.value = Date(timeInterval: 60*60*24, since: startDateDescriptor.value as! Date)
endDateDescriptor.cellConfig.removeObject(forKey: "detailTextLabel.attributedText")
updateFormRow(endDateDescriptor)
}
}
else if formRow.tag == "ends" {
let startDateDescriptor = form.formRow(withTag: "starts")!
let endDateDescriptor = form.formRow(withTag: "ends")!
let dateEndCell = endDateDescriptor.cell(forForm: self) as! XLFormDateCell
if (startDateDescriptor.value! as AnyObject).compare(endDateDescriptor.value as! Date) == .orderedDescending {
// startDateDescriptor is later than endDateDescriptor
dateEndCell.update()
let newDetailText = dateEndCell.detailTextLabel!.text!
let strikeThroughAttribute = [NSAttributedString.Key.strikethroughStyle : NSUnderlineStyle.single.rawValue]
let strikeThroughText = NSAttributedString(string: newDetailText, attributes: strikeThroughAttribute)
endDateDescriptor.cellConfig["detailTextLabel.attributedText"] = strikeThroughText
updateFormRow(endDateDescriptor)
}
else{
let endDateDescriptor = self.form.formRow(withTag: "ends")!
endDateDescriptor.cellConfig.removeObject(forKey: "detailTextLabel.attributedText")
updateFormRow(endDateDescriptor)
}
}
}
@objc func cancelPressed(_ button: UIBarButtonItem){
dismiss(animated: true, completion: nil)
}
@objc func savePressed(_ button: UIBarButtonItem){
let validationErrors : Array<NSError> = formValidationErrors() as! Array<NSError>
if (validationErrors.count > 0){
showFormValidationError(validationErrors.first)
return
}
tableView.endEditing(true)
}
}
class NativeEventNavigationViewController : UINavigationController {
override func viewDidLoad(){
super.viewDidLoad()
view.tintColor = .red
}
}
|
mit
|
6eeef72e738ea89d5ba266c3459a6afa
| 46.40678 | 170 | 0.656596 | 5.32255 | false | false | false | false |
timsawtell/SwiftAppStarter
|
App/Controller/Commands/CommandCenter.swift
|
1
|
1849
|
//
// CommandCenter.swift
// SwiftAppStarter
//
// Created by Tim Sawtell on 29/09/2015.
// Copyright © 2015 Tim Sawtell. All rights reserved.
//
import Foundation
class CommandCenter {
class func securelyArchiveRootObject(object: AnyObject, key: String) -> NSData? {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data);
archiver.requiresSecureCoding = true
archiver.encodeObject(object, forKey: key as String)
archiver.finishEncoding()
return data
}
class func securelyUnarchiveData(data: NSData, key: String) -> AnyObject? {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data);
unarchiver.requiresSecureCoding = true
let x = unarchiver.decodeObjectForKey(key)
return x
}
class func archiveRootObject(object: AnyObject, key: NSString) -> NSData? {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data);
archiver.encodeObject(object, forKey: key as String)
archiver.finishEncoding()
return data
}
class func unarchiveData(data: NSData, key: String) -> AnyObject? {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data);
let x = unarchiver.decodeObjectForKey(key)
return x
}
class func getModelDataFromDisk() -> Model {
let model = Model()
do {
let data = try NSData(contentsOfFile: kPathForModelFile, options: NSDataReadingOptions.DataReadingMappedIfSafe)
if let modelInstance = CommandCenter.unarchiveData(data, key: kModelArchiveKey) as? Model {
return modelInstance
} else {
return model
}
} catch {
return model
}
}
}
|
mit
|
104c0b5bf2ac0d0513a9d66166204b71
| 32.017857 | 123 | 0.643939 | 5.090909 | false | false | false | false |
wess/Appendix
|
Sources/shared/Cache.swift
|
1
|
4964
|
//
// Cache.swift
// Appendix
//
// Created by Wess Cope on 3/12/19.
//
import Foundation
public protocol CacheDelegate : class {
func cache<Key:Hashable, Value>(_ cache:Cache<Key, Value>, willEvict value:Value)
}
open class Cache<Key:Hashable, Value> : NSObject, ExpressibleByDictionaryLiteral, NSCacheDelegate {
private lazy var engine:NSCache<Box<Key>, Box<Value>> = {
let cache = NSCache<Box<Key>, Box<Value>>()
cache.delegate = self
return cache
}()
open weak var delegate:CacheDelegate? = nil
public private(set) var keys:Set<Key> = []
open var name:String {
get {
return engine.name
}
set {
engine.name = newValue
}
}
open var totalCostLimit:Int {
get {
return engine.totalCostLimit
}
set {
engine.totalCostLimit = newValue
}
}
open var countLimit:Int {
get {
return engine.countLimit
}
set {
engine.countLimit = newValue
}
}
open var evictsObjectsWithDiscardedContent:Bool {
get {
return engine.evictsObjectsWithDiscardedContent
}
set {
engine.evictsObjectsWithDiscardedContent = newValue
}
}
convenience init<S: Sequence>(_ sequence: S) where S.Iterator.Element == (key: Key, value: Value) {
self.init()
for (key, value) in sequence {
self[key] = value
}
}
required public convenience init(dictionaryLiteral elements: (Key, Value)...) {
self.init(elements.map { (key: $0.0, value: $0.1) })
}
///Mark - NSCacheDelegate
public func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any) {
guard let value = obj as? Value else { return }
delegate?.cache(self, willEvict: value)
}
}
extension Cache /* Box */ {
private class Box<T> : NSObject {
let value:T
init(_ value:T) {
self.value = value
}
override func isEqual(_ object: Any?) -> Bool {
guard let otherKey = object as? Box<Key>,
let key = self as? Box<Key> else { return false }
return key.value == otherKey.value
}
override var hash: Int {
guard let value = self as? Box<Value> else { return 0 }
return value.hashValue
}
}
}
extension Cache /* Accessors */ {
@discardableResult
open func set(_ value:Value, for key:Key, cost:Int) -> Cache {
self[key, cost] = value
return self
}
@discardableResult
open func set(_ value:Value, for key:Key) -> Cache {
self[key] = value
return self
}
open func get(for key:Key) -> Value? {
return self[key]
}
open func remove(key:Key) {
self[key] = nil
}
open func clear() {
keys.forEach(remove)
}
}
extension Cache /* Subscript */ {
open subscript(key:Key, cost:Int) -> Value? {
get {
return engine.object(forKey: Box(key))?.value
}
set {
guard let value = newValue else {
keys.remove(key)
engine.removeObject(forKey: Box(key))
return
}
keys.insert(key)
engine.setObject(Box(value), forKey: Box(key), cost: cost)
}
}
open subscript(key:Key) -> Value? {
get {
return engine.object(forKey: Box(key))?.value
}
set {
guard let value = newValue else {
keys.remove(key)
engine.removeObject(forKey: Box(key))
return
}
keys.insert(key)
engine.setObject(Box(value), forKey: Box(key))
}
}
}
extension Cache : Sequence {
public typealias Iterator = AnyIterator<(key:Key, value:Value)>
public func makeIterator() -> AnyIterator<(key: Key, value: Value)> {
let keys = self.keys
var iterator = keys.makeIterator()
func next() -> (key:Key, value:Value)? {
guard let key = iterator.next() else { return nil }
if let value = self[key] {
return (key: key, value: value)
}
self.keys.remove(key)
return next()
}
return AnyIterator(next)
}
}
extension Cache: Collection {
public struct Index: Comparable {
fileprivate let index: Set<Key>.Index
fileprivate init(_ dictionaryIndex: Set<Key>.Index) {
self.index = dictionaryIndex
}
public static func == (lhs: Index, rhs: Index) -> Bool {
return lhs.index == rhs.index
}
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs.index < rhs.index
}
}
public var startIndex: Index {
return Index(keys.startIndex)
}
public var endIndex: Index {
return Index(keys.endIndex)
}
public subscript (position: Index) -> Iterator.Element {
let key = keys[position.index]
guard let value = self[key] else { fatalError("Invalid key") }
return (key: key, value: value)
}
public func index(after position: Index) -> Index {
return Index(keys.index(after: position.index))
}
}
|
mit
|
864cbad480a10d968f7cba130371ebbe
| 20.396552 | 101 | 0.592869 | 3.917916 | false | false | false | false |
ZamzamInc/SwiftyPress
|
Sources/SwiftyPress/Repositories/Post/Services/PostNetworkService.swift
|
1
|
3343
|
//
// PostsNetworkService.swift
// SwiftyPress
//
// Created by Basem Emara on 2018-10-10.
// Copyright © 2018 Zamzam Inc. All rights reserved.
//
import Foundation
import ZamzamCore
public struct PostNetworkService: PostService {
private let networkRepository: NetworkRepository
private let jsonDecoder: JSONDecoder
private let constants: Constants
private let log: LogRepository
public init(
networkRepository: NetworkRepository,
jsonDecoder: JSONDecoder,
constants: Constants,
log: LogRepository
) {
self.networkRepository = networkRepository
self.jsonDecoder = jsonDecoder
self.constants = constants
self.log = log
}
}
public extension PostNetworkService {
func fetch(id: Int, with request: PostAPI.ItemRequest, completion: @escaping (Result<ExtendedPost, SwiftyPressError>) -> Void) {
let urlRequest: URLRequest = .readPost(id: id, with: request, constants: constants)
networkRepository.send(with: urlRequest) {
// Handle errors
guard case .success = $0 else {
// Handle no existing data
if $0.error?.statusCode == 404 {
completion(.failure(.nonExistent))
return
}
self.log.error("An error occured while fetching the post: \(String(describing: $0.error)).")
completion(.failure(SwiftyPressError(from: $0.error ?? .init(request: urlRequest))))
return
}
// Ensure available
guard case let .success(item) = $0, let data = item.data else {
completion(.failure(.nonExistent))
return
}
DispatchQueue.transform.async {
do {
// Parse response data
let payload = try self.jsonDecoder.decode(ExtendedPost.self, from: data)
DispatchQueue.main.async {
completion(.success(payload))
}
} catch {
self.log.error("An error occured while parsing the post: \(error).")
DispatchQueue.main.async { completion(.failure(.parseFailure(error))) }
return
}
}
}
}
}
// MARK: - Requests
private extension URLRequest {
static func readPost(id: Int, with request: PostAPI.ItemRequest, constants: Constants) -> URLRequest {
URLRequest(
url: constants.baseURL
.appendingPathComponent(constants.baseREST)
.appendingPathComponent("post/\(id)"),
method: .get,
parameters: {
var params: [String: Any] = [:]
if !request.taxonomies.isEmpty {
params["taxonomies"] = request.taxonomies
.joined(separator: ",")
}
if !request.postMetaKeys.isEmpty {
params["meta_keys"] = request.postMetaKeys
.joined(separator: ",")
}
return params
}()
)
}
}
|
mit
|
92764904a9f1f7582679abec279fce9a
| 32.089109 | 132 | 0.523938 | 5.355769 | false | false | false | false |
jarrodparkes/DominoKit
|
Sources/Suit.swift
|
1
|
3059
|
//
// Suit.swift
// DominoKit
//
// Created by Jarrod Parkes on 1/31/17.
// Copyright © 2017 Jarrod Parkes. All rights reserved.
//
// MARK: - Suit
/**
The value of one end of a domino which corresponds to the number of dots,
also known as pips, seen on its face.
- invalid: An erroneous, impossible value.
- zero: The absense of a value, or blank.
- [remaining values]: The number of dots present on this end of the domino.
*/
public enum Suit: Int {
case invalid = -1
case zero = 0
case one, two, three, four, five, six, seven, eight, nine
case ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen
// MARK: Properties
/// An array containing all possible, valid suits.
public static let allValues: [Suit] = Suit.suitsFromZeroTo(.eighteen)
// MARK: Custom Initializer
/**
Initializes a suit from an integer value.
- Parameter value: An integer representing the number of dots present
for a particular suit
- Returns: If the value given is valid, then a suit is returned where
its number of dots is equal to the value.
*/
public init?(value: Int) {
switch value {
case 0...18:
self = Suit(rawValue: value)!
default:
self = .invalid
}
}
// MARK: Helpers
/**
Generates an array of suits ranging from zero to a specified suit.
- Parameter highestSuit: The upper bound for the range of suits to be
generated
- Returns: An array of suits ranging from zero to a specified suit.
*/
public static func suitsFromZeroTo(_ highestSuit: Suit) -> [Suit] {
guard highestSuit != .invalid else {
return [Suit]()
}
var suits = [Suit]()
for x in 0...highestSuit.rawValue {
suits.append(Suit(rawValue: x)!)
}
return suits
}
}
// MARK: - Suit: Comparable
extension Suit: Comparable {}
/**
Compares two suits to determine if the first suit is less than the second
suit.
- Parameters:
lhs: The first suit
rhs: The second suit
- Returns: A Boolean value indicating if the first suit is less than the
second suit.
*/
public func <(lhs: Suit, rhs: Suit) -> Bool {
switch (lhs, rhs) {
case (.invalid, _):
return true
case (_, .invalid):
return false
case (_, _) where lhs == rhs:
return false
default:
return lhs.rawValue < rhs.rawValue
}
}
// MARK: - Suit: CustomStringConvertible
extension Suit: CustomStringConvertible {
/// Textual representation of a domino.
public var description: String {
switch self {
case .invalid:
return "invalid"
case _ where self.rawValue < 10:
return "0\(self.rawValue)"
case _ where self.rawValue >= 10 && self.rawValue != Suit.invalid.rawValue:
return "\(self.rawValue)"
default:
return "unknown"
}
}
}
|
mit
|
9ca694d601616dae9c1bb55a85ef1b3e
| 25.136752 | 87 | 0.598757 | 4.247222 | false | false | false | false |
DarthMike/YapDatabaseExtensions
|
framework/YapDatabaseExtensions/PromiseKit/PromiseKit.swift
|
1
|
17865
|
//
// Created by Daniel Thorpe on 08/04/2015.
//
import YapDatabase
import PromiseKit
extension YapDatabaseConnection {
public func asyncRead<Object where Object: Persistable>(key: String) -> Promise<Object?> {
return Promise { (fulfiller, _) in
self.asyncRead({ $0.read(key) }, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
public func asyncRead<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(key: String) -> Promise<Value?> {
return Promise { (fulfiller, _) in
self.asyncRead({ $0.read(key) }, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
}
extension YapDatabaseConnection {
public func asyncRead<Object where Object: Persistable>(keys: [String]) -> Promise<[Object]> {
return Promise { (fulfiller, _) in
self.asyncRead({ $0.read(keys) }, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
public func asyncRead<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(keys: [String]) -> Promise<[Value]> {
return Promise { (fulfiller, _) in
self.asyncRead({ $0.read(keys) }, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
}
extension YapDatabaseConnection {
/**
Asynchonously writes a Persistable object conforming to NSCoding to the database using the connection.
:param: object An Object.
:return: a Promise Object.
*/
public func asyncWrite<Object where Object: NSCoding, Object: Persistable>(object: Object) -> Promise<Object> {
return Promise { (fulfiller, _) in
self.asyncWrite(object, completion: fulfiller)
}
}
/**
Asynchonously writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: object An ObjectWithObjectMetadata.
:return: a Future ObjectWithObjectMetadata.
*/
public func asyncWrite<ObjectWithObjectMetadata where ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> Promise<ObjectWithObjectMetadata> {
return Promise { (fulfiller, _) in
self.asyncWrite(object, completion: fulfiller)
}
}
/**
Asynchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: object An ObjectWithValueMetadata.
:return: a Future ObjectWithValueMetadata.
*/
public func asyncWrite<ObjectWithValueMetadata where ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata) -> Promise<ObjectWithValueMetadata> {
return Promise { (fulfiller, _) in
self.asyncWrite(object, completion: fulfiller)
}
}
/**
Asynchonously writes a Persistable value conforming to Saveable to the database inside the read write transaction.
:param: value A Value.
:return: a Promise Value.
*/
public func asyncWrite<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(value: Value) -> Promise<Value> {
return Promise { (fulfiller, _) in
self.asyncWrite(value, completion: fulfiller)
}
}
/**
Asynchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: value A ValueWithValueMetadata.
:return: a Promise Value.
*/
public func asyncWrite<ValueWithValueMetadata where ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> Promise<ValueWithValueMetadata> {
return Promise { (fulfiller, _) in
self.asyncWrite(value, completion: fulfiller)
}
}
/**
Asynchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: value A ValueWithObjectMetadata.
:return: a Promise Value.
*/
public func asyncWrite<ValueWithObjectMetadata where ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> Promise<ValueWithObjectMetadata> {
return Promise { (fulfiller, _) in
self.asyncWrite(value, completion: fulfiller)
}
}
}
extension YapDatabaseConnection {
/**
Asynchonously writes Persistable objects conforming to NSCoding to the database using the connection.
:param: objects A SequenceType of Object instances.
:return: a Promise array of Object instances.
*/
public func asyncWrite<Objects, Object where Objects: SequenceType, Objects.Generator.Element == Object, Object: NSCoding, Object: Persistable>(objects: Objects) -> Promise<[Object]> {
return Promise { (fulfiller, _) in
self.asyncWrite(objects, completion: fulfiller)
}
}
/**
Asynchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithObjectMetadata instances.
:returns: a Promise array of ObjectWithObjectMetadata instances.
*/
public func asyncWrite<Objects, ObjectWithObjectMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithObjectMetadata, ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> Promise<[ObjectWithObjectMetadata]> {
return Promise { (fulfiller, _) in
self.asyncWrite(objects, completion: fulfiller)
}
}
/**
Asynchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithValueMetadata instances.
:returns: a Promise array of ObjectWithValueMetadata instances.
*/
public func asyncWrite<Objects, ObjectWithValueMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithValueMetadata, ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> Promise<[ObjectWithValueMetadata]> {
return Promise { (fulfiller, _) in
self.asyncWrite(objects, completion: fulfiller)
}
}
/**
Asynchonously writes Persistable values conforming to Saveable to the database using the connection.
:param: values A SequenceType of Value instances.
:return: a Promise array of Value instances.
*/
public func asyncWrite<Values, Value where Values: SequenceType, Values.Generator.Element == Value, Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(values: Values) -> Promise<[Value]> {
return Promise { (fulfiller, _) in
self.asyncWrite(values, completion: fulfiller)
}
}
/**
Asynchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: values A SequenceType of ValueWithObjectMetadata instances.
:returns: a Promise array of ValueWithObjectMetadata instances.
*/
public func asyncWrite<Values, ValueWithObjectMetadata where Values: SequenceType, Values.Generator.Element == ValueWithObjectMetadata, ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> Promise<[ValueWithObjectMetadata]> {
return Promise { (fulfiller, _) in
self.asyncWrite(values, completion: fulfiller)
}
}
/**
Asynchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: values A SequenceType of ValueWithValueMetadata instances.
:returns: a Promise array of ValueWithValueMetadata instances.
*/
public func asyncWrite<Values, ValueWithValueMetadata where Values: SequenceType, Values.Generator.Element == ValueWithValueMetadata, ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata>(values: Values) -> Promise<[ValueWithValueMetadata]> {
return Promise { (fulfiller, _) in
self.asyncWrite(values, completion: fulfiller)
}
}
}
extension YapDatabaseConnection {
public func asyncRemove<Item where Item: Persistable>(item: Item) -> Promise<Void> {
return Promise { (fulfiller, _) in
self.asyncRemove(item, completion: fulfiller)
}
}
}
extension YapDatabaseConnection {
public func asyncRemove<Items where Items: SequenceType, Items.Generator.Element: Persistable>(items: Items) -> Promise<Void> {
return Promise { (fulfiller, _) in
self.asyncRemove(items, completion: fulfiller)
}
}
}
extension YapDatabase {
public func asyncRead<Object where Object: Persistable>(key: String) -> Promise<Object?> {
return Promise { (fulfiller, _) in
self.asyncRead(key, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
public func asyncRead<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(key: String) -> Promise<Value?> {
return Promise { (fulfiller, _) in
self.asyncRead(key, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
}
extension YapDatabase {
public func asyncRead<Object where Object: Persistable>(keys: [String]) -> Promise<[Object]> {
return Promise { (fulfiller, _) in
self.asyncRead(keys, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
public func asyncRead<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(keys: [String]) -> Promise<[Value]> {
return Promise { (fulfiller, _) in
self.asyncRead(keys, queue: dispatch_get_main_queue(), completion: fulfiller)
}
}
}
extension YapDatabase {
/**
Asynchonously writes a Persistable object conforming to NSCoding to the database using a new connection.
:param: object An Object.
:return: a Promise Object.
*/
public func asyncWrite<Object where Object: NSCoding, Object: Persistable>(object: Object) -> Promise<Object> {
return newConnection().asyncWrite(object)
}
/**
Asynchonously writes a Persistable object with metadata, both conforming to NSCoding to the database using a new connection.
:param: object An ObjectWithObjectMetadata.
:return: a Future ObjectWithObjectMetadata.
*/
public func asyncWrite<ObjectWithObjectMetadata where ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> Promise<ObjectWithObjectMetadata> {
return newConnection().asyncWrite(object)
}
/**
Asynchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database using a new connection.
:param: object An ObjectWithValueMetadata.
:return: a Future ObjectWithValueMetadata.
*/
public func asyncWrite<ObjectWithValueMetadata where ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata) -> Promise<ObjectWithValueMetadata> {
return newConnection().asyncWrite(object)
}
/**
Asynchonously writes a Persistable value conforming to Saveable to the database using a new connection.
:param: value A Value.
:return: a Promise Value.
*/
public func asyncWrite<Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(value: Value) -> Promise<Value> {
return newConnection().asyncWrite(value)
}
/**
Asynchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database using a new connection.
:param: value A ValueWithObjectMetadata.
:return: a Promise Value.
*/
public func asyncWrite<ValueWithObjectMetadata where ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> Promise<ValueWithObjectMetadata> {
return newConnection().asyncWrite(value)
}
/**
Asynchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database using a new connection.
:param: value A ValueWithValueMetadata.
:return: a Promise Value.
*/
public func asyncWrite<ValueWithValueMetadata where ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata, ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> Promise<ValueWithValueMetadata> {
return newConnection().asyncWrite(value)
}
}
extension YapDatabase {
/**
Asynchonously writes Persistable objects conforming to NSCoding to the database using a new connection.
:param: objects A SequenceType of Object instances.
:return: a Promise array of Object instances.
*/
public func asyncWrite<Objects, Object where Objects: SequenceType, Objects.Generator.Element == Object, Object: NSCoding, Object: Persistable>(objects: Objects) -> Promise<[Object]> {
return newConnection().asyncWrite(objects)
}
/**
Asynchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database using a new connection.
:param: objects A SequenceType of ObjectWithObjectMetadata instances.
:returns: a Promise array of ObjectWithObjectMetadata instances.
*/
public func asyncWrite<Objects, ObjectWithObjectMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithObjectMetadata, ObjectWithObjectMetadata: NSCoding, ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> Promise<[ObjectWithObjectMetadata]> {
return newConnection().asyncWrite(objects)
}
/**
Asynchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database using a new connection.
:param: objects A SequenceType of ObjectWithValueMetadata instances.
:returns: a Promise array of ObjectWithValueMetadata instances.
*/
public func asyncWrite<Objects, ObjectWithValueMetadata where Objects: SequenceType, Objects.Generator.Element == ObjectWithValueMetadata, ObjectWithValueMetadata: NSCoding, ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> Promise<[ObjectWithValueMetadata]> {
return newConnection().asyncWrite(objects)
}
/**
Asynchonously writes Persistable values conforming to Saveable to the database using a new connection.
:param: values A SequenceType of Value instances.
:return: a Promise array of Value instances.
*/
public func asyncWrite<Values, Value where Values: SequenceType, Values.Generator.Element == Value, Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(values: Values) -> Promise<[Value]> {
return newConnection().asyncWrite(values)
}
/**
Asynchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database using a new connection.
:param: values A SequenceType of ValueWithObjectMetadata instances.
:returns: a Promise array of ValueWithObjectMetadata instances.
*/
public func asyncWrite<Values, ValueWithObjectMetadata where Values: SequenceType, Values.Generator.Element == ValueWithObjectMetadata, ValueWithObjectMetadata: Saveable, ValueWithObjectMetadata: ObjectMetadataPersistable, ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> Promise<[ValueWithObjectMetadata]> {
return newConnection().asyncWrite(values)
}
/**
Asynchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database using a new connection.
:param: values A SequenceType of ValueWithValueMetadata instances.
:returns: a Promise array of ValueWithValueMetadata instances.
*/
public func asyncWrite<Values, ValueWithValueMetadata where Values: SequenceType, Values.Generator.Element == ValueWithValueMetadata, ValueWithValueMetadata: Saveable, ValueWithValueMetadata: ValueMetadataPersistable, ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata>(values: Values) -> Promise<[ValueWithValueMetadata]> {
return newConnection().asyncWrite(values)
}
}
extension YapDatabase {
public func asyncRemove<Item where Item: Persistable>(item: Item) -> Promise<Void> {
return newConnection().asyncRemove(item)
}
}
extension YapDatabase {
public func asyncRemove<Items where Items: SequenceType, Items.Generator.Element: Persistable>(items: Items) -> Promise<Void> {
return newConnection().asyncRemove(items)
}
}
|
mit
|
104df143e24cce682dba3b11b787f982
| 46.513298 | 379 | 0.735572 | 4.814066 | false | false | false | false |
Foild/SugarRecord
|
library/Core/SugarRecord.swift
|
1
|
6528
|
//
// SugarRecord.swift
// SugarRecord
//
// Created by Pedro Piñera Buendía on 03/08/14.
// Copyright (c) 2014 PPinera. All rights reserved.
//
import Foundation
import CoreData
// MARK: - Library Constants
internal let srSugarRecordVersion: String = "v1.0 - Alpha"
// MARK: - Error codes
internal enum SugarRecordErrorCodes: Int {
case UserError, LibraryError, CoreDataError, REALMError
}
/**
* Completion closure used by the stack initialization
*
* @param NSError? Error passed in case of something happened
*
* @return Nothing to return
*/
public typealias CompletionClosure = (error: NSError?) -> ()
// MARK: - Library
/**
* Main Library class with some useful constants and methods
*/
public class SugarRecord {
/* Workaround to have static vars */
private struct StaticVars
{
static var stacks: [protocol<SugarRecordStackProtocol>] = [SugarRecordStackProtocol]()
}
internal class func stacks() -> [protocol<SugarRecordStackProtocol>]
{
return StaticVars.stacks
}
/**
Set the stack of SugarRecord. The stack should be previously initialized with the custom user configuration.
- parameter stack: Stack by default where objects are going to be persisted
*/
public class func addStack(stack: protocol<SugarRecordStackProtocol>)
{
SugarRecordLogger.logLevelInfo.log("Stack -\(stack)- added to SugarRecord")
StaticVars.stacks.append(stack)
stack.initialize()
}
/**
Remove all the stacks from the list
*/
public class func removeAllStacks()
{
StaticVars.stacks.removeAll(keepCapacity: false)
SugarRecordLogger.logLevelVerbose.log("Removed all stacks form SugarRecord")
}
/**
Returns a valid stack for a given type
- parameter stackType: StackType of the required stack
- returns: SugarRecord stack
*/
internal class func stackFortype(stackType: SugarRecordEngine) -> SugarRecordStackProtocol?
{
for stack in StaticVars.stacks {
if stack.stackType == stackType {
return stack
}
}
return nil
}
/**
Called when the application will resign active
*/
public class func applicationWillResignActive()
{
SugarRecordLogger.logLevelInfo.log("Notifying the current stack that the app will resign active")
for stack in StaticVars.stacks {
stack.applicationWillResignActive()
}
}
/**
Called when the application will terminate
*/
public class func applicationWillTerminate()
{
SugarRecordLogger.logLevelInfo.log("Notifying the current stack that the app will temrinate")
for stack in StaticVars.stacks {
stack.applicationWillTerminate()
}
}
/**
Called when the application will enter foreground
*/
public class func applicationWillEnterForeground()
{
SugarRecordLogger.logLevelInfo.log("Notifying the current stack that the app will temrinate")
for stack in StaticVars.stacks {
stack.applicationWillEnterForeground()
}
}
/**
Clean up the stack and notifies it using key srKVOCleanedUpNotification
*/
public class func cleanup()
{
for stack in StaticVars.stacks {
stack.cleanup()
}
SugarRecordLogger.logLevelVerbose.log("Cleanup executed")
}
/**
Remove the local database of stacks
*/
public class func removeDatabase()
{
for stack in StaticVars.stacks {
stack.removeDatabase()
}
removeAllStacks()
SugarRecordLogger.logLevelVerbose.log("Database removed")
}
/**
Returns the current version of SugarRecord
- returns: String with the version value
*/
public class func currentVersion() -> String
{
return srSugarRecordVersion
}
//MARK: - Operations
/**
Executes an operation closure in the main thread
- parameter closure: Closure with operations to be executed
*/
public class func operation(stackType: SugarRecordEngine, closure: (context: SugarRecordContext) -> ())
{
operation(inBackground: false, stackType: stackType, closure: closure)
}
/**
Executes an operation closure passing it the context to perform operations
- parameter background: Bool indicating if the operation is in background or not
- parameter closure: Closure with actions to be executed
*/
public class func operation(inBackground background: Bool, stackType: SugarRecordEngine, closure: (context: SugarRecordContext) -> ())
{
let stack: SugarRecordStackProtocol? = stackFortype(stackType)
if stack == nil {
SugarRecord.handle(NSError(domain: "Cannot find an stack for the given type", code: SugarRecordErrorCodes.UserError.rawValue, userInfo: nil))
}
else if !stack!.stackInitialized {
SugarRecordLogger.logLevelWarn.log("The stack hasn't been initialized yet")
return
}
let context: SugarRecordContext? = background ? stack!.backgroundContext(): stack!.mainThreadContext()
if context == nil {
SugarRecord.handle(NSError(domain: "Something went wrong, the stack is set as initialized but there's no contexts", code: SugarRecordErrorCodes.LibraryError.rawValue, userInfo: nil))
}
if background {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
closure(context: context!)
})
}
else {
closure(context: context!)
}
}
// MARK: - SugarRecord Error Handler
/**
Handles an error around the SugarRecordLibrary
Note: It asserts the error
- parameter error: NSError to be processed
*/
internal class func handle(error: NSError?) {
if error == nil { return }
SugarRecordLogger.logLevelFatal.log("Error caught: \(error)")
assert(true, "\(error?.localizedDescription)")
}
/**
Handles an exception around the library
- parameter exception: NSException to be processed
*/
internal class func handle(exception: NSException?) {
if exception == nil { return }
SugarRecordLogger.logLevelError.log("Exception caught: \(exception)")
}
}
|
mit
|
c21d67bee00f649f3ff0ec9b74523eb9
| 28.529412 | 194 | 0.646797 | 4.970297 | false | false | false | false |
kristopherjohnson/KJLunarLander
|
KJLunarLander/LanderSceneController.swift
|
1
|
4526
|
//
// LanderSceneController.swift
// KJLunarLander
//
// Copyright © 2016 Kristopher Johnson. All rights reserved.
//
import SpriteKit
/// Implements the lander game.
class LanderSceneController: NSObject {
fileprivate enum State {
case start
case inProgress
case landed
case destroyed
}
private let view: SKView
private let scene: SKScene
fileprivate let camera: Camera
fileprivate var state = State.start
fileprivate let lander: LanderSprite
fileprivate let surface: SurfaceNode
fileprivate var hud: HUD?
fileprivate var lastHUDUpdateTime: TimeInterval = 0
weak var controlInput: ControlInput?
init(view: SKView) {
self.view = view
scene = SKScene(size: Constant.sceneSize)
scene.backgroundColor = .black
scene.scaleMode = .aspectFit
scene.physicsWorld.gravity = CGVector.zero
camera = Camera()
camera.position = scene.frame.centerPoint
scene.camera = camera
scene.addChild(camera)
view.presentScene(scene)
view.ignoresSiblingOrder = true
// Show SpriteKit diagnostics
if true {
view.showsFPS = true
view.showsDrawCount = true
view.showsNodeCount = true
view.showsQuadCount = true
//view.showsPhysics = true
//view.showsFields = true
}
hud = HUD(parent: camera)
surface = SurfaceNode()
surface.zPosition = ZPosition.surface
scene.addChild(surface)
lander = LanderSprite.sprite(scene: scene,
position: Constant.landerInitialPosition,
velocity: Constant.landerInitialVelocity)
super.init()
scene.delegate = self
scene.physicsWorld.contactDelegate = self
}
}
// MARK: - SKSceneDelegate
extension LanderSceneController: SKSceneDelegate {
public func update(_ currentTime: TimeInterval, for scene: SKScene) {
guard let controlInput = controlInput else { return }
guard let landerBody = lander.physicsBody else { return }
// If lander goes off left or right edge, wrap around to opposite edge.
let sceneWidth = scene.size.width
let landerX = lander.position.x
if landerX < 0 {
lander.wraparoundX(to: sceneWidth - 1)
}
else if landerX > sceneWidth {
lander.wraparoundX(to: 1)
}
// Apply control inputs.
let thrustLevel = controlInput.thrustInput
lander.thrustLevel = thrustLevel
if thrustLevel > 0 {
let thrustForce = controlInput.thrustInput * Constant.landerThrust
let thrustDirection = lander.zRotation + pi2
let thrustVector = CGVector(angle: thrustDirection, length: thrustForce)
landerBody.applyForce(thrustVector)
}
if controlInput.rotationInput != 0 {
let torque = controlInput.rotationInput * Constant.landerTorque
landerBody.applyTorque(torque)
}
// Calculate current altitude above surface.
var altitude: CGFloat = 0.0
if let calculatedAltitude = surface.altitudeOf(point: lander.position) {
altitude = calculatedAltitude - lander.landedPositionHeight
}
// Update camera position and HUD.
camera.follow(focusPosition: lander.position, altitude: altitude)
if let hud = hud {
if (currentTime - lastHUDUpdateTime) > 0.1 {
hud.updateDisplayValues(lander: lander, altitude: altitude)
lastHUDUpdateTime = currentTime
}
}
// State-specific handling
switch state {
case .start:
if thrustLevel > 0.0 {
scene.physicsWorld.gravity = CGVector(dx: 0, dy: Constant.lunarGravity)
state = .inProgress
}
default:
break
}
}
public func didEvaluateActions(for scene: SKScene) {
}
public func didSimulatePhysics(for scene: SKScene) {
}
public func didApplyConstraints(for scene: SKScene) {
}
public func didFinishUpdate(for scene: SKScene) {
}
}
// MARK: - SKPhysicsContactDelegate
extension LanderSceneController: SKPhysicsContactDelegate {
public func didBegin(_ contact: SKPhysicsContact) {
}
public func didEnd(_ contact: SKPhysicsContact) {
}
}
|
mit
|
527c0b91535556fc593b2447386732d1
| 25.30814 | 87 | 0.616354 | 4.723382 | false | false | false | false |
bmichotte/HSTracker
|
HSTracker/AppDelegate.swift
|
1
|
17344
|
//
// AppDelegate.swift
// HSTracker
//
// Created by Benjamin Michotte on 19/02/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Cocoa
import CleanroomLogger
import MASPreferences
import HearthAssets
import HockeySDK
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let hockeyHelper = HockeyHelper()
var appWillRestart = false
var splashscreen: Splashscreen?
var dockMenu = NSMenu(title: "DockMenu")
var appHealth: AppHealth = AppHealth.instance
var coreManager: CoreManager!
var preferences: MASPreferencesWindowController = {
var controllers = [
GeneralPreferences(nibName: "GeneralPreferences", bundle: nil)!,
GamePreferences(nibName: "GamePreferences", bundle: nil)!,
TrackersPreferences(nibName: "TrackersPreferences", bundle: nil)!,
PlayerTrackersPreferences(nibName: "PlayerTrackersPreferences", bundle: nil)!,
OpponentTrackersPreferences(nibName: "OpponentTrackersPreferences", bundle: nil)!,
HSReplayPreferences(nibName: "HSReplayPreferences", bundle: nil)!,
TrackOBotPreferences(nibName: "TrackOBotPreferences", bundle: nil)!
]
let preferences = MASPreferencesWindowController(
viewControllers: controllers,
title: NSLocalizedString("Preferences", comment: ""))
return preferences
}()
func applicationDidFinishLaunching(_ aNotification: Notification) {
// warn user about memory reading
if Settings.showMemoryReadingWarning {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("I understand", comment: ""))
// swiftlint:disable line_length
alert.messageText = NSLocalizedString("HSTracker needs elevated privileges to read data from Hearthstone's memory. If macOS asks you for your system password, do not be alarmed, no changes to your computer will be performed.", comment: "")
// swiftlint:enable line_length
alert.runModal()
Settings.showMemoryReadingWarning = false
}
// create folders in file system
Paths.initDirs()
// initialize realm's database
RealmHelper.initRealm(destination: Paths.HSTracker)
// init debug loggers
var loggers = [LogConfiguration]()
#if DEBUG
let xcodeConfig = ConsoleLogConfiguration(minimumSeverity: .verbose,
stdStreamsMode: .useExclusively,
formatters: [HSTrackerLogFormatter()])
loggers.append(xcodeConfig)
#endif
let path = Paths.logs.path
let severity = Settings.logSeverity
let rotatingConf = RotatingLogFileConfiguration(minimumSeverity: severity,
daysToKeep: 7,
directoryPath: path,
formatters: [HSTrackerLogFormatter()])
loggers.append(rotatingConf)
Log.enable(configuration: loggers)
Log.info?.message("*** Starting \(Version.buildName) ***")
// fix hearthstone log folder path
if Settings.hearthstonePath.hasSuffix("/Logs") {
Settings.hearthstonePath = Settings.hearthstonePath.replace("/Logs", with: "")
}
if Settings.validated() {
loadSplashscreen()
} else {
initalConfig = InitialConfiguration(windowNibName: "InitialConfiguration")
initalConfig?.completionHandler = {
self.loadSplashscreen()
}
initalConfig?.showWindow(nil)
initalConfig?.window?.orderFrontRegardless()
}
}
func applicationWillTerminate(_ notification: Notification) {
coreManager.stopTracking()
if appWillRestart {
let appPath = Bundle.main.bundlePath
let task = Process()
task.launchPath = "/usr/bin/open"
task.arguments = [appPath]
task.launch()
}
}
// MARK: - Application init
func loadSplashscreen() {
NSRunningApplication.current().activate(options: [
.activateAllWindows,
.activateIgnoringOtherApps
])
NSApp.activate(ignoringOtherApps: true)
splashscreen = Splashscreen(windowNibName: "Splashscreen")
let screenFrame = NSScreen.screens()!.first!.frame
let splashscreenWidth: CGFloat = 350
let splashscreenHeight: CGFloat = 250
splashscreen?.window?.setFrame(NSRect(
x: (screenFrame.width / 2) - (splashscreenWidth / 2),
y: (screenFrame.height / 2) - (splashscreenHeight / 2),
width: splashscreenWidth,
height: splashscreenHeight),
display: true)
splashscreen?.showWindow(self)
Log.info?.message("Opening trackers")
coreManager = CoreManager()
DispatchQueue.global().async { [unowned(unsafe) self] in
// load build dates via http request
let buildsOperation = BlockOperation {
BuildDates.loadBuilds(splashscreen: self.splashscreen!)
/*if BuildDates.isOutdated() || !Database.jsonFilesAreValid() {
BuildDates.downloadCards(splashscreen: self.splashscreen!)
}*/
}
// load card tier via http request
let cardTierOperation = BlockOperation {
ArenaHelperSync.checkTierList(splashscreen: self.splashscreen!)
if ArenaHelperSync.isOutdated() || !ArenaHelperSync.jsonFilesAreValid() {
ArenaHelperSync.downloadTierList(splashscreen: self.splashscreen!)
}
}
// load and generate assets from hearthstone files
let assetsOperation = BlockOperation {
DispatchQueue.main.async { [weak self] in
self?.splashscreen?.display(
NSLocalizedString("Loading Hearthstone assets", comment: ""),
indeterminate: true)
}
}
// load and init local database
let databaseOperation = BlockOperation {
let database = Database()
var langs: [Language.Hearthstone] = []
if let language = Settings.hearthstoneLanguage, language != .enUS {
langs += [language]
}
langs += [.enUS]
database.loadDatabase(splashscreen: self.splashscreen!, withLanguages: langs)
}
// build menu
let menuOperation = BlockOperation {
OperationQueue.main.addOperation {
Log.info?.message("Loading menu")
self.buildMenu()
}
}
databaseOperation.addDependency(buildsOperation)
if Settings.useHearthstoneAssets {
databaseOperation.addDependency(assetsOperation)
assetsOperation.addDependency(buildsOperation)
}
var operations = [Operation]()
operations.append(buildsOperation)
operations.append(cardTierOperation)
if Settings.useHearthstoneAssets {
operations.append(assetsOperation)
}
operations.append(databaseOperation)
operations.append(menuOperation)
self.operationQueue = OperationQueue()
self.operationQueue.addOperations(operations, waitUntilFinished: true)
DispatchQueue.main.async { [unowned(unsafe) self] in
self.completeSetup()
}
}
}
/** Finished setup, should only be called once */
private func completeSetup() {
var message: String?
var alertStyle = NSAlertStyle.critical
do {
let canStart = try coreManager.setup()
if !canStart {
message = "You must restart Hearthstone for logs to be used"
alertStyle = .informational
}
} catch HearthstoneLogError.canNotCreateDir {
message = "Can not create Hearthstone config dir"
} catch HearthstoneLogError.canNotReadFile {
message = "Can not read Hearthstone config file"
} catch HearthstoneLogError.canNotCreateFile {
message = "Can not write Hearthstone config file"
} catch {
message = "Unknown error"
}
if let message = message {
splashscreen?.close()
splashscreen = nil
if alertStyle == .critical {
Log.error?.message(message)
}
NSAlert.show(style: alertStyle,
message: NSLocalizedString(message, comment: ""),
forceFront: true)
return
}
coreManager.start()
let events = [
"reload_decks": #selector(AppDelegate.reloadDecks(_:)),
"hstracker_language": #selector(AppDelegate.languageChange(_:))
]
for (event, selector) in events {
NotificationCenter.default.addObserver(self,
selector: selector,
name: NSNotification.Name(rawValue: event),
object: nil)
}
if let activeDeck = Settings.activeDeck {
self.coreManager.game.set(activeDeckId: activeDeck, autoDetected: false)
}
splashscreen?.close()
splashscreen = nil
}
func reloadDecks(_ notification: Notification) {
buildMenu()
}
func languageChange(_ notification: Notification) {
let msg = "You must restart HSTracker for the language change to take effect"
NSAlert.show(style: .informational,
message: NSLocalizedString(msg, comment: ""))
appWillRestart = true
NSApplication.shared().terminate(nil)
exit(0)
}
// MARK: - Menu
/**
Builds the menu and its items.
*/
func buildMenu() {
DispatchQueue.main.async { [unowned(unsafe) self] in
guard let decks = RealmHelper.getActiveDecks() else {
return
}
// build main menu
// ---------------
let mainMenu = NSApplication.shared().mainMenu
let deckMenu = mainMenu?.item(withTitle: NSLocalizedString("Decks", comment: ""))
deckMenu?.submenu?.removeAllItems()
deckMenu?.submenu?.addItem(withTitle: NSLocalizedString("Deck Manager", comment: ""),
action: #selector(AppDelegate.openDeckManager(_:)),
keyEquivalent: "d")
let saveMenus = NSMenu()
saveMenus.addItem(withTitle: NSLocalizedString("Save Current Deck", comment: ""),
action: #selector(AppDelegate.saveCurrentDeck(_:)),
keyEquivalent: "").tag = 2
saveMenus.addItem(withTitle: NSLocalizedString("Save Opponent's Deck", comment: ""),
action: #selector(AppDelegate.saveCurrentDeck(_:)),
keyEquivalent: "").tag = 1
deckMenu?.submenu?.addItem(withTitle: NSLocalizedString("Save", comment: ""),
action: nil,
keyEquivalent: "").submenu = saveMenus
deckMenu?.submenu?.addItem(withTitle: NSLocalizedString("Clear", comment: ""),
action: #selector(AppDelegate.clearTrackers(_:)),
keyEquivalent: "R")
// build dock menu
// ---------------
if let decksmenu = self.dockMenu.item(withTag: 1) {
decksmenu.submenu?.removeAllItems()
} else {
let decksmenu = NSMenuItem(title: NSLocalizedString("Decks", comment: ""),
action: nil, keyEquivalent: "")
decksmenu.tag = 1
decksmenu.submenu = NSMenu()
self.dockMenu.addItem(decksmenu)
}
let dockdeckMenu = self.dockMenu.item(withTag: 1)
// add deck items to main and dock menu
// ------------------------------------
deckMenu?.submenu?.addItem(NSMenuItem.separator())
for (playerClass, _decks) in decks
.sorted(by: { NSLocalizedString($0.0.rawValue.lowercased(), comment: "")
< NSLocalizedString($1.0.rawValue.lowercased(), comment: "") }) {
// create menu item for all decks in this class
let classmenuitem = NSMenuItem(title: NSLocalizedString(
playerClass.rawValue.lowercased(),
comment: ""), action: nil, keyEquivalent: "")
let classsubMenu = NSMenu()
_decks.filter({ $0.isActive == true })
.sorted(by: {$0.name.lowercased() < $1.name.lowercased() }).forEach({
let item = classsubMenu
.addItem(withTitle: $0.name,
action: #selector(AppDelegate.playDeck(_:)),
keyEquivalent: "")
item.representedObject = $0
})
classmenuitem.submenu = classsubMenu
deckMenu?.submenu?.addItem(classmenuitem)
if let menuitemcopy = classmenuitem.copy() as? NSMenuItem {
dockdeckMenu?.submenu?.addItem(menuitemcopy)
}
}
let replayMenu = mainMenu?.item(withTitle: NSLocalizedString("Replays", comment: ""))
let replaysMenu = replayMenu?.submenu?.item(withTitle: NSLocalizedString("Last replays",
comment: ""))
replaysMenu?.submenu?.removeAllItems()
replaysMenu?.isEnabled = false
if Settings.hsReplayUploadToken != nil,
let statistics = RealmHelper.getValidStatistics() {
replaysMenu?.isEnabled = statistics.count > 0
let max = min(statistics.count, 10)
for i in 0..<max {
let stat = statistics[i]
var deckName = ""
if let deck = stat.deck.first, !deck.name.isEmpty {
deckName = deck.name
}
let opponentName = stat.opponentName.isEmpty ? "unknow" : stat.opponentName
let opponentClass = stat.opponentHero
var name = ""
if !deckName.isEmpty {
name = "\(deckName) vs"
} else {
name = "Vs"
}
name += " \(opponentName)"
if opponentClass != .neutral {
name += " (\(NSLocalizedString(opponentClass.rawValue, comment: "")))"
}
if let item = replaysMenu?.submenu?
.addItem(withTitle: name,
action: #selector(self.showReplay(_:)),
keyEquivalent: "") {
item.representedObject = stat.hsReplayId
}
}
}
let windowMenu = mainMenu?.item(withTitle: NSLocalizedString("Window", comment: ""))
let item = windowMenu?.submenu?.item(withTitle: NSLocalizedString("Lock windows",
comment: ""))
item?.title = NSLocalizedString(Settings.windowsLocked ? "Unlock windows" : "Lock windows",
comment: "")
}
}
func showReplay(_ sender: NSMenuItem) {
if let replayId = sender.representedObject as? String {
HSReplayManager.showReplay(replayId: replayId)
}
}
@IBAction func importReplay(_ sender: NSMenuItem) {
let panel = NSOpenPanel()
panel.directoryURL = Paths.replays
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
panel.allowedFileTypes = ["hdtreplay"]
panel.begin { (returnCode) in
if returnCode == NSFileHandlingPanelOKButton {
for filename in panel.urls {
let path = filename.path
LogUploader.upload(filename: path, completion: { (result) in
if case UploadResult.successful(let replayId) = result {
HSReplayManager.showReplay(replayId: replayId)
}
})
}
}
}
}
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
return self.dockMenu
}
func playDeck(_ sender: NSMenuItem) {
if let deck = sender.representedObject as? Deck {
let deckId = deck.deckId
self.coreManager.game.set(activeDeckId: deckId, autoDetected: false)
}
}
@IBAction func openDeckManager(_ sender: AnyObject) {
if deckManager == nil {
deckManager = DeckManager(windowNibName: "DeckManager")
deckManager?.game = coreManager.game
}
deckManager?.showWindow(self)
}
@IBAction func clearTrackers(_ sender: AnyObject) {
coreManager.game.removeActiveDeck()
}
@IBAction func saveCurrentDeck(_ sender: AnyObject) {
switch sender.tag {
case 1: // Opponent
saveDeck(coreManager.game.opponent)
case 2: // Self
saveDeck(coreManager.game.player)
default:
break
}
}
private func saveDeck(_ player: Player) {
if let playerClass = player.playerClass {
if deckManager == nil {
deckManager = DeckManager(windowNibName: "DeckManager")
}
let deck = Deck()
deck.playerClass = playerClass
deck.name = player.name ?? "Custom \(playerClass)"
let playerCardlist = player.playerCardList.filter({ $0.collectible == true })
RealmHelper.add(deck: deck, with: playerCardlist)
deckManager?.currentDeck = deck
deckManager?.editDeck(self)
}
}
@IBAction func openPreferences(_ sender: AnyObject) {
preferences.showWindow(self)
}
@IBAction func lockWindows(_ sender: AnyObject) {
let mainMenu = NSApplication.shared().mainMenu
let windowMenu = mainMenu?.item(withTitle: NSLocalizedString("Window", comment: ""))
let text = Settings.windowsLocked ? "Unlock windows" : "Lock windows"
let item = windowMenu?.submenu?.item(withTitle: NSLocalizedString(text, comment: ""))
Settings.windowsLocked = !Settings.windowsLocked
item?.title = NSLocalizedString(Settings.windowsLocked ? "Unlock windows" : "Lock windows",
comment: "")
}
#if DEBUG
var windowMove: WindowMove?
@IBAction func openDebugPositions(_ sender: AnyObject) {
if windowMove == nil {
windowMove = WindowMove(windowNibName: "WindowMove", windowManager: coreManager.game.windowManager)
}
windowMove?.showWindow(self)
}
#endif
@IBAction func closeWindow(_ sender: AnyObject) {
}
@IBAction func openReplayDirectory(_ sender: AnyObject) {
NSWorkspace.shared().activateFileViewerSelecting([Paths.replays])
}
}
extension AppDelegate: SUUpdaterDelegate {
func feedParameters(for updater: SUUpdater,
sendingSystemProfile sendingProfile: Bool) -> [[String : String]] {
var parameters: [[String : String]] = []
for data: Any in BITSystemProfile.shared().systemUsageData() {
if let dict = data as? [String: String] {
parameters.append(dict)
}
}
return parameters
}
}
|
mit
|
c4e0585b15cc193126d206f65f7f0a96
| 32.480695 | 242 | 0.65254 | 4.167988 | false | false | false | false |
facebook/css-layout
|
YogaKit/YogaKitSample/YogaKitSample/Views/SingleLabelCollectionCell.swift
|
2
|
1326
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import UIKit
import YogaKit
final class SingleLabelCollectionCell: UICollectionViewCell {
let label: UILabel = UILabel(frame: .zero)
override init(frame: CGRect) {
super.init(frame: frame)
contentView.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .column
layout.justifyContent = .flexEnd
}
label.textAlignment = .center
label.numberOfLines = 1
label.yoga.isIncludedInLayout = false
contentView.addSubview(label)
let border = UIView(frame: .zero)
border.backgroundColor = .lightGray
border.configureLayout { (layout) in
layout.isEnabled = true
layout.height = 0.5
layout.marginHorizontal = 25
}
contentView.addSubview(border)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.yoga.applyLayout(preservingOrigin: false)
label.frame = contentView.bounds
}
}
|
bsd-3-clause
|
35f3db4a04cbc89f6b4f6974d5a7e25c
| 26.625 | 66 | 0.641026 | 4.685512 | false | false | false | false |
TCA-Team/iOS
|
TUM Campus App/AppDelegate.swift
|
1
|
1717
|
//
// AppDelegate.swift
// TUM Campus App
//
// Created by Mathias Quintero on 10/28/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import UIKit
import Firebase
import Crashlytics
import Fabric
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
initFirebase()
setupAppearance()
conditionallyShowLoginViewController()
return true
}
private func initFirebase() {
FirebaseApp.configure()
}
private func setupAppearance() {
UINavigationBar.appearance().barTintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: Constants.tumBlue]
UINavigationBar.appearance().tintColor = Constants.tumBlue
}
private func conditionallyShowLoginViewController() {
if !PersistentUser.isLoggedIn && !Usage.value {
let loginViewController = ViewControllerProvider.loginNavigationViewController
window?.makeKeyAndVisible()
window?.rootViewController?.present(loginViewController, animated: true, completion: nil)
}
}
func application(_ application: UIApplication,
supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return UIInterfaceOrientationMask.portrait
} else {
return UIInterfaceOrientationMask.all
}
}
}
|
gpl-3.0
|
6464f0977d3ad115a9853511b7a3561a
| 30.777778 | 145 | 0.691725 | 5.758389 | false | false | false | false |
dsmelov/simsim
|
SimSim/Entities/AppGroup.swift
|
1
|
1795
|
//
// AppGroup.swift
// SimSim
//
import Foundation
//============================================================================
class AppGroup
{
private let uuid: String
let path: String
let identifier: String
//----------------------------------------------------------------------------
var isAppleAppGroup: Bool
{
return identifier.isEmpty ||
identifier.starts(with: "com.apple") ||
identifier.starts(with: "group.com.apple") ||
identifier.starts(with: "group.is.workflow") ||
identifier.starts(with: "243LU875E5.groups.com.apple")
}
//----------------------------------------------------------------------------
private init(uuid: String, path: String, identifier: String)
{
self.uuid = uuid
self.path = path
self.identifier = identifier
}
//----------------------------------------------------------------------------
convenience init?(dictionary: [AnyHashable : Any], simulator: Simulator)
{
guard let uuid = dictionary[Tools.Keys.fileName] as? String else
{
return nil
}
let path = simulator.pathForAppGroup(withUUID: uuid)
let plistPath = path + ".com.apple.mobile_container_manager.metadata.plist"
guard let plistData = try? Data(contentsOf: URL(fileURLWithPath: plistPath)) else
{
return nil
}
guard let metadataPlist = try? PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as? [String: Any] else
{
return nil
}
let identifier = metadataPlist["MCMMetadataIdentifier"] as! String
self.init(uuid: uuid, path: path, identifier: identifier)
}
}
|
mit
|
93b455b9e978aedadd1f9b027b603a75
| 29.948276 | 143 | 0.493593 | 5.218023 | false | false | false | false |
nessBautista/iOSBackup
|
iOSNotebook/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift
|
11
|
4450
|
//
// UISearchBar+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import RxSwift
import UIKit
extension Reactive where Base: UISearchBar {
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<UISearchBar, UISearchBarDelegate> {
return RxSearchBarDelegateProxy.proxy(for: base)
}
/// Reactive wrapper for `text` property.
public var text: ControlProperty<String?> {
return value
}
/// Reactive wrapper for `text` property.
public var value: ControlProperty<String?> {
let source: Observable<String?> = Observable.deferred { [weak searchBar = self.base as UISearchBar] () -> Observable<String?> in
let text = searchBar?.text
return (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty())
.map { a in
return a[1] as? String
}
.startWith(text)
}
let bindingObserver = Binder(self.base) { (searchBar, text: String?) in
searchBar.text = text
}
return ControlProperty(values: source, valueSink: bindingObserver)
}
/// Reactive wrapper for `selectedScopeButtonIndex` property.
public var selectedScopeButtonIndex: ControlProperty<Int> {
let source: Observable<Int> = Observable.deferred { [weak source = self.base as UISearchBar] () -> Observable<Int> in
let index = source?.selectedScopeButtonIndex ?? 0
return (source?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty())
.map { a in
return try castOrThrow(Int.self, a[1])
}
.startWith(index)
}
let bindingObserver = Binder(self.base) { (searchBar, index: Int) in
searchBar.selectedScopeButtonIndex = index
}
return ControlProperty(values: source, valueSink: bindingObserver)
}
#if os(iOS)
/// Reactive wrapper for delegate method `searchBarCancelButtonClicked`.
public var cancelButtonClicked: ControlEvent<Void> {
let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarCancelButtonClicked(_:)))
.map { _ in
return ()
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `searchBarBookmarkButtonClicked`.
public var bookmarkButtonClicked: ControlEvent<Void> {
let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarBookmarkButtonClicked(_:)))
.map { _ in
return ()
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `searchBarResultsListButtonClicked`.
public var resultsListButtonClicked: ControlEvent<Void> {
let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarResultsListButtonClicked(_:)))
.map { _ in
return ()
}
return ControlEvent(events: source)
}
#endif
/// Reactive wrapper for delegate method `searchBarSearchButtonClicked`.
public var searchButtonClicked: ControlEvent<Void> {
let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarSearchButtonClicked(_:)))
.map { _ in
return ()
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `searchBarTextDidBeginEditing`.
public var textDidBeginEditing: ControlEvent<Void> {
let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidBeginEditing(_:)))
.map { _ in
return ()
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `searchBarTextDidEndEditing`.
public var textDidEndEditing: ControlEvent<Void> {
let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:)))
.map { _ in
return ()
}
return ControlEvent(events: source)
}
}
#endif
|
cc0-1.0
|
556ac4e4775a0c226af3d26a5203b9ae
| 34.879032 | 156 | 0.662396 | 4.954343 | false | false | false | false |
xiongxiong/TagList
|
Framework/SwiftTagList/TagPresentables.swift
|
1
|
2042
|
//
// TagPresentables.swift
// TagList
//
// Created by 王继荣 on 16/12/2016.
// Copyright © 2016 wonderbear. All rights reserved.
//
import UIKit
public struct TagPresentableText: TagPresentable {
public private(set) var tag: String = ""
public var isSelected: Bool = false
private var onInit: ((TagContentText) -> Void)?
public init(tag: String, onInit: ((TagContentText) -> Void)? = nil) {
self.tag = tag
self.onInit = onInit
}
public func createTagContent() -> TagContent {
let tagContent = TagContentText(tag: tag)
onInit?(tagContent)
return tagContent
}
}
public struct TagPresentableIcon: TagPresentable {
public private(set) var tag: String
public private(set) var icon: String
public private(set) var height: CGFloat
public var isSelected: Bool = false
private var onInit: ((TagContentIcon) -> Void)?
public init(tag: String, icon: String, height: CGFloat, onInit: ((TagContentIcon) -> Void)? = nil) {
self.tag = tag
self.icon = icon
self.height = height
self.onInit = onInit
}
public func createTagContent() -> TagContent {
let tagContent = TagContentIcon(tag: tag, height: height)
tagContent.icon.image = UIImage(named: icon)
onInit?(tagContent)
return tagContent
}
}
public struct TagPresentableIconText: TagPresentable {
public private(set) var tag: String = ""
public private(set) var icon: String = ""
public var isSelected: Bool = false
private var onInit: ((TagContentIconText) -> Void)?
public init(tag: String, icon: String, onInit: ((TagContentIconText) -> Void)? = nil) {
self.tag = tag
self.icon = icon
self.onInit = onInit
}
public func createTagContent() -> TagContent {
let tagContent = TagContentIconText(tag: tag)
tagContent.icon.image = UIImage(named: icon)
onInit?(tagContent)
return tagContent
}
}
|
mit
|
7c5e0599c9ee010bf73a8a1d83d02a75
| 27.263889 | 104 | 0.629975 | 4.037698 | false | false | false | false |
rustedivan/tapmap
|
tapmap/App/MapViewController.swift
|
1
|
10697
|
//
// GameViewController.swift
// tapmap
//
// Created by Ivan Milles on 2017-03-31.
// Copyright © 2017 Wildbrain. All rights reserved.
//
import MetalKit
import fixa
class MapViewController: UIViewController, MTKViewDelegate {
@IBOutlet weak var metalView: MTKView!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var placeName: UILabel!
@IBOutlet var labelView: LabelView!
var renderers: MetalRenderer!
// Presentation
var world: RuntimeWorld
var inputOverlayView: UIView!
// Navigation
var zoom: Float = 1.0
var zoomLimits: (Float, Float) = (1.0, 1.0)
var offset: CGPoint = .zero
let mapSpace = CGRect(x: -180.0, y: -90.0, width: 360.0, height: 180.0)
var mapFrame = CGRect.zero
var lastRenderFrame: Int = Int.max
var needsRender: Bool = true { didSet {
if needsRender { metalView.isPaused = false }
}}
var renderRect: Aabb {
return visibleLongLat(viewBounds: view.bounds)
}
// Rendering
var geometryStreamer: GeometryStreamer
required init?(coder: NSCoder) {
let path = Bundle.main.path(forResource: "world", ofType: "geo")!
guard let streamer = GeometryStreamer(attachFile: path) else {
print("Could not attach geometry streamer to \(path)")
return nil
}
self.geometryStreamer = streamer
let geoWorld = geometryStreamer.loadGeoWorld()
let worldTree = geometryStreamer.loadWorldTree()
world = RuntimeWorld(withGeoWorld: geoWorld)
let userState = AppDelegate.sharedUserState
let uiState = AppDelegate.sharedUIState
userState.delegate = world
userState.buildWorldAvailability(withWorld: world)
uiState.delegate = world
uiState.buildQuadTree(withTree: worldTree)
super.init(coder: coder)
NotificationCenter.default.addObserver(forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
object: NSUbiquitousKeyValueStore.default,
queue: nil,
using: takeCloudProfile)
NotificationCenter.default.addObserver(forName: FixaStream.DidUpdateValues, object: nil, queue: nil) { _ in
self.labelView.isHidden = !Stylesheet.shared.renderLabels.value;
self.needsRender = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
let metalView = view as! MTKView
renderers = MetalRenderer(in: metalView, forWorld: world)
geometryStreamer.metalDevice = renderers.device
metalView.delegate = self
// Scroll view setup
let inputOverlayViewW = view.frame.width
let inputOverlayViewH = view.frame.width * (mapSpace.height / mapSpace.width) // View-size, map-aspect
let inputOverlayViewFrame = CGRect(x: 0.0, y: 0.0, width: inputOverlayViewW, height: inputOverlayViewH)
inputOverlayView = UIView(frame: inputOverlayViewFrame)
scrollView.contentSize = inputOverlayView.frame.size
scrollView.addSubview(inputOverlayView)
inputOverlayView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
// Calculate view-space frame of the map (scale map to fit in view, calculate the vertical offset to center it)
let heightDiff = inputOverlayView.bounds.height - (mapSpace.height / (mapSpace.width / inputOverlayView.bounds.width))
mapFrame = inputOverlayView.bounds.insetBy(dx: 0.0, dy: heightDiff / 2.0)
let limits = mapZoomLimits(viewSize: scrollView.bounds.size, inputViewSize: inputOverlayViewFrame.size)
scrollView.minimumZoomScale = limits.0
scrollView.zoomScale = limits.0
scrollView.maximumZoomScale = limits.1
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
zoomLimits = (Float(limits.0), Float(limits.1))
renderers.zoomLevel = Float(scrollView.zoomScale)
labelView.isHidden = !Stylesheet.shared.renderLabels.value
labelView.initPoiMarkers(withVisibleContinents: world.availableContinents,
countries: world.availableCountries,
provinces: world.availableProvinces)
// Prepare UI for rendering the map
AppDelegate.sharedUIState.cullWorldTree(focus: renderRect)
needsRender = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func handleTap(sender: UITapGestureRecognizer) {
needsRender = true
if sender.state == .ended {
let viewP = sender.location(in: inputOverlayView)
let mapP = mapPoint(viewP, from: inputOverlayView.bounds, to: mapFrame, space: mapSpace)
let tapPoint = Vertex(Float(mapP.x), Float(mapP.y))
let userState = AppDelegate.sharedUserState
let uiState = AppDelegate.sharedUIState
GeometryCounters.begin()
defer { GeometryCounters.end() }
// Filter out sets of closed, visible regions that contain the tap
let candidateContinents = Set(world.visibleContinents.filter { boxContains($0.value.aabb, tapPoint) }.values)
let candidateCountries = Set(world.visibleCountries.filter { boxContains($0.value.aabb, tapPoint) }.values)
let candidateProvinces = Set(world.visibleProvinces.filter { boxContains($0.value.aabb, tapPoint) }.values)
if let hitHash = pickFromTessellations(p: tapPoint, candidates: candidateContinents) {
let hitContinent = world.availableContinents[hitHash]!
if processSelection(of: hitContinent, user: userState, ui: uiState) {
uiState.clearSelection()
renderers.selectionRenderer.clear()
renderers.effectRenderer.addOpeningEffect(for: hitContinent.geographyId.hashed)
processVisit(of: hitContinent, user: userState, ui: uiState)
}
} else if let hitHash = pickFromTessellations(p: tapPoint, candidates: candidateCountries) {
let hitCountry = world.availableCountries[hitHash]!
if processSelection(of: hitCountry, user: userState, ui: uiState) {
uiState.clearSelection()
renderers.selectionRenderer.clear()
renderers.effectRenderer.addOpeningEffect(for: hitCountry.geographyId.hashed)
processVisit(of: hitCountry, user: userState, ui: uiState)
}
} else if let hitHash = pickFromTessellations(p: tapPoint, candidates: candidateProvinces) {
let hitProvince = world.availableProvinces[hitHash]!
_ = processSelection(of: hitProvince, user: userState, ui: uiState)
} else {
uiState.clearSelection()
renderers.selectionRenderer.clear()
}
uiState.cullWorldTree(focus: renderRect)
}
}
func processSelection<T:GeoIdentifiable>(of hit: T, user: UserState, ui: UIState) -> Bool {
placeName.text = hit.name
if ui.selected(hit) {
user.visitPlace(hit)
return true
} else {
ui.selectRegion(hit)
renderers.selectionRenderer.selectionHash = hit.geographyId.hashed
return false
}
}
func processVisit<T:GeoNode & GeoPlaceContainer>(of hit: T, user: UserState, ui: UIState)
where T.SubType: GeoPlaceContainer {
user.openPlace(hit)
renderers.selectionRenderer.clear()
if geometryStreamer.renderPrimitive(for: hit.geographyId.hashed) != nil {
geometryStreamer.evictPrimitive(for: hit.geographyId.hashed)
}
renderers.poiRenderer.updatePoiGroups(for: hit, with: hit.children)
labelView.updatePoiMarkers(for: hit, with: hit.children)
}
func prepareFrame() {
renderers.updateProjection(viewSize: scrollView.bounds.size,
mapSize: mapSpace.size,
centeredOn: offset,
zoomedTo: zoom)
let zoomRate = (zoom - zoomLimits.0) / (zoomLimits.1 - zoomLimits.0) // How far down the zoom scale are we?
renderers.prepareFrame(forWorld: world, zoomRate: zoomRate, inside: renderRect)
labelView.updateLabels(for: renderers.poiRenderer.activePoiHashes,
inArea: renderRect,
atZoom: zoom,
projection: mapToView)
geometryStreamer.updateLodLevel() // Must run after requests have been filed in renderers.prepareFrame, otherwise glitch when switching LOD level
geometryStreamer.updateStreaming()
needsRender = geometryStreamer.streaming ? true : needsRender
if renderers.shouldIdle(appUpdated: needsRender) {
metalView.isPaused = true
}
}
func draw(in view: MTKView) {
prepareFrame()
renderers.render(forWorld: world, into: view)
needsRender = false
}
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
renderers.updateProjection(viewSize: size,
mapSize: mapSpace.size,
centeredOn: offset,
zoomedTo: zoom)
}
}
extension MapViewController : UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return inputOverlayView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
zoom = Float(scrollView.zoomScale)
geometryStreamer.zoomedTo(zoom)
renderers.zoomLevel = zoom
AppDelegate.sharedUIState.cullWorldTree(focus: renderRect)
needsRender = true
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
offset = scrollView.contentOffset
AppDelegate.sharedUIState.cullWorldTree(focus: renderRect)
needsRender = true
}
func visibleLongLat(viewBounds: CGRect) -> Aabb {
let focusBox = viewBounds // .insetBy(dx: 100.0, dy: 100.0)
let bottomLeft = CGPoint(x: focusBox.minX, y: focusBox.minY)
let topRight = CGPoint(x: focusBox.maxX, y: focusBox.maxY)
let worldCorners = [bottomLeft, topRight].map({ (p: CGPoint) -> CGPoint in
let viewP = view.convert(p, to: inputOverlayView)
return mapPoint(viewP,
from: inputOverlayView.bounds,
to: mapFrame,
space: mapSpace)
})
return Aabb(loX: Float(worldCorners[0].x),
loY: Float(worldCorners[1].y),
hiX: Float(worldCorners[1].x),
hiY: Float(worldCorners[0].y))
}
var mapToView: ((Vertex) -> CGPoint) {
return { (p: Vertex) -> CGPoint in
let wRatio = self.mapFrame.width / self.mapSpace.width
let hRatio = self.mapFrame.height / self.mapSpace.height
let mp = projectPoint(CGPoint(x: CGFloat(p.x), y: CGFloat(p.y)),
from: self.inputOverlayView.bounds,
to: self.mapFrame,
space: self.mapSpace,
wRatio: wRatio, hRatio: hRatio)
return self.view.convert(mp, from: self.inputOverlayView)
}
}
}
// MARK: iCloud
extension MapViewController {
func takeCloudProfile(notification: Notification) {
if let diff = mergeCloudProfile(notification: notification, world: world) {
let userState = AppDelegate.sharedUserState
let uiState = AppDelegate.sharedUIState
needsRender = true
for newContinent in diff.continentVisits {
processVisit(of: newContinent, user: userState, ui: uiState)
}
for newCountry in diff.countryVisits {
processVisit(of: newCountry, user: userState, ui: uiState)
}
for _ in diff.provinceVisits {
// No-op
}
uiState.cullWorldTree(focus: renderRect)
}
}
}
|
mit
|
369e577945ecd7be1fd6095c179ba1df
| 34.30033 | 147 | 0.723261 | 3.749036 | false | false | false | false |
iOS-Swift-Developers/Swift
|
基础语法/结构体/main.swift
|
1
|
3112
|
//
// main.swift
// 结构体
//
// Created by 韩俊强 on 2017/6/12.
// Copyright © 2017年 HaRi. All rights reserved.
//
import Foundation
/*
结构体:
结构体是用于封装不同或相同类型的数据的, Swift中的结构体是一类类型, 可以定义属性和方法(甚至构造方法和析构方法等)
格式:
struct 结构体名称 {
结构体属性和方法
}
*/
struct Rect {
var width: Double = 0.0
var height:Double = 0.0
}
// 如果结构体的属性有默认值, 可以直接使用()构造一个结构体
// 如果结构体的属性没有默认值, 必须使用逐一构造器实例化结构体
var r = Rect()
print("width = \(r.width), height = \(r.height)")
// 结构体属性访问 使用语法
r.width = 99.9
r.height = 120.5
print("width = \(r.width), height = \(r.height)")
/*
结构体构造器
Swift中的结构体和类跟其它面向对象语言一样都有构造函数, 而OC是没有的
Swift要求实例化一个结构体或类的时候,所有的成员变量都必须有初始值, 构造函数的意义就是用于初始化所有成员变量的, 而不是分配内存, 分配内存是系统帮我们做的.
如果结构体中的所有属性都有默认值, 可以调用()构造一个结构体实例
如果结构体中的属性没有默认值, 可以自定义构造器, 并在构造器中给所有的属性赋值
其实结构体有一个默认的逐一构造器, 用于在初始化时给所有属性赋值
*/
struct Rect2 {
var width:Double
var height:Double = 0.0
}
// 逐一构造器
var r1 = Rect2(width: 10.0, height: 10.0)
// 错误写法1: 顺序必须和结构体中成员的顺序一致
//var r1 = Rect2(height: 10.0, width: 10.0) // Error!
// 错误写法2: 必须包含所有成员
//var r1 = Rect2(width: 10.0) //Error!
/*
结构体中定义成员方法
在C和OC中结构体只有属性, 而Swift中结构体中还可以定义方法
*/
struct Rect3 {
var width:Double
var height:Double = 0.0
// 1.给结构体定义一个方法, 该方法属于该结构体
// 2.结构体中的成员方法必须使用某个实例调用
// 3.成员方法可以访问成员属性
func getWidth() -> Double {
return width
}
}
var r2 = Rect3(width: 10.0, height: 10.0)
//结构体中的成员方法是和某个实例对象绑定在一起的, so, 谁调用, 方法中访问的属性就是谁
// 取得r2这个对象的宽度
print(r2.getWidth())
var r3 = Rect3(width: 50.0, height: 30.0)
// 取得r3这个对象的宽度
print(r3.getWidth())
/** 结构体是值类型 **/
struct Rect4 {
var width:Double
var height:Double = 0.0
func show() -> Void {
print("width = \(width) height = \(height)")
}
}
var r4 = Rect4(width: 10.0, height: 10.0)
var r5 = r4
print(r4)
print(r5)
/*
赋值有两种情况
1.指向同一块存储空间
2.两个不同实例, 但内容相同
*/
r4.show()
r5.show()
r4.width = 20.0
// 结构体是值类型, 结构体之间的赋值其实是将r4中的值完全拷贝一份到r5中, 所以他们两个是不同的实例
r4.show()
r5.show()
|
mit
|
1ee2688917cdd1feb27d3d8b77670f40
| 16.572727 | 83 | 0.66477 | 2.274118 | false | false | false | false |
steve-holmes/music-app-2
|
MusicApp/Modules/Search/SearchGeneralViewController.swift
|
1
|
7713
|
//
// SearchGeneralViewController.swift
// MusicApp
//
// Created by Hưng Đỗ on 7/11/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import XLPagerTabStrip
import RxSwift
import RxCocoa
import RxDataSources
import Action
import NSObject_Rx
class SearchGeneralViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var searchController: UISearchController!
var store: SearchStore!
var action: SearchAction!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
bindStore()
bindAction()
}
fileprivate let SongSection = 0
fileprivate let PlaylistSection = 1
fileprivate let VideoSection = 2
fileprivate lazy var dataSource: RxTableViewSectionedReloadDataSource<SectionModel<String, SearchItem>> = {
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, SearchItem>>()
dataSource.configureCell = { dataSource, tableView, indexPath, item in
if indexPath.section == self.SongSection, case let .song(song) = item {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SongCell.self), for: indexPath)
if let cell = cell as? SongCell {
let contextAction = CocoaAction { _ in
return self.action.onContextButtonTap.execute(song).map { _ in }
}
cell.configure(name: song.name, singer: song.singer, contextAction: contextAction)
}
return cell
}
if indexPath.section == self.PlaylistSection, case let .playlist(playlist) = item {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PlaylistDetailCell.self), for: indexPath)
if let cell = cell as? PlaylistDetailCell {
cell.configure(name: playlist.name, singer: playlist.singer, image: playlist.avatar)
}
return cell
}
if indexPath.section == self.VideoSection , case let .video(video) = item {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: VideoItemCell.self), for: indexPath)
if let cell = cell as? VideoItemCell {
cell.configure(name: video.name, singer: video.singer, image: video.avatar)
}
return cell
}
dataSource.titleForHeaderInSection = { dataSource, section in dataSource[section].model }
return UITableViewCell()
}
return dataSource
}()
}
extension SearchGeneralViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == SongSection { return 44 }
if indexPath.section == PlaylistSection { return 60 }
if indexPath.section == VideoSection { return 80 }
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == SongSection {
let songHeader = SearchGeneralSectionHeaderView(frame: CGRect(
origin: .zero,
size: CGSize(width: tableView.bounds.width, height: 35)
))
songHeader.title = "Bài hát"
songHeader.action = CocoaAction { [weak self] _ in self?.action.searchStateChange.execute(.song) ?? .empty() }
return songHeader
}
if section == PlaylistSection {
let playlistHeader = SearchGeneralSectionHeaderView(frame: CGRect(
origin: .zero,
size: CGSize(width: tableView.bounds.width, height: 35)
))
playlistHeader.title = "Playlist"
playlistHeader.action = CocoaAction { [weak self] _ in self?.action.searchStateChange.execute(.playlist) ?? .empty() }
return playlistHeader
}
if section == VideoSection {
let videoHeader = SearchGeneralSectionHeaderView(frame: CGRect(
origin: .zero,
size: CGSize(width: tableView.bounds.width, height: 35)
))
videoHeader.title = "Video"
videoHeader.action = CocoaAction { [weak self] _ in self?.action.searchStateChange.execute(.video) ?? .empty() }
return videoHeader
}
return nil
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
}
extension SearchGeneralViewController: IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return "Tất cả"
}
}
extension SearchGeneralViewController {
func bindStore() {
bindSearchResult()
}
private func bindSearchResult() {
store.info.asObservable()
.map { ($0.songs ?? [], $0.playlists ?? [], $0.videos ?? []) }
.filter { !$0.0.isEmpty && !$0.1.isEmpty && !$0.2.isEmpty }
.map { songs, playlists, videos in [
SectionModel(model: "Songs", items: songs.map { SearchItem.song($0) }),
SectionModel(model: "Playlists", items: playlists.map { SearchItem.playlist($0) }),
SectionModel(model: "Videos", items: videos.map { SearchItem.video($0) })
]}
.bind(to: tableView.rx.items(dataSource: dataSource))
.addDisposableTo(rx_disposeBag)
}
}
extension SearchGeneralViewController {
func bindAction() {
tableView.rx.modelSelected(SearchItem.self)
.filter { item in
if case .song(_) = item { return true } else { return false }
}
.map { item -> Song? in
if case let .song(song) = item { return song } else { return nil }
}
.subscribe(onNext: { [weak self] song in
guard let song = song else { return }
self?.searchController.setInactive()
self?.action.songDidSelect.execute(song)
})
.addDisposableTo(rx_disposeBag)
tableView.rx.modelSelected(SearchItem.self)
.filter { item in
if case .playlist(_) = item { return true } else { return false }
}
.map { item -> Playlist? in
if case let .playlist(playlist) = item { return playlist } else { return nil }
}
.subscribe(onNext: { [weak self] playlist in
guard let playlist = playlist else { return }
self?.searchController.setInactive()
self?.action.playlistDidSelect.execute(playlist)
})
.addDisposableTo(rx_disposeBag)
tableView.rx.modelSelected(SearchItem.self)
.filter { item in
if case .video(_) = item { return true } else { return false }
}
.map { item -> Video? in
if case let .video(video) = item { return video } else { return nil }
}
.subscribe(onNext: { [weak self] video in
guard let video = video else { return }
self?.searchController.setInactive()
self?.action.videoDidSelect.execute(video)
})
.addDisposableTo(rx_disposeBag)
}
}
|
mit
|
ae2739133cc011e3af6b854bd54ed312
| 36.570732 | 133 | 0.579849 | 5.104042 | false | false | false | false |
victorchee/CollectionView
|
DecorationSectionCollectionView/DecorationSectionCollectionView/ViewController.swift
|
2
|
3172
|
//
// ViewController.swift
// DecorationSectionCollectionView
//
// Created by Victor Chee on 2017/4/16.
// Copyright © 2017年 VictorChee. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (section + 1) * 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
// Configure the cell
cell.backgroundColor = UIColor.lightGray
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)
header.backgroundColor = UIColor.magenta.withAlphaComponent(0.7)
return header
} else {
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath)
footer.backgroundColor = UIColor.brown.withAlphaComponent(0.7)
return footer
}
}
}
extension ViewController: CollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumSectionSpacingForSectionAt section: Int) -> CGFloat {
if section == 0 {
return 5
} else if section == 1 {
return 20
} else {
return 80
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor {
if section == 0 {
return UIColor.red
} else if section == 1 {
return UIColor.green
} else {
return UIColor.yellow
}
}
}
|
mit
|
a697c513fe021de44fe050806c1e83b0
| 34.211111 | 173 | 0.680656 | 5.901304 | false | false | false | false |
khwang/Streak-Club-iOS
|
Streak Club/SignupView.swift
|
1
|
5458
|
//
// SignupView.swift
// Streak Club
//
// Created by Kevin Hwang on 10/16/15.
// Copyright © 2015 Kevin Hwang. All rights reserved.
//
import UIKit
import SnapKit
final class SignupView: UIView {
private let formContainer: UIView = {
let view = UIView()
view.backgroundColor = UIColor.whiteColor()
view.layer.cornerRadius = 3
view.layer.masksToBounds = true
return view
}()
let usernameField: UITextField = {
let field = UITextField()
field.placeholder = NSLocalizedString("Username", comment: "Input form for a username")
return field;
}()
let passwordField: UITextField = {
let field = UITextField()
field.placeholder = NSLocalizedString("Password", comment: "Input form for a password")
field.secureTextEntry = true
return field
}()
let repeatPasswordField: UITextField = {
let field = UITextField()
field.placeholder = NSLocalizedString("Repeat password", comment: "Input form to confirm password")
field.secureTextEntry = true
return field;
}()
let emailField: UITextField = {
let field = UITextField()
field.placeholder = NSLocalizedString("Email", comment: "Input form for a user's email")
return field
}()
let actionButton: UIButton = {
let button = UIButton()
button.setTitle(NSLocalizedString("Create Account", comment: "Button for creating an account"), forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
return button
}()
let switchModeButton: UIButton = {
let button = UIButton()
button.setTitle(NSLocalizedString("Already have an account?", comment: "Button for switching between registering and logging in."), forState: UIControlState.Normal)
return button
}()
init() {
super.init(frame: CGRectZero)
_configureViews()
_configureSubviews()
_initializeAutolayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func _configureViews() {
backgroundColor = UIColor(hexString: "34a0f2")
_configureTextField(usernameField)
_configureTextField(passwordField)
_configureTextField(repeatPasswordField)
_configureTextField(emailField)
}
private func _configureSubviews() {
addSubview(formContainer)
formContainer.addSubview(usernameField)
formContainer.addSubview(passwordField)
formContainer.addSubview(repeatPasswordField)
formContainer.addSubview(emailField)
formContainer.addSubview(actionButton)
addSubview(switchModeButton)
}
private func _configureTextField(textField: UITextField) {
textField.font = UIFont.regularWithSize(16)
textField.layer.borderColor = UIColor(hexString: "cdcdcd").CGColor
textField.layer.borderWidth = 2
textField.autocapitalizationType = UITextAutocapitalizationType.None
textField.autocorrectionType = UITextAutocorrectionType.No
let viewSpacer = UIView(frame: CGRectMake(0, 0, 10, 0))
textField.leftView = viewSpacer
textField.leftViewMode = UITextFieldViewMode.Always
}
private func _initializeAutolayout() {
let sideMargin: Float = 20
formContainer.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(actionButton)
make.left.equalTo(self).offset(sideMargin)
make.right.equalTo(self).offset(-sideMargin)
make.centerY.equalTo(self)
}
let sidePadding: Float = 20
let verticalPadding: Float = 10
let fieldHeight: Float = 44
usernameField.snp_makeConstraints { (make) -> Void in
make.left.equalTo(formContainer).offset(sidePadding)
make.right.equalTo(formContainer).offset(-sidePadding)
make.top.equalTo(formContainer).offset(verticalPadding)
make.height.equalTo(fieldHeight)
}
passwordField.snp_makeConstraints { (make) -> Void in
make.left.right.equalTo(usernameField)
make.top.equalTo(usernameField.snp_bottom).offset(verticalPadding)
make.height.equalTo(usernameField)
}
repeatPasswordField.snp_makeConstraints { (make) -> Void in
make.left.right.equalTo(usernameField)
make.top.equalTo(passwordField.snp_bottom).offset(verticalPadding)
make.height.equalTo(usernameField)
}
emailField.snp_makeConstraints { (make) -> Void in
make.left.right.equalTo(usernameField)
make.top.equalTo(repeatPasswordField.snp_bottom).offset(verticalPadding)
make.height.equalTo(usernameField)
}
actionButton.snp_makeConstraints { (make) -> Void in
make.left.right.equalTo(usernameField)
make.top.equalTo(emailField.snp_bottom)
make.height.equalTo(usernameField)
}
switchModeButton.snp_makeConstraints { (make) -> Void in
make.left.right.equalTo(usernameField)
make.top.equalTo(actionButton.snp_bottom)
make.height.equalTo(usernameField)
}
}
}
|
mit
|
e50c2e57ba08afe57b538d6c4a35df22
| 34.907895 | 172 | 0.642294 | 5.119137 | false | true | false | false |
Shuangzuan/Pew
|
Pew/AlienLaser.swift
|
1
|
1188
|
//
// AlienLaser.swift
// Pew
//
// Created by Shuangzuan He on 4/20/15.
// Copyright (c) 2015 Pretty Seven. All rights reserved.
//
import SpriteKit
class AlienLaser: Entity {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(imageNamed: "laserbeam_red", maxHp: 1, healthBarType: .None)
setupCollisionBody()
}
private func setupCollisionBody() {
let offset = CGPoint(x: size.width * anchorPoint.x, y: size.height * anchorPoint.y)
let path = CGPathCreateMutable()
moveToPoint(CGPoint(x: 4, y: 8), path: path, offset: offset)
addLineToPoint(CGPoint(x: 24, y: 8), path: path, offset: offset)
addLineToPoint(CGPoint(x: 24, y: 3), path: path, offset: offset)
addLineToPoint(CGPoint(x: 4, y: 3), path: path, offset: offset)
CGPathCloseSubpath(path)
physicsBody = SKPhysicsBody(polygonFromPath: path)
physicsBody?.categoryBitMask = PhysicsCategory.AlienLaser
physicsBody?.collisionBitMask = 0
physicsBody?.contactTestBitMask = PhysicsCategory.Player
}
}
|
mit
|
2081b90a079265b4a889976cba3a2097
| 31.108108 | 91 | 0.640572 | 4.082474 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Biometry/Biometry.swift
|
1
|
6563
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import LocalAuthentication
import Localization
import PlatformKit
public struct Biometry {
public enum BiometryError: LocalizedError {
private typealias LocalizedString = LocalizationConstants.Biometry
case authenticationFailed
case passcodeNotSet
case biometryLockout
case biometryNotAvailable
case biometryNotEnrolled(type: BiometryType)
case appCancel
case systemCancel
case userCancel
case userFallback
case general
/// A user message corresponding to the error
public var errorDescription: String? {
switch self {
case .authenticationFailed:
return LocalizedString.authenticationFailed
case .passcodeNotSet:
return LocalizedString.passcodeNotSet
case .biometryLockout:
return LocalizedString.biometricsLockout
case .biometryNotAvailable:
return LocalizedString.biometricsNotSupported
case .biometryNotEnrolled(let type):
switch type {
case .faceID:
return LocalizedString.faceIDEnableInstructions
case .touchID:
return LocalizedString.touchIDEnableInstructions
case .none:
return LocalizedString.genericError
}
case .general:
return LocalizedString.genericError
case .appCancel,
.systemCancel,
.userCancel,
.userFallback:
return ""
}
}
/// Initializes with error, expects the error to have `code`
/// compatible code to `LAError.Code.rawValue`
public init(with error: Error, type: BiometryType) {
let code = (error as NSError).code
self.init(with: code, type: type)
}
/// Initializes with expected `LAError.Code`'s `rawValue`
init(with rawCodeValue: Int, type: BiometryType) {
if let localAuthenticationCode = LAError.Code(rawValue: rawCodeValue) {
self.init(with: localAuthenticationCode, type: type)
} else {
self = .general
}
}
/// Initializes with `LAError.Code` value
init(with error: LAError.Code, type: BiometryType) {
switch error {
case .authenticationFailed:
self = .authenticationFailed
case .appCancel:
self = .appCancel
case .passcodeNotSet:
self = .passcodeNotSet
case .systemCancel:
self = .systemCancel
case .userCancel:
self = .userCancel
case .userFallback:
self = .userFallback
case .touchIDLockout:
self = .biometryLockout
case .touchIDNotAvailable:
self = .biometryNotAvailable
case .touchIDNotEnrolled:
self = .biometryNotEnrolled(type: type)
case .invalidContext,
.notInteractive:
self = .general
@unknown default:
self = .general
}
}
}
// MARK: - Types
public enum Reason {
case enterWallet
var localized: String {
switch self {
case .enterWallet:
return LocalizationConstants.Biometry.authenticationReason
}
}
}
/// Indicates the current biometrics configuration state
public enum Status {
/// Not configured on device but there is no restriction for configuring one
case configurable(BiometryType)
/// Configured on the device and in app
case configured(BiometryType)
/// Cannot be configured because the device do not support it,
/// or because the user hasn't enabled it, or because that feature is not remotely
case unconfigurable(Error)
/// Returns `true` if biometrics is configurable
public var isConfigurable: Bool {
switch self {
case .configurable:
return true
case .configured, .unconfigurable:
return false
}
}
/// Returns `true` if biometrics is configured
public var isConfigured: Bool {
switch self {
case .configured:
return true
case .configurable, .unconfigurable:
return false
}
}
/// Returns associated `BiometricsType` if any
public var biometricsType: BiometryType {
switch self {
case .configurable(let type):
return type
case .configured(let type):
return type
case .unconfigurable:
return .none
}
}
}
/// A type of biomety authenticator
public enum BiometryType {
/// The device supports Touch ID.
case touchID
/// The device supports Face ID.
case faceID
/// The device does not support biometry.
case none
public init(with systemType: LABiometryType) {
switch systemType {
case .faceID:
self = .faceID
case .touchID:
self = .touchID
case .none:
self = .none
@unknown default:
self = .none
}
}
public var localizedName: String? {
switch self {
case .faceID:
return LocalizationConstants.faceId
case .touchID:
return LocalizationConstants.touchId
case .none:
return nil
}
}
public var isValid: Bool {
self != .none
}
}
/// Represents `LAContext` result on calling `canEvaluatePolicy` for biometrics
public enum EvaluationError: LocalizedError {
/// Wraps
case system(BiometryError)
case notAllowed
public var errorDescription: String? {
switch self {
case .system(let error):
return String(describing: error)
case .notAllowed:
return LocalizationConstants.Biometry.notConfigured
}
}
}
}
|
lgpl-3.0
|
4b05164909f5af88b1f820eecf8dda85
| 29.37963 | 90 | 0.543127 | 5.822538 | false | true | false | false |
AlesTsurko/DNMKit
|
DNMModel/SimpleRoot.swift
|
1
|
3184
|
// SimpleRoot.swift - As straight a port as I could get my head around of Jim Armstrong's
// port of Jack Crenshaw's TWBRF simple root finding algorithm. See license below:
//
// SimpleRoot.as - A straight port of Jack Crenshaw's TWBRF method for simple roots in an interval.
// -- To use, identify an interval in which the function whose zero is desired has a sign change
// -- (via bisection, for example). Call the findRoot method.
//
// This program is derived from source bearing the following copyright notice,
//
// Copyright (c) 2008, Jim Armstrong. All rights reserved.
//
// This software program is supplied 'as is' without any warranty, express,
// implied, or otherwise, including without limitation all warranties of
// merchantability or fitness for a particular purpose. Jim Armstrong shall not
// be liable for any special incidental, or consequential damages, including,
// witout limitation, lost revenues, lost profits, or loss of prospective
// economic advantage, resulting from the use or misuse of this software program.
//
// Programmed by Jim Armstrong, (http://algorithmist.wordpress.com)
// Ported to Degrafa with full permission of author
/**
* @version 1.0
*/
import QuartzCore
public class SimpleRoot {
private var i: Int = 0
public init() { }
public func findRoot(
x0 x0: CGFloat,
x2: CGFloat,
maximumIterationLimit: Int,
tolerance: CGFloat,
f: CGFloat -> CGFloat
) -> CGFloat
{
var xmLast: CGFloat = x0
var y0: CGFloat = f(x0)
if y0 == 0.0 { return x0 }
var y2 = f(x2)
if y2 == 0.0 { return x2 }
if y2 * y0 > 0.0 { return x0 }
var x0 = x0
var x2 = x2
var x1: CGFloat = 0
var y1: CGFloat = 0
var xm: CGFloat = 0
var ym: CGFloat = 0
while i <= maximumIterationLimit {
// increment
i++
x1 = 0.5 * (x2 + x0)
y1 = f(x1)
if y1 == 0 { return x1 }
if abs(x1 - x0) < tolerance { return x1 }
if y1 * y0 > 0 {
var temp = x0
x0 = x2
x2 = temp
temp = y0
y0 = y2
y2 = temp
}
let y10 = y1 - y0
let y21 = y2 - y1
let y20 = y2 - y0
if (y2 * y20 < 2 * y1 * y0) {
x2 = x1
y2 = y1
}
else {
let b = (x1 - x0) / y10
let c = (y10 - y21) / (y21 * y20)
xm = x0 - b * y0 * (1 - c * y1)
ym = f(xm)
if ym == 0 { return xm }
if abs(xm - xmLast) < tolerance { return xm }
xmLast = xm
if ym * y0 < 0 {
x2 = xm
y2 = ym
}
else {
x0 = xm
y0 = ym
x2 = x1
y2 = y1
}
}
}
return x1
}
}
|
gpl-2.0
|
697008c9cec939a574e90a85a71e6124
| 29.037736 | 101 | 0.482726 | 3.878197 | false | false | false | false |
crossroadlabs/ExpressCommandLine
|
swift-express/Commands/Build/BuildSPM.swift
|
1
|
4005
|
//===--- BuildSPM.swift -------------------------------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===---------------------------------------------------------------------------===//
import Foundation
import Result
struct BuildSPMStep : RunSubtaskStep {
let dependsOn:[Step] = [CheckoutSPM(force: false)]
func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] {
guard let path = params["path"] as? String else {
throw SwiftExpressError.BadOptions(message: "BuildSPM: No path option.")
}
guard let buildType = params["buildType"] as? BuildType else {
throw SwiftExpressError.BadOptions(message: "BuildSPM: No buildType option.")
}
guard let force = params["force"] as? Bool else {
throw SwiftExpressError.BadOptions(message: "BuildSPM: No force option.")
}
guard let dispatch = params["dispatch"] as? Bool else {
throw SwiftExpressError.BadOptions(message: "BuildSPM: No dispatch option.")
}
print("Building in \(buildType.description) mode with Swift Package Manager...")
if force {
let buildpath = path.addPathComponent(".build").addPathComponent(buildType.spmValue)
if FileManager.isDirectoryExists(buildpath) {
try FileManager.removeItem(buildpath)
}
}
var args = ["swift", "build", "-c", buildType.spmValue]
if dispatch || !IS_LINUX {
args.appendContentsOf(["-Xcc", "-fblocks", "-Xswiftc", "-Ddispatch"])
}
let result = try executeSubtaskAndWait(SubTask(task: "/usr/bin/env", arguments: args, workingDirectory: path, environment: nil, useAppOutput: true))
if result != 0 {
throw SwiftExpressError.SubtaskError(message: "Build task exited with status \(result)")
}
return [String: Any]()
}
func cleanup(params:[String: Any], output: StepResponse) throws {
}
func revert(params: [String : Any], output: [String : Any]?, error: SwiftExpressError?) {
switch error {
case .SubtaskError(_)?:
if let path = params["path"] as? String {
let buildDir = path.addPathComponent(".build")
if FileManager.isDirectoryExists(buildDir) {
let hiddenRe = "^\\.[^\\.]+".r!
do {
let builds = try FileManager.listDirectory(buildDir)
for build in builds {
if hiddenRe.matches(build) {
continue
}
try FileManager.removeItem(buildDir.addPathComponent(build))
}
} catch {}
}
}
default:
return
}
}
func callParams(ownParams: [String: Any], forStep: Step, previousStepsOutput: StepResponse) throws -> [String: Any] {
if ownParams["path"] == nil {
throw SwiftExpressError.BadOptions(message: "BuildSPM: No path option.")
}
return ["workingFolder": ownParams["path"]!]
}
}
|
gpl-3.0
|
8ac335b5ad217c8d154339c639944664
| 42.064516 | 156 | 0.57603 | 4.938348 | false | false | false | false |
coach-plus/ios
|
Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift
|
6
|
5010
|
//
// ControlProperty.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 8/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
/// Protocol that enables extension of `ControlProperty`.
public protocol ControlPropertyType : ObservableType, ObserverType {
/// - returns: `ControlProperty` interface
func asControlProperty() -> ControlProperty<Element>
}
/**
Trait for `Observable`/`ObservableType` that represents property of UI element.
Sequence of values only represents initial control value and user initiated value changes.
Programmatic value changes won't be reported.
It's properties are:
- `shareReplay(1)` behavior
- it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced
- it will `Complete` sequence on control being deallocated
- it never errors out
- it delivers events on `MainScheduler.instance`
**The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler
(`subscribeOn(ConcurrentMainScheduler.instance)` behavior).**
**It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.**
**If they aren't, then using this trait communicates wrong properties and could potentially break someone's code.**
**In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated
properties, please don't use this trait.**
*/
public struct ControlProperty<PropertyType> : ControlPropertyType {
public typealias Element = PropertyType
let _values: Observable<PropertyType>
let _valueSink: AnyObserver<PropertyType>
/// Initializes control property with a observable sequence that represents property values and observer that enables
/// binding values to property.
///
/// - parameter values: Observable sequence that represents property values.
/// - parameter valueSink: Observer that enables binding values to control property.
/// - returns: Control property created with a observable sequence of values and an observer that enables binding values
/// to property.
public init<Values: ObservableType, Sink: ObserverType>(values: Values, valueSink: Sink) where Element == Values.Element, Element == Sink.Element {
self._values = values.subscribeOn(ConcurrentMainScheduler.instance)
self._valueSink = valueSink.asObserver()
}
/// Subscribes an observer to control property values.
///
/// - parameter observer: Observer to subscribe to property values.
/// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values.
public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
return self._values.subscribe(observer)
}
/// `ControlEvent` of user initiated value changes. Every time user updates control value change event
/// will be emitted from `changed` event.
///
/// Programmatic changes to control value won't be reported.
///
/// It contains all control property values except for first one.
///
/// The name only implies that sequence element will be generated once user changes a value and not that
/// adjacent sequence values need to be different (e.g. because of interaction between programmatic and user updates,
/// or for any other reason).
public var changed: ControlEvent<PropertyType> {
return ControlEvent(events: self._values.skip(1))
}
/// - returns: `Observable` interface.
public func asObservable() -> Observable<Element> {
return self._values
}
/// - returns: `ControlProperty` interface.
public func asControlProperty() -> ControlProperty<Element> {
return self
}
/// Binds event to user interface.
///
/// - In case next element is received, it is being set to control value.
/// - In case error is received, DEBUG buids raise fatal error, RELEASE builds log event to standard output.
/// - In case sequence completes, nothing happens.
public func on(_ event: Event<Element>) {
switch event {
case .error(let error):
bindingError(error)
case .next:
self._valueSink.on(event)
case .completed:
self._valueSink.on(event)
}
}
}
extension ControlPropertyType where Element == String? {
/// Transforms control property of type `String?` into control property of type `String`.
public var orEmpty: ControlProperty<String> {
let original: ControlProperty<String?> = self.asControlProperty()
let values: Observable<String> = original._values.map { $0 ?? "" }
let valueSink: AnyObserver<String> = original._valueSink.mapObserver { $0 }
return ControlProperty<String>(values: values, valueSink: valueSink)
}
}
|
mit
|
6e442fd01a452c1954b50c7a0fe040bc
| 41.449153 | 151 | 0.70553 | 5.095626 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/TraderChartsExample/View/DividerView.swift
|
1
|
3096
|
//
// DividerView.swift
// SciChartShowcaseDemo
//
// Created by Gkol on 7/29/17.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import Foundation
class DividerView: UIView {
@IBOutlet weak var dividerAbove: DividerView?
@IBOutlet weak var dividerBelow: DividerView?
@IBOutlet var relationConstraint : NSLayoutConstraint!
var minViewHeight : CGFloat = 100.0
private var originTopViewHeight: CGFloat = 0.0
private var originBottomViewHeight: CGFloat = 0.0
private var originRelationConstraintConstant: CGFloat = 0.0
private var originRelationBelowConstraintConstant: CGFloat = 0.0
private var originRelationAboveConstraintConstant: CGFloat = 0.0
@IBAction func panGesture(_ sender: UIPanGestureRecognizer) {
let locationPan = sender.translation(in: nil)
switch sender.state {
case .began:
if let below = dividerBelow {
originRelationBelowConstraintConstant = below.relationConstraint.constant
}
if let above = dividerAbove {
originRelationAboveConstraintConstant = above.relationConstraint.constant
}
if let topView = relationConstraint.firstItem as? UIView {
originTopViewHeight = topView.frame.size.height
}
if let bottomView = relationConstraint.secondItem as? UIView {
originBottomViewHeight = bottomView.frame.size.height
}
originRelationConstraintConstant = relationConstraint.constant
break
case .changed:
if locationPan.y > 0 {
if originBottomViewHeight - locationPan.y > minViewHeight {
relationConstraint.constant = originRelationConstraintConstant+locationPan.y*(relationConstraint.multiplier+1)
if let below = dividerBelow {
below.relationConstraint.constant = originRelationBelowConstraintConstant-locationPan.y
}
if let above = dividerAbove {
above.relationConstraint.constant = originRelationAboveConstraintConstant-locationPan.y*above.relationConstraint.multiplier
}
}
}
else {
if originTopViewHeight + locationPan.y > minViewHeight {
relationConstraint.constant = originRelationConstraintConstant+locationPan.y*(relationConstraint.multiplier+1)
if let below = dividerBelow {
below.relationConstraint.constant = originRelationBelowConstraintConstant-locationPan.y
}
if let above = dividerAbove {
above.relationConstraint.constant = originRelationAboveConstraintConstant-locationPan.y*above.relationConstraint.multiplier
}
}
}
break
default:
break
}
}
}
|
mit
|
58dfd934415a4daba6da423d6029cb38
| 38.177215 | 147 | 0.608078 | 5.731481 | false | false | false | false |
xxxAIRINxxx/GooglePlayTransition
|
GooglePlayTransition/GooglePlayTransition/GooglePlayTransitionAnimation.swift
|
1
|
6290
|
//
// GooglePlayTransitionAnimation.swift
// GooglePlayTransition
//
// Created by xxxAIRINxxx on 2015/08/24.
// Copyright (c) 2015 xxxAIRINxxx. All rights reserved.
//
import UIKit
import ARNTransitionAnimator
protocol GooglePlayTransitionInterface: UIViewController {
func createTransitionImageView() -> UIImageView
func createTransitionHeaderImageView() -> UIImageView
func headerCircleColor() -> UIColor
// Present
func presentationBeforeAction()
func presentationAnimationAction(_ percentComplete: CGFloat)
func presentationCompletionAction(_ completeTransition: Bool)
// Dismiss
func dismissalBeforeAction()
func dismissalAnimationAction(_ percentComplete: CGFloat)
func dismissalCompletionAction(_ completeTransition: Bool)
}
// optional
extension GooglePlayTransitionInterface {
func createTransitionHeaderImageView() -> UIImageView {
return UIImageView()
}
func headerCircleColor() -> UIColor {
return UIColor.white
}
func presentationBeforeAction() {}
func presentationAnimationAction(_ percentComplete: CGFloat) {}
func presentationCompletionAction(_ completeTransition: Bool) {}
func dismissalBeforeAction() {}
func dismissalAnimationAction(_ percentComplete: CGFloat) {}
func dismissalCompletionAction(_ completeTransition: Bool) {}
}
final class GooglePlayTransitionAnimation : TransitionAnimatable {
deinit {
print("deinit GooglePlayTransitionAnimation")
}
fileprivate weak var rootVC: GooglePlayTransitionInterface!
fileprivate weak var modalVC: GooglePlayTransitionInterface!
fileprivate var circleView : UIView?
fileprivate var sourceImageView: UIImageView?
fileprivate var sourceHeaderImageView: UIImageView?
fileprivate var destinationImageView: UIImageView?
fileprivate var destinationHeaderImageView: UIImageView?
init(rootVC: GooglePlayTransitionInterface, modalVC: GooglePlayTransitionInterface) {
self.rootVC = rootVC
self.modalVC = modalVC
}
func willAnimation(_ transitionType: TransitionType, containerView: UIView) {
if transitionType.isPresenting {
sourceImageView = rootVC.createTransitionImageView()
destinationImageView = modalVC.createTransitionImageView()
destinationHeaderImageView = modalVC.createTransitionHeaderImageView()
if let _destinationHeaderImageView = destinationHeaderImageView {
containerView.addSubview(_destinationHeaderImageView)
_destinationHeaderImageView.image = nil
circleView = UIView(frame: CGRect.zero)
circleView!.clipsToBounds = true
let destSize = _destinationHeaderImageView.frame.size
if destSize.width >= destSize.height {
circleView!.frame.size = CGSize(width: destSize.width, height: destSize.width)
} else {
circleView!.frame.size = CGSize(width: destSize.height, height: destSize.height)
}
circleView!.layer.cornerRadius = circleView!.frame.size.width * 0.5
circleView!.backgroundColor = modalVC.headerCircleColor()
circleView!.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
let circleSize = circleView!.frame.size
circleView!.frame.origin = CGPoint(x: (destSize.width * 0.5) - (circleSize.width * 0.5), y: (destSize.height * 0.5) - (circleSize.height * 0.5))
_destinationHeaderImageView.addSubview(circleView!)
}
containerView.addSubview(sourceImageView!)
containerView.addSubview(destinationImageView!)
destinationImageView?.isHidden = true
rootVC.presentationBeforeAction()
modalVC.presentationBeforeAction()
modalVC.view.alpha = 0.0
} else {
sourceImageView = modalVC.createTransitionImageView()
destinationImageView = rootVC.createTransitionImageView()
sourceImageView!.layer.cornerRadius = destinationImageView!.layer.cornerRadius
containerView.addSubview(sourceImageView!)
rootVC.dismissalBeforeAction()
modalVC.dismissalBeforeAction()
sourceHeaderImageView = rootVC.createTransitionHeaderImageView()
containerView.addSubview(sourceHeaderImageView!)
}
}
func updateAnimation(_ transitionType: TransitionType, percentComplete: CGFloat) {
if transitionType.isPresenting {
sourceImageView?.frame = destinationImageView?.frame ?? CGRect.zero
circleView?.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
modalVC.view.alpha = 1.0
rootVC.presentationAnimationAction(percentComplete)
modalVC.presentationAnimationAction(percentComplete)
} else {
sourceImageView?.frame = destinationImageView?.frame ?? CGRect.zero
if let _sourceHeaderImageView = sourceHeaderImageView {
_sourceHeaderImageView.frame.origin.y -= _sourceHeaderImageView.frame.size.height
}
rootVC.dismissalAnimationAction(percentComplete)
modalVC.dismissalAnimationAction(percentComplete)
}
}
func finishAnimation(_ transitionType: TransitionType, didComplete: Bool) {
if transitionType.isPresenting {
sourceImageView?.removeFromSuperview()
circleView?.removeFromSuperview()
destinationHeaderImageView?.removeFromSuperview()
rootVC.presentationCompletionAction(didComplete)
modalVC.presentationCompletionAction(didComplete)
} else {
sourceImageView?.removeFromSuperview()
sourceHeaderImageView?.removeFromSuperview()
rootVC.dismissalCompletionAction(didComplete)
modalVC.dismissalCompletionAction(didComplete)
}
}
}
extension GooglePlayTransitionAnimation {
func sourceVC() -> UIViewController {
if let nav = self.rootVC.navigationController {
return nav
}
return self.rootVC
}
func destVC() -> UIViewController { return self.modalVC }
}
|
mit
|
ab861431cbe5b1dc6814cede0ba9ae3f
| 33.944444 | 160 | 0.683466 | 5.906103 | false | false | false | false |
PureSwift/Bluetooth
|
Sources/BluetoothHCI/LinkControlCommand.swift
|
1
|
7273
|
//
// LinkControlCommand.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 1/13/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
@frozen
public enum LinkControlCommand: UInt16, HCICommand {
public static let opcodeGroupField = HCIOpcodeGroupField.linkControl
/// Command used to enter Inquiry mode where it discovers other Bluetooth devices.
case inquiry = 0x0001
/// Command to cancel the Inquiry mode in which the Bluetooth device is in.
case inquiryCancel = 0x0002
/// Command to set the device to enter Inquiry modes periodically according to the time interval set.
case periodicInquiry = 0x0003
/// Command to exit the periodic Inquiry mode.
case exitPeriodicInquiry = 0x0004
/// Command to create an ACL connection to the device specified by the BD_ADDR in the parameters.
case createConnection = 0x0005
/// Command to terminate the existing connection to a device.
case disconnect = 0x0006
/// Create an SCO connection defined by the connection handle parameters.
case addSCOConnection = 0x0007
/// Cancel Create Connection
case createConnectionCancel = 0x0008
/// Command to accept a new connection request.
case acceptConnection = 0x0009
/// Command to reject a new connection request.
case rejectConnection = 0x000A
/// Reply command to a link key request event sent from controller to the host.
case linkKeyReply = 0x000B
/// Reply command to a link key request event from the controller to the host if there is no link key associated with the connection.
case linkKeyNegativeReply = 0x000C
/// Reply command to a PIN code request event sent from a controller to the host.
case pinCodeReply = 0x000D
/// Reply command to a PIN code request event sent from the controller to the host if there is no PIN associated with the connection.
case pinCodeNegativeReply = 0x000E
/// Command to change the type of packets to be sent for an existing connection.
case setConnectionPacketType = 0x000F
/// Command to establish authentication between two devices specified by the connection handle.
case authenticationRequested = 0x0011
/// Command to enable or disable the link level encryption.
case setConnectionEncryption = 0x0013
/// Command to force the change of a link key to a new one between two connected devices.
case changeConnectionLinkKey = 0x0015
/// Command to force two devices to use the master's link key temporarily.
case masterLinkKey = 0x0017
/// Command to determine the user friendly name of the connected device.
case remoteNameRequest = 0x0019
/// Cancels the remote name request.
case remoteNameRequestCancel = 0x001A
/// Command to determine the features supported by the connected device.
case readRemoteFeatures = 0x001B
/// Command to determine the extended features supported by the connected device.
case readRemoteExtendedFeatures = 0x001C
/// Command to determine the version information of the connected device.
case readRemoteVersion = 0x001D
/// Command to read the clock offset of the remote device.
case readClockOffset = 0x001F
/// Read LMP Handle
case readLMPHandle = 0x0020
/// Setup Synchronous Connection Command
case setupSynchronousConnection = 0x0028
/// Accept Synchronous Connection Request Command
case acceptSychronousConnection = 0x0029
/// Reject Synchronous Connection Request Command
case rejectSynchronousConnection = 0x002A
/// IO Capability Request Reply Command
case ioCapabilityRequestReply = 0x002B
/// User Confirmation Request Reply Command
case userConfirmationRequestReply = 0x002C
/// User Confirmation Request Negative Reply Command
case userConfirmationRequestNegativeReply = 0x002D
/// User Passkey Request Reply Command
case userPasskeyRequestReply = 0x002E
/// User Passkey Request Negative Reply Command
case userPasskeyRequestNegativeReply = 0x002F
/// Remote OOB Data Request Reply Command
case remoteOOBDataRequestReply = 0x0030
/// Remote OOB Data Request Negative Reply Command
case remoteOOBDataRequestNegativeReply = 0x0033
/// IO Capability Request Negative Reply Command
case ioCapabilityRequestNegativeReply = 0x0034
/// Create Physical Link Command
case createPhysicalLink = 0x0035
/// Accept Physical Link Command
case acceptPhysicalLink = 0x0036
/// Disconnect Physical Link Command
case disconnectPhysicalLink = 0x0037
/// Create Logical Link Command
case createLogicalLink = 0x0038
/// Accept Logical Link Command
case acceptLogicalLink = 0x0039
/// Disconnect Logical Link Command
case disconnectLogicalLink = 0x003A
/// Logical Link Cancel Command
case logicalLinkCancel = 0x003B
/// Flow Spec Modify Command
case flowSpecModify = 0x003C
}
// MARK: - Name
public extension LinkControlCommand {
var name: String {
return type(of: self).names[Int(rawValue)]
}
private static let names = [
"Unknown",
"Inquiry",
"Inquiry Cancel",
"Periodic Inquiry Mode",
"Exit Periodic Inquiry Mode",
"Create Connection",
"Disconnect",
"Add SCO Connection",
"Create Connection Cancel",
"Accept Connection Request",
"Reject Connection Request",
"Link Key Request Reply",
"Link Key Request Negative Reply",
"PIN Code Request Reply",
"PIN Code Request Negative Reply",
"Change Connection Packet Type",
"Unknown",
"Authentication Requested",
"Unknown",
"Set Connection Encryption",
"Unknown",
"Change Connection Link Key",
"Unknown",
"Master Link Key",
"Unknown",
"Remote Name Request",
"Remote Name Request Cancel",
"Read Remote Supported Features",
"Read Remote Extended Features",
"Read Remote Version Information",
"Unknown",
"Read Clock Offset",
"Read LMP Handle",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Unknown",
"Setup Synchronous Connection",
"Accept Synchronous Connection",
"Reject Synchronous Connection",
"IO Capability Request Reply",
"User Confirmation Request Reply",
"User Confirmation Request Negative Reply",
"User Passkey Request Reply",
"User Passkey Request Negative Reply",
"Remote OOB Data Request Reply",
"Unknown",
"Unknown",
"Remote OOB Data Request Negative Reply",
"IO Capability Request Negative Reply",
"Create Physical Link",
"Accept Physical Link",
"Disconnect Physical Link",
"Create Logical Link",
"Accept Logical Link",
"Disconnect Logical Link",
"Logical Link Cancel",
"Flow Spec Modify"
]
}
|
mit
|
87223742df74cb8a08a861306e40847e
| 31.756757 | 137 | 0.667492 | 4.994505 | false | false | false | false |
Cleverdesk/cleverdesk-ios
|
Cleverdesk/CheckBox.swift
|
1
|
1050
|
//
// CheckBox.swift
// Cleverdesk
//
// Created by Matthias Kremer on 24.05.16.
// Copyright © 2016 Cleverdesk. All rights reserved.
//
import Foundation
import UIKit
class CheckBox: Component{
var value: Bool?
var enabled: Bool?
var input_name: String?
func name() -> String {
return "CheckBox"
}
func copy() -> Component {
return CheckBox()
}
func fromJSON(json: AnyObject){
let dic = (json as! Dictionary<NSString, NSObject>)
input_name = dic["input_name"] as? String
enabled = dic["enabled"] as? Bool
value = dic["value"] as? Bool
}
func toUI(frame: CGRect) -> [UIView]? {
let checkBox = UISwitch(frame: CGRectMake(10,10,0,0))
if let state = value{
checkBox.on = state
}
if let usable = enabled{
checkBox.enabled = usable
}
let view = UIView(frame: CGRectMake(0,0,0,42))
view.addSubview(checkBox)
return [view]
}
}
|
gpl-3.0
|
b0e36c2448d326d6615e27c46578238f
| 20.875 | 61 | 0.551954 | 4.003817 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Formatters/Iso8601DateFormatter.swift
|
2
|
1164
|
//
// Iso8601DateFormatter.swift
// Eurofurence
//
// Copyright © 2017 Eurofurence. All rights reserved.
//
import Foundation
/**
Simple, hacky fix to support creating Dates from ISO8601 timestamps with and
without fractional seconds.
*/
public class Iso8601DateFormatter: DateFormatter {
public static let instance = Iso8601DateFormatter()
public let noFractionsDateFormatter = DateFormatter()
override public init() {
super.init()
locale = Locale(identifier: "en_US_POSIX")
timeZone = TimeZone(secondsFromGMT: 0)
dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"
noFractionsDateFormatter.locale = Locale(identifier: "en_US_POSIX")
noFractionsDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
noFractionsDateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func date(from string: String) -> Date? {
if let date = noFractionsDateFormatter.date(from: string) {
return date
}
return super.date(from: string)
}
override public func string(from date: Date) -> String {
return super.string(from: date)
}
}
|
mit
|
9a4143b0ab86bfe52e013b401d8a1069
| 24.844444 | 76 | 0.72485 | 3.556575 | false | false | false | false |
kdw9/TIY-Assignments
|
Forecaster/Forecaster/ForecastTableViewController.swift
|
1
|
5474
|
//
// ForecastTableViewController.swift
// Forecaster
//
// Created by Keron Williams on 10/30/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
protocol APIControllerProtocol
{
func didReceiveAPIResults (results:NSArray)
func cityWasFound(aCity: City)
}
protocol ModalViewControllerProtocol
{
func zipCodeWasEntered(zipCode: String)
}
class ForecastTableViewController: UITableViewController, ModalViewControllerProtocol, APIControllerProtocol
{
var api: APIController!
var weatherCities = Array<City>()
//var weather = Array<Weather>()
override func viewDidLoad()
{
super.viewDidLoad()
api = APIController(delegate: self)
//api.googleLocationApi("32712")
// 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()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return weatherCities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("WeatherDataCell", forIndexPath: indexPath) as! WeatherLocationTableViewCell
cell.numberDegreeLabel.text = "\(indexPath.row)"
cell.weatherLocationLabel.text = "New York"
cell.conditionLabel.text = "Sunny"
cell.weathericon.image = UIImage(named: "SunnyIcon.png")
return cell
// func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
// {
// tableView.deselectRowAtIndexPath(indexPath, animated: true)
// }
/////////////// This Block Out Code is to Create the deleteSwipe/////////
///// insert Array Name - {''''}/////
// override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true}
// override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
// {
// if(editingStyle == UITableViewCellEditingStyle.Delete) {
// ''''.removeAtIndex(indexPath.row)
// self.tableView
// }
// Override to support conditional editing of the table view.
//override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
//return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete
{
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
// Override to support rearranging the table view.
// override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
// Override to support conditional rearranging of the table view.
// override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
// return true
// }
// 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.
if segue.identifier == "ModalSegue"
{
let destVC = segue.destinationViewController as! UINavigationController
let modal = destVC.viewControllers[0] as! ModalViewController
modal.delegate = self
}
}
// MARK: - ModalViewControllerProtocol
func zipCodeWasEntered(zipCode: String)
{
dismissViewControllerAnimated(true, completion: nil)
print(zipCode)
api.googleLocationAp(zipCode)
}
// MARK: - API Controller Protocol
func didReceiveAPIResults (results:NSArray)
{
}
func cityWasFound(aCity: City)
{
weatherCities.append(aCity)
tableView.reloadData()
}
}
|
cc0-1.0
|
b5f45a845714a32e1480f1a0078bb8e1
| 30.641618 | 157 | 0.672574 | 5.445771 | false | false | false | false |
auth0/Lock.iOS-OSX
|
LockTests/Models/RuleSpec.swift
|
2
|
5937
|
// RuleSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Quick
import Nimble
@testable import Lock
class RuleSpec: QuickSpec {
override func spec() {
describe("length") {
let message = "length"
it("should pass message in result") {
let rule = withPassword(lengthInRange: 1...10, message: message)
expect(rule.evaluate(on: "password").message) == message
}
it("should validate length with range") {
let rule = withPassword(lengthInRange: 1...10, message: message)
expect(rule.evaluate(on: "password").valid) == true
}
it("should fail when length is smaller than desired") {
let rule = withPassword(lengthInRange: 8...10, message: message)
expect(rule.evaluate(on: "short").valid) == false
}
it("should fail when length is greater than desired") {
let rule = withPassword(lengthInRange: 1...4, message: message)
expect(rule.evaluate(on: "longpassword").valid) == false
}
it("should fail with nil") {
let rule = withPassword(lengthInRange: 1...4, message: message)
expect(rule.evaluate(on: nil).valid) == false
}
}
describe("character set") {
let rule = withPassword(havingCharactersIn: .alphanumerics, message: "character set")
it("should pass message in result") {
expect(rule.evaluate(on: "password").message) == "character set"
}
it("should allow valid characters") {
expect(rule.evaluate(on: "should match this 1 password").valid) == true
}
it("should fail whe no valid character is found") {
expect(rule.evaluate(on: "#@&$)*@#()*$)(#*)$@#*").valid) == false
}
it("should fail with nil") {
expect(rule.evaluate(on: nil).valid) == false
}
}
describe("consecutive repeats") {
let rule = withPassword(havingMaxConsecutiveRepeats: 2, message: "no repeats")
it("should pass message in result") {
expect(rule.evaluate(on: "password").message) == "no repeats"
}
it("should allow string with no repeating count") {
expect(rule.evaluate(on: "1234567890").valid) == true
}
it("should allow string with max repeating count") {
expect(rule.evaluate(on: "12234567890").valid) == true
}
it("should fail with nil") {
expect(rule.evaluate(on: nil).valid) == false
}
it("should detect repeating characters") {
expect(rule.evaluate(on: "123455567890").valid) == false
}
it("should detect at least one repeating characters") {
expect(rule.evaluate(on: "1222222345567890").valid) == false
}
}
describe("at least rule") {
let valid = MockRule(valid: true)
let invalid = MockRule(valid: false)
let password = "a password"
it("should pass message in result") {
let rule = AtLeastRule(minimum: 1, rules: [valid], message: "only one")
expect(rule.evaluate(on: "password").message) == "only one"
}
it("should have conditions") {
let rule = AtLeastRule(minimum: 1, rules: [valid, invalid], message: "only one")
let result = rule.evaluate(on: "password")
expect(result.conditions).to(haveCount(2))
expect(result.conditions[0].valid) == true
expect(result.conditions[1].valid) == false
}
it("should be valid for only one") {
let rule = AtLeastRule(minimum: 1, rules: [valid], message: "only one")
expect(rule.evaluate(on: password).valid) == true
}
it("should be valid when the minimum valid quote is reached") {
let rule = AtLeastRule(minimum: 1, rules: [valid, invalid, invalid], message: "only one")
expect(rule.evaluate(on: password).valid) == true
}
it("should be invalid when minimum of valid rules is not reached") {
let rule = AtLeastRule(minimum: Int.max, rules: [valid, invalid, invalid], message: "impossible")
expect(rule.evaluate(on: password).valid) == false
}
}
}
}
struct MockRule: Rule {
let valid: Bool
let message = "MOCK"
func evaluate(on password: String?) -> RuleResult {
return SimpleRule.Result(message: message, valid: valid)
}
}
|
mit
|
a54ed7565dc32ef093b75f7b1d53a617
| 35.648148 | 113 | 0.579586 | 4.528604 | false | false | false | false |
johnpatrickmorgan/wtfautolayout
|
Sources/App/Parsing/ConstraintsParser+Examples.swift
|
1
|
1407
|
import Foundation
import Random
extension ConstraintsParser {
private static let example1 = """
(
"<NSLayoutConstraint:0x69c2f0 UIImageView:0x7fd382f50.height == 60>",
"<NSLayoutConstraint:0x69a8b0 UIImageView:0x7fd382f50.top == UITableViewCell:0x7fd39b20.top>",
"<NSLayoutConstraint:0x697ca0 UITableViewCell:0x7fd39b20.bottom == UIImageView:0x7fd382f50.bottom>",
"<NSLayoutConstraint:0x697d40 'UIView-Encapsulated-Layout-Height' UITableViewCell:0x7fd39b20.height == 80>\"
)
"""
private static let example2 = """
(
"<NSLayoutConstraint:0x134580 name_label.height == 25 (active, names: name_label:0x104590 )>",
"<NSLayoutConstraint:0x145cc0 name_label.height >= 50 (active, names: name_label:0x104590 )>"
)
"""
private static let example3 = """
(
"<NSLayoutConstraint:0x6199cd0 UIButton:0x7fbbf90.width == 0 (active)>",
"<NSLayoutConstraint:0x6998ec0 H:|-(15)-[UILabel:0x6ce60] (active, names: '|':UIButton:0x7fbbf90 )>",
"<NSLayoutConstraint:0x6199000 H:[UILabel:0x6ce60]-(15)-| (active, names: '|':UIButton:0x7fbbf90 )>"
)
"""
static func randomExample() -> String {
let examples = [
example1,
example2,
example3
]
return examples.random!
}
}
|
mit
|
043e991fc69dfa4324f121f66766d2da
| 36.026316 | 118 | 0.61194 | 3.654545 | false | false | false | false |
paulz/PerspectiveTransform
|
Example/PerspectiveTransform/PolygonLoader.swift
|
1
|
1221
|
//
// PolygonLoader.swift
// Example
//
// Created by Paul Zabelin on 3/12/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
class PolygonLoader: NSObject {
let parser: XMLParser
init(fileName: String) {
let bundle = Bundle(for: type(of: self))
let name = fileName.split(separator: ".")
let fileName: String = String(name.first!)
let fileExtension: String = String(name.last!)
let svgFileUrl = bundle.url(forResource: fileName, withExtension: fileExtension)!
parser = XMLParser(contentsOf: svgFileUrl)!
super.init()
parser.delegate = self
}
func loadPoints() -> String {
parser.parse()
return pointString!
}
var pointString: String?
}
extension PolygonLoader: XMLParserDelegate {
func parser(_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String] = [:]) {
if elementName == "polygon" {
pointString = attributeDict["points"]?.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
}
|
mit
|
09abc602ac4c632504f40065e46a62b7
| 26.727273 | 98 | 0.619672 | 4.656489 | false | false | false | false |
smartystreets/smartystreets-ios-sdk
|
Sources/SmartyStreets/USStreet/USStreetCandidate.swift
|
1
|
2971
|
import Foundation
@objcMembers public class USStreetCandidate: NSObject, Codable {
// A candidate is a possible match for an address that was submitted.
// A lookup can have multiple candidates if the address was ambiguous, and
// the maxCandidates field is set higher than 1.
//
// See "https://smartystreets.com/docs/cloud/us-street-api#root"
public var status:String?
public var reason:String?
public var inputId:String?
public var inputIndex:Int?
public var objcInputIndex:NSNumber? {
get {
return inputIndex as NSNumber?
}
}
public var candidateIndex:Int?
public var objcCandidateIndex:NSNumber? {
get {
return candidateIndex as NSNumber?
}
}
public var addressee:String?
public var deliveryLine1:String?
public var deliveryLine2:String?
public var lastline:String?
public var deliveryPointBarcode:String?
public var components:USStreetComponents?
public var metadata:USStreetMetadata?
public var analysis:USStreetAnalysis?
enum CodingKeys:String, CodingKey {
case inputId = "input_id"
case inputIndex = "input_index"
case candidateIndex = "candidate_index"
case addressee = "addressee"
case deliveryLine1 = "delivery_line_1"
case deliveryLine2 = "delivery_line_2"
case lastline = "last_line"
case deliveryPointBarcode = "delivery_point_barcode"
case components = "components"
case metadata = "metadata"
case analysis = "analysis"
}
init(dictionary:NSDictionary) {
self.inputId = dictionary["input_id"] as? String
self.inputIndex = dictionary["input_index"] as? Int
self.candidateIndex = dictionary["candidate_index"] as? Int
self.addressee = dictionary["addressee"] as? String
self.deliveryLine1 = dictionary["delivery_line_1"] as? String
self.deliveryLine2 = dictionary["delivery_line_2"] as? String
self.lastline = dictionary["last_line"] as? String
self.deliveryPointBarcode = dictionary["delivery_point_barcode"] as? String
if let components = dictionary["components"] {
self.components = USStreetComponents(dictionary: components as! NSDictionary)
} else {
self.components = USStreetComponents(dictionary: NSDictionary())
}
if let metadata = dictionary["metadata"] {
self.metadata = USStreetMetadata(dictionary: metadata as! NSDictionary)
} else {
self.metadata = USStreetMetadata(dictionary: NSDictionary())
}
if let analysis = dictionary["analysis"]{
self.analysis = USStreetAnalysis(dictionary: analysis as! NSDictionary)
} else {
self.analysis = USStreetAnalysis(dictionary: NSDictionary())
}
}
init(inputIndex:Int) {
self.inputIndex = inputIndex
}
}
|
apache-2.0
|
e1f1198261b6b85b6de252f4a8c75d4d
| 37.584416 | 89 | 0.651632 | 4.542813 | false | false | false | false |
Valine/mr-inspiration
|
ProjectChartSwift/Mr. Inspiration/ToggleView.swift
|
2
|
2992
|
//
// ToggleView.swift
// Mr. Inspiration
//
// Created by Lukas Valine on 12/2/15.
// Copyright © 2015 Lukas Valine. All rights reserved.
//
import Foundation
import UIKit
class ToggleButtonView: UIView { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
var buttons: Array<UIButton> = [UIButton]()
let scrollView: UIScrollView
var selected: Int
let selectedWidth: CGFloat = 2
init(frame: CGRect, numberOfButtons: Int, buttonWidth: CGFloat) {
selected = 0
scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
scrollView.clipsToBounds = false
super.init(frame: frame)
for i in 0...numberOfButtons - 1 {
let margin: CGFloat = 10
let button = UIButton(type: UIButtonType.Custom)
button.frame = CGRect(x: CGFloat(i) * (buttonWidth + margin), y: 0, width: buttonWidth, height: frame.height)
scrollView.addSubview(button)
button.backgroundColor = UIColor.whiteColor()
buttons.append(button)
button.tag = i
button.layer.borderColor = color1.CGColor
if i == 0 { button.layer.borderWidth = selectedWidth}
button.setTitleColor(color1, forState: UIControlState.Normal)
button.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
scrollView.contentSize = CGSize(width: (buttonWidth + margin) * CGFloat(numberOfButtons), height: 0)
}
self.addSubview(scrollView)
}
func setButtonNames(names: Array<String>) throws {
guard names.count == buttons.count else {
throw ToggleViewError.WrongNameCount
}
for i in buttons.enumerate() {
i.element.setTitle(names[i.index], forState: UIControlState.Normal)
}
}
func buttonPressed(sender: UIButton) {
sender.layer.borderWidth = selectedWidth
selected = sender.tag
UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
sender.frame.offsetInPlace(dx: 0, dy: 5)
}, completion: nil)
UIView.animateWithDuration(0.1, delay: 0.1, options: UIViewAnimationOptions.CurveEaseIn, animations: {
sender.frame.offsetInPlace(dx: 0, dy: -5)
}, completion: nil)
for i in buttons.enumerate() {
if i.element != sender {
i.element.layer.borderWidth = 0
}
}
}
}
enum ToggleViewError: ErrorType {
case WrongNameCount
}
|
gpl-2.0
|
0f9f38e1e0a87dd20668b32ef2b25ed7
| 29.212121 | 128 | 0.562019 | 4.993322 | false | false | false | false |
airbnb/lottie-ios
|
Sources/Private/Model/Layers/SolidLayerModel.swift
|
3
|
1528
|
//
// SolidLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
import Foundation
/// A layer that holds a solid color.
final class SolidLayerModel: LayerModel {
// MARK: Lifecycle
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: SolidLayerModel.CodingKeys.self)
colorHex = try container.decode(String.self, forKey: .colorHex)
width = try container.decode(Double.self, forKey: .width)
height = try container.decode(Double.self, forKey: .height)
try super.init(from: decoder)
}
required init(dictionary: [String: Any]) throws {
colorHex = try dictionary.value(for: CodingKeys.colorHex)
width = try dictionary.value(for: CodingKeys.width)
height = try dictionary.value(for: CodingKeys.height)
try super.init(dictionary: dictionary)
}
// MARK: Internal
/// The color of the solid in Hex // Change to value provider.
let colorHex: String
/// The Width of the color layer
let width: Double
/// The height of the color layer
let height: Double
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(colorHex, forKey: .colorHex)
try container.encode(width, forKey: .width)
try container.encode(height, forKey: .height)
}
// MARK: Private
private enum CodingKeys: String, CodingKey {
case colorHex = "sc"
case width = "sw"
case height = "sh"
}
}
|
apache-2.0
|
768f4e3bf4cf614964e011e577a34cde
| 26.285714 | 83 | 0.697644 | 3.897959 | false | false | false | false |
jakub-tucek/fit-checker-2.0
|
fit-checker/networking/operations/BaseOperation.swift
|
1
|
1383
|
//
// BaseOperation.swift
// fit-checker
//
// Created by Josef Dolezal on 14/01/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Foundation
import Alamofire
/// Base class for network operations.
class BaseOperation: Operation {
/// Holds error when occured, nil otherwise
var error: Error? {
didSet {
// Print the error if occures
if let error = error {
Logger.shared.error("\(classForCoder): \(error)")
}
}
}
/// Injected request manager
var sessionManager: SessionManager
init(sessionManager: SessionManager) {
self.sessionManager = sessionManager
super.init()
}
/// Indicates wheter async operation is finished
var internalIsFinished = false
override var isFinished: Bool {
get {
return internalIsFinished
} set {
// Enable KVO on isFinished to notify queue if value is changed
willChangeValue(forKey: "isFinished")
internalIsFinished = newValue
didChangeValue(forKey: "isFinished")
}
}
}
/// Network operation promise, allows Operatation creator
/// to set custom callbacks.
class OperationPromise<T> {
/// Success callback
var success: (T) -> Void = { _ in }
/// Failure callback
var failure: () -> Void = {}
}
|
mit
|
18dae9604696bc4cfea9060b2c41f579
| 23.678571 | 75 | 0.611433 | 4.849123 | false | false | false | false |
myTargetSDK/mytarget-ios
|
myTargetDemoSwift/myTargetDemo/Views/AdCollectionCell.swift
|
1
|
1312
|
//
// AdCollectionCell.swift
// myTargetDemo
//
// Created by Alexander Vorobyev on 11.08.2022.
// Copyright © 2022 Mail.ru Group. All rights reserved.
//
import UIKit
final class AdCollectionCell: UICollectionViewCell {
static let reuseIdentifier: String = String(describing: AdCollectionCell.self)
var adView: UIView? {
didSet {
oldValue?.removeFromSuperview()
adView.map { contentView.insertSubview($0, belowSubview: line) }
setNeedsLayout()
}
}
private lazy var line: UIView = {
let view = UIView()
view.backgroundColor = .separatorColor()
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
contentView.addSubview(line)
}
override func layoutSubviews() {
super.layoutSubviews()
line.frame = CGRect(x: 0, y: frame.height - 1, width: frame.width, height: 1)
adView?.frame = bounds
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return adView?.sizeThatFits(size) ?? .zero
}
}
|
lgpl-3.0
|
a7a184c7e9036aaecd4965355b0a101a
| 23.277778 | 85 | 0.597254 | 4.552083 | false | false | false | false |
frtlupsvn/Vietnam-To-Go
|
VietNamToGo/SuperRecord/NSPredicateExtension.swift
|
3
|
4078
|
//
// NSPredicateExtension.swift
// SuperRecord
//
// Created by Piergiuseppe Longo on 26/11/14.
// Copyright (c) 2014 Michael Armstrong. All rights reserved.
//
import Foundation
//MARK: Logical operators
/**
Create a new NSPredicate as logical AND of left and right predicate
- parameter left:
- parameter right:
- returns: NSPredicate
*/
public func & (left : NSPredicate, right : NSPredicate )-> NSPredicate{
return [left] & [right]
}
/**
Create a new NSPredicate as logical AND of left and right predicates
- parameter left:
- parameter right: a collection NSPredicate
- returns: NSPredicate
*/
public func & (left : NSPredicate, right : [NSPredicate] )-> NSPredicate{
return [left] & right
}
/**
Create a new NSPredicate as logical AND of left and right predicates
- parameter left: a collection NSPredicate
- parameter right: a collection NSPredicate
- returns: NSPredicate
*/
public func & (left : [NSPredicate], right : [NSPredicate] )-> NSPredicate{
return NSCompoundPredicate(andPredicateWithSubpredicates: left + right)
}
/**
Create a new NSPredicate as logical OR of left and right predicate
- parameter left:
- parameter right:
- returns: NSPredicate
*/
public func | (left : NSPredicate, right : NSPredicate )-> NSPredicate{
return [left] | [right]
}
/**
Create a new NSPredicate as logical OR of left and right predicates
- parameter left:
- parameter right: a collection NSPredicate
- returns: NSPredicate
*/
public func | (left : NSPredicate, right : [NSPredicate] )-> NSPredicate{
return [left] | right
}
/**
Create a new NSPredicate as logical OR of left and right predicates
- parameter left: a collection NSPredicate
- parameter right: a collection NSPredicate
- returns: NSPredicate
*/
public func | (left : [NSPredicate], right : [NSPredicate] )-> NSPredicate{
return NSCompoundPredicate(orPredicateWithSubpredicates: left + right)
}
/**
Used to specify the the logical operator to use in the init of a complex NSPredicate
*/
public enum NSLogicOperator : String {
/**
And Operator
*/
case And = "AND"
/**
OR Operator
*/
case Or = "OR"
}
/**
Used to specify the the operator to use in NSPredicate.predicateBuilder
*/
public enum NSPredicateOperator : String {
/**
Operator &&
*/
case And = "AND"
/**
Operator ||
*/
case Or = "OR"
/**
Operator IN
*/
case In = "IN"
/**
Operator ==
*/
case Equal = "=="
/**
Operator !=
*/
case NotEqual = "!="
/**
Operator >
*/
case GreaterThan = ">"
/**
Operator >=
*/
case GreaterThanOrEqual = ">="
/**
Operator <
*/
case LessThan = "<"
/**
Operator <=
*/
case LessThanOrEqual = "<="
/**
Operator <=
*/
case Contains = "contains[c]"
}
public extension NSPredicate {
/**
Init a new NSPredicate using the input predicates adding parenthesis for more complex NSPredicate
- parameter firstPredicate:
- parameter secondPredicate:
- parameter NSLogicOperator: to use in the predicate AND/OR
- returns: NSPredicate
*/
public convenience init?(firstPredicate : NSPredicate, secondPredicate: NSPredicate, predicateOperator: NSLogicOperator ) {
self.init(format: "(\(firstPredicate)) \(predicateOperator.rawValue) (\(secondPredicate))")
}
/**
Build NSPredicate using the input parameters
- parameter attribute: the name of the attribute
- parameter value: the value the attribute should assume
- parameter predicateOperator: to use in the predicate
- returns: NSPredicate
*/
public class func predicateBuilder(attribute: String!, value: AnyObject, predicateOperator: NSPredicateOperator) -> NSPredicate? {
var predicate = NSPredicate(format: "%K \(predicateOperator.rawValue) $value", attribute)
predicate = predicate.predicateWithSubstitutionVariables(["value" : value]);
return predicate
}
}
|
mit
|
db70929640bd3cb07430b150d73f7ffe
| 20.356021 | 134 | 0.656449 | 4.536151 | false | false | false | false |
apple/swift-experimental-string-processing
|
Sources/Exercises/Participants/RegexParticipant.swift
|
1
|
2941
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
import _StringProcessing
import RegexBuilder
/*
TODO: We probably want to allow participants to register
multiple variations or strategies.
We have:
1) DSL vs literal
2) HareVM, TortoiseVM, transpile to PEG, transpile to
MatchingEngine
*/
struct RegexDSLParticipant: Participant {
static var name: String { "Regex DSL" }
// Produce a function that will parse a grapheme break entry from a line
static func graphemeBreakProperty() throws -> (String) -> GraphemeBreakEntry? {
graphemeBreakPropertyData(forLine:)
}
}
struct RegexLiteralParticipant: Participant {
static var name: String { "Regex Literal" }
// Produce a function that will parse a grapheme break entry from a line
static func graphemeBreakProperty() throws -> (String) -> GraphemeBreakEntry? {
graphemeBreakPropertyDataLiteral(forLine:)
}
}
// MARK: - Regex literal
private func extractFromCaptures(
_ match: (Substring, Substring, Substring?, Substring)
) -> GraphemeBreakEntry? {
guard let lowerScalar = Unicode.Scalar(hex: match.1),
let upperScalar = match.2.map(Unicode.Scalar.init(hex:)) ?? lowerScalar,
let property = Unicode.GraphemeBreakProperty(match.3)
else {
return nil
}
return GraphemeBreakEntry(lowerScalar...upperScalar, property)
}
@inline(__always) // get rid of generic please
private func graphemeBreakPropertyData<RP: RegexComponent>(
forLine line: String,
using regex: RP
) -> GraphemeBreakEntry? where RP.RegexOutput == (Substring, Substring, Substring?, Substring) {
line.wholeMatch(of: regex).map(\.output).flatMap(extractFromCaptures)
}
private func graphemeBreakPropertyDataLiteral(
forLine line: String
) -> GraphemeBreakEntry? {
let regex = try! Regex(
#"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s+;\s+(\w+).*"#,
as: (Substring, Substring, Substring?, Substring).self)
return graphemeBreakPropertyData(forLine: line, using: regex)
}
// MARK: - Builder DSL
private func graphemeBreakPropertyData(
forLine line: String
) -> GraphemeBreakEntry? {
line.wholeMatch {
TryCapture(OneOrMore(.hexDigit)) { Unicode.Scalar(hex: $0) }
Optionally {
".."
TryCapture(OneOrMore(.hexDigit)) { Unicode.Scalar(hex: $0) }
}
OneOrMore(.whitespace)
";"
OneOrMore(.whitespace)
TryCapture(OneOrMore(.word)) { Unicode.GraphemeBreakProperty($0) }
ZeroOrMore(.any)
}.map {
let (_, lower, upper, property) = $0.output
return GraphemeBreakEntry(lower...(upper ?? lower), property)
}
}
|
apache-2.0
|
f1bd42532640eaeb12cc4ff91c1284d4
| 29.010204 | 96 | 0.66916 | 4.045392 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures
|
Algorithms/Search/VariousDepthFirstTreeTraversalImplementations.playground/Contents.swift
|
1
|
872
|
//Recursive implementations for in-order, post-order and pre-order tree traversal
class TreeNode<T>{
var value:T
init(_ value:T){
self.value = value
}
var left:TreeNode?
var right:TreeNode?
}
func inOrder<T>(_ root:TreeNode<T>?){
if root == nil{
return
}
inOrder(root?.left)
guard let value = root?.value else {return}
print(value)
inOrder(root?.right)
return
}
func postOrder<T>(_ root:TreeNode<T>?){
if root == nil{
return
}
postOrder(root?.left)
postOrder(root?.right)
guard let value = root?.value else {return}
print(value)
return
}
func preOrder<T>(_ root:TreeNode<T>?){
if root == nil{
return
}
guard let value = root?.value else {return}
print(value)
preOrder(root?.left)
preOrder(root?.right)
return
}
|
mit
|
f8f23ec267d64726731b18647ffd2251
| 17.166667 | 81 | 0.586009 | 3.57377 | false | false | false | false |
googleads/googleads-mobile-ios-examples
|
Swift/advanced/SwiftUIDemo/SwiftUIDemo/Interstitial/InterstitialContentView.swift
|
1
|
2854
|
import GoogleMobileAds
import SwiftUI
struct InterstitialContentView: View {
@StateObject private var countdownTimer = CountdownTimer()
@State private var showGameOverAlert = false
private let coordinator = InterstitialAdCoordinator()
private let adViewControllerRepresentable = AdViewControllerRepresentable()
let navigationTitle: String
var adViewControllerRepresentableView: some View {
adViewControllerRepresentable
.frame(width: .zero, height: .zero)
}
var body: some View {
VStack(spacing: 20) {
Text("The Impossible Game")
.font(.largeTitle)
.background(adViewControllerRepresentableView)
Spacer()
Text("\(countdownTimer.timeLeft) seconds left!")
.font(.title2)
Button("Play Again") {
startNewGame()
}
.font(.title2)
.opacity(countdownTimer.isComplete ? 1 : 0)
Spacer()
}
.onAppear {
if !countdownTimer.isComplete {
startNewGame()
}
}
.onDisappear {
countdownTimer.pause()
}
.onChange(of: countdownTimer.isComplete) { newValue in
showGameOverAlert = newValue
}
.alert(isPresented: $showGameOverAlert) {
Alert(
title: Text("Game Over"),
message: Text("You lasted \(countdownTimer.countdownTime) seconds"),
dismissButton: .cancel(
Text("OK"),
action: {
coordinator.showAd(from: adViewControllerRepresentable.viewController)
}))
}
.navigationTitle(navigationTitle)
}
private func startNewGame() {
coordinator.loadAd()
countdownTimer.start()
}
}
struct InterstitialContentView_Previews: PreviewProvider {
static var previews: some View {
InterstitialContentView(navigationTitle: "Interstitial")
}
}
// MARK: - Helper to present Interstitial Ad
private struct AdViewControllerRepresentable: UIViewControllerRepresentable {
let viewController = UIViewController()
func makeUIViewController(context: Context) -> some UIViewController {
return viewController
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
}
private class InterstitialAdCoordinator: NSObject, GADFullScreenContentDelegate {
private var interstitial: GADInterstitialAd?
func loadAd() {
GADInterstitialAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/4411468910", request: GADRequest()
) { ad, error in
self.interstitial = ad
self.interstitial?.fullScreenContentDelegate = self
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
interstitial = nil
}
func showAd(from viewController: UIViewController) {
guard let interstitial = interstitial else {
return print("Ad wasn't ready")
}
interstitial.present(fromRootViewController: viewController)
}
}
|
apache-2.0
|
2942d11500455da37ae8294d65af1dab
| 25.924528 | 92 | 0.697968 | 4.929188 | false | false | false | false |
ianyh/Highball
|
Highball/ReblogTransitionAnimator.swift
|
1
|
1910
|
//
// ReblogTransitionAnimator.swift
// Highball
//
// Created by Ian Ynda-Hummel on 9/7/14.
// Copyright (c) 2014 ianynda. All rights reserved.
//
import UIKit
class ReblogTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var presenting = true
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.2
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey),
toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
else {
return
}
if presenting {
toViewController.view.alpha = 0
toViewController.view.frame = fromViewController.view.frame
transitionContext.containerView()!.addSubview(toViewController.view)
toViewController.viewWillAppear(true)
fromViewController.viewWillDisappear(true)
UIView.animateWithDuration(
transitionDuration(transitionContext),
animations: {
fromViewController.view.tintAdjustmentMode = .Dimmed
toViewController.view.alpha = 1
},
completion: { finished in
transitionContext.completeTransition(finished)
if finished {
toViewController.viewDidAppear(true)
fromViewController.viewDidDisappear(true)
}
}
)
} else {
toViewController.viewWillAppear(true)
fromViewController.viewWillDisappear(true)
UIView.animateWithDuration(
transitionDuration(transitionContext),
animations: {
toViewController.view.tintAdjustmentMode = .Normal
fromViewController.view.alpha = 0
},
completion: { finished in
transitionContext.completeTransition(finished)
if finished {
toViewController.viewDidAppear(true)
fromViewController.viewDidDisappear(true)
}
}
)
}
}
}
|
mit
|
4b4de32290755117b58d196b42cdf5e1
| 27.088235 | 114 | 0.760209 | 4.88491 | false | false | false | false |
longjianjiang/Drizzling
|
Drizzling/Drizzling/View/ThreeDaysForecastView.swift
|
1
|
5421
|
//
// ThreeDaysForecastView.swift
// Drizzling
//
// Created by longjianjiang on 2017/3/4.
// Copyright © 2017年 Jiang. All rights reserved.
//
import UIKit
import Kingfisher
class ForecastCell: UICollectionViewCell {
lazy var weekLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.black
label.textAlignment = .center
return label
}()
lazy var temperatureLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.black
label.textAlignment = .center
return label
}()
lazy var conditionImageview: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(weekLabel)
contentView.addSubview(temperatureLabel)
contentView.addSubview(conditionImageview)
}
override func layoutSubviews() {
super.layoutSubviews()
// weekLabel.snp.makeConstraints { (maker) in
// maker.top.equalTo(contentView).offset(10)
// maker.left.right.equalTo(contentView)
// maker.height.equalTo(20)
// }
//
// temperatureLabel.snp.makeConstraints { (maker) in
// maker.top.equalTo(weekLabel.snp.bottom).offset(5)
// maker.left.right.equalTo(contentView)
// maker.height.equalTo(20)
// }
//
// conditionImageview.snp.makeConstraints { (maker) in
// maker.top.equalTo(temperatureLabel.snp.bottom).offset(5)
// maker.left.right.equalTo(contentView)
// maker.height.equalTo(40)
// }
}
func configCell(day: ForecastDay) {
let unitStr = UserDefaults.standard.object(forKey: "unit") as! String
weekLabel.text = day.forecastDate?["weekday_short"] as! String?
if let icon = day.forecastIcon,
let low = day.forecastLowTemperature?[unitStr],
let high = day.forecastHighTemperature?[unitStr]{
self.temperatureLabel.text = "\(high) / \(low)"
let urlStr = "https://icons.wxug.com/i/c/k/\(icon).gif"
conditionImageview.kf.setImage(with: URL(string: urlStr))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ThreeDaysForecastView: UIView {
var collectionView: UICollectionView!
var darkStyle = false
var forecastDays: [ForecastDay]! = [] {
didSet {
collectionView.reloadData()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 105)
collectionView = UICollectionView.init(frame: self.bounds, collectionViewLayout: layout)
collectionView.dataSource = self;
collectionView.backgroundColor = UIColor.white
collectionView.register(ForecastCell.self, forCellWithReuseIdentifier: "forecast")
self.addSubview(collectionView)
// add observer to response change theme notification
NotificationCenter.default.addObserver(self, selector: #selector(changeToNight), name: NSNotification.Name(rawValue: "ChangeToNightNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(changeToDay), name: NSNotification.Name(rawValue: "ChangeToDayNotification"), object: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
// collectionView.snp.makeConstraints { (maker) in
// maker.left.bottom.right.top.equalTo(self)
// }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func changeToNight() {
self.collectionView.backgroundColor = UIColor.black
self.darkStyle = true
self.collectionView.reloadData()
}
@objc func changeToDay() {
self.collectionView.backgroundColor = UIColor.white
self.darkStyle = false
self.collectionView.reloadData()
}
}
extension ThreeDaysForecastView : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "forecast", for: indexPath) as! ForecastCell
if forecastDays.count > 0 {
if darkStyle {
cell.weekLabel.textColor = UIColor.white
cell.temperatureLabel.textColor = UIColor.white
} else {
cell.weekLabel.textColor = UIColor.black
cell.temperatureLabel.textColor = UIColor.black
}
cell.configCell(day: (forecastDays?[indexPath.row+1])!)
}
return cell
}
}
|
apache-2.0
|
0e529ffefbdfa5f82676ed220a555bdc
| 31.443114 | 167 | 0.627538 | 4.777778 | false | false | false | false |
slimane-swift/Hanger
|
Sources/Hanger.swift
|
1
|
2544
|
//
// Hanger.swift
// Hanger
//
// Created by Yuki Takei on 5/2/16.
//
//
public struct Hanger {
public init(connection: ClientConnection, request: Request, completion: ((Void) throws -> Response) -> Void) throws {
if case .Closed = connection.state {
throw StreamError.closedStream(data: [])
}
if case .Disconnected = connection.state {
let connection = ClientConnection(uri: request.uri)
try connection.open {
do {
try $0()
try writeRequest(connection: connection, request: request, completion: completion)
} catch {
completion {
try connection.close()
throw error
}
}
}
} else {
try writeRequest(connection: connection, request: request, completion: completion)
}
}
public init(request: Request, completion: ((Void) throws -> Response) -> Void) throws {
let connection = ClientConnection(uri: request.uri)
try connection.open {
do {
try $0()
try writeRequest(connection: connection, request: request, forceClose: true, completion: completion)
} catch {
completion {
try connection.close()
throw error
}
}
}
}
}
private func writeRequest(connection: ClientConnection, request: Request, forceClose: Bool = false, completion: ((Void) throws -> Response) -> Void) throws {
var request = request
try connection.send(request.serialize())
let parser = ResponseParser()
connection.receive { [unowned connection] in
do {
let data = try $0()
if let response = try parser.parse(data) {
completion {
try closeConnection(shouldClose: forceClose || !request.isKeepAlive, connection: connection)
return response
}
}
} catch {
completion {
try closeConnection(shouldClose: forceClose || !request.isKeepAlive, connection: connection)
throw error
}
}
}
}
private func closeConnection(shouldClose: Bool, connection: ClientConnection) throws {
if shouldClose {
try connection.close()
} else {
connection.unref()
}
}
|
mit
|
e68f6c390faa51f2d3b927f336923763
| 29.662651 | 157 | 0.527123 | 5.278008 | false | false | false | false |
ZezhouLi/Virtual-Keyboard
|
Virtual Keyboard/VKAudioController.swift
|
1
|
9982
|
//
// VKAudioController.swift
// Virtual Keyboard
//
// Created by Zezhou Li on 12/15/16.
// Copyright © 2016 Zezhou Li. All rights reserved.
//
// Framework
import AVFoundation
typealias VKAudioInputCallback = (
_ timeStamp: Double,
_ numberOfFrames: Int,
_ samples: [Float]
) -> Void
class VKAudioController: NSObject {
private(set) var audioUnit: AudioUnit!
let audioSession : AVAudioSession = AVAudioSession.sharedInstance()
var sampleRate: Float
var numberOfChannels: Int
private let outputBus: UInt32 = 0
private let inputBus: UInt32 = 1
private var audioInputCallback: VKAudioInputCallback!
var audioPlayer: AVAudioPlayer?
init(audioInputCallback callback: @escaping VKAudioInputCallback, sampleRate: Float = 44100.0, numberOfChannels: Int = 2) {
self.sampleRate = sampleRate
self.numberOfChannels = numberOfChannels
audioInputCallback = callback
}
func CheckError(_ error: OSStatus, operation: String) {
guard error != noErr else {
return
}
var result: String = ""
var char = Int(error.bigEndian)
for _ in 0..<4 {
guard isprint(Int32(char&255)) == 1 else {
result = "\(error)"
break
}
result.append(String(describing: UnicodeScalar(char&255)))
char = char/256
}
print("Error: \(operation) (\(result))")
exit(1)
}
private let recordingCallback: AURenderCallback = { (inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData)
-> OSStatus in
let audioInput = unsafeBitCast(inRefCon, to: VKAudioController.self)
var osErr: OSStatus = 0
var bufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(audioInput.numberOfChannels),
mDataByteSize: 4,
mData: nil))
osErr = AudioUnitRender(audioInput.audioUnit,
ioActionFlags,
inTimeStamp,
inBusNumber,
inNumberFrames,
&bufferList)
assert(osErr == noErr, "Audio Unit Render Error \(osErr)")
var monoSamples = [Float]()
let ptr = bufferList.mBuffers.mData?.assumingMemoryBound(to: Float.self)
monoSamples.append(contentsOf: UnsafeBufferPointer(start: ptr, count: Int(inNumberFrames)))
audioInput.audioInputCallback(inTimeStamp.pointee.mSampleTime / Double(audioInput.sampleRate),
Int(inNumberFrames),
monoSamples)
return noErr
}
// Setup audio session
private func setupAudioSession() {
// Configure the audio session
if !audioSession.availableCategories.contains(AVAudioSessionCategoryPlayAndRecord) {
print("can't record! bailing.")
return
}
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.overrideOutputAudioPort(.speaker)
// Set Session Sample Rate
try audioSession.setPreferredSampleRate(Double(sampleRate))
// Set Session Buffer Duration
let bufferDuration: TimeInterval = 0.01
try audioSession.setPreferredIOBufferDuration(bufferDuration)
audioSession.requestRecordPermission { (granted) -> Void in
if !granted {
print("Record permission denied")
}
}
} catch {
print("Setup Audio Session Error: \(error)")
}
}
// Setup IO unit
private func setupAudioUnit() {
// Create a new instance of AURemoteIO
var desc: AudioComponentDescription = AudioComponentDescription(
componentType: OSType(kAudioUnitType_Output),
componentSubType: OSType(kAudioUnitSubType_RemoteIO),
componentManufacturer: OSType(kAudioUnitManufacturer_Apple),
componentFlags: 0,
componentFlagsMask: 0)
// Get component
let inputComponent: AudioComponent! = AudioComponentFindNext(nil, &desc)
assert(inputComponent != nil, "Couldn't find a default component")
// Create an instance of the AudioUnit
var tempUnit: AudioUnit?
CheckError(AudioComponentInstanceNew(inputComponent, &tempUnit), operation: "Could not get component!")
self.audioUnit = tempUnit
// Enable input and output on AURemoteIO
var one: UInt32 = 1
CheckError(AudioUnitSetProperty(audioUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Input,
inputBus,
&one,
UInt32(MemoryLayout<UInt32>.size)),
operation: "Could not enable input on AURemoteIO")
CheckError(AudioUnitSetProperty(audioUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Output,
outputBus,
&one,
UInt32(MemoryLayout<UInt32>.size)),
operation: "Could not enable output on AURemoteIO")
// Explicitly set the input and output client formats
var streamFormatDesc: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: Double(sampleRate),
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved,
mBytesPerPacket: 4,
mFramesPerPacket: 1,
mBytesPerFrame: 4,
mChannelsPerFrame: UInt32(self.numberOfChannels),
mBitsPerChannel: 4 * 8,
mReserved: 0
)
// Set format for input and output busses
CheckError(AudioUnitSetProperty(audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output,
inputBus,
&streamFormatDesc,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size)),
operation: "Couldn't set the input client format on AURemoteIO")
// CheckError(AudioUnitSetProperty(audioUnit,
// kAudioUnitProperty_StreamFormat,
// kAudioUnitScope_Input,
// outputBus,
// &streamFormatDesc,
// UInt32(MemoryLayout<AudioStreamBasicDescription>.size)),
// operation: "Couldn't set the output client format on AURemoteIO")
// Setup callback on AURemoteIO
var inputCallbackStruct = AURenderCallbackStruct(
inputProc: recordingCallback,
inputProcRefCon: UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
CheckError(AudioUnitSetProperty(audioUnit,
AudioUnitPropertyID(kAudioOutputUnitProperty_SetInputCallback),
AudioUnitScope(kAudioUnitScope_Global),
inputBus,
&inputCallbackStruct,
UInt32(MemoryLayout<AURenderCallbackStruct>.size)),
operation: "couldn't set render callback on AURemoteIO")
CheckError(AudioUnitSetProperty(audioUnit,
AudioUnitPropertyID(kAudioUnitProperty_ShouldAllocateBuffer),
AudioUnitScope(kAudioUnitScope_Output),
inputBus,
&one,
UInt32(MemoryLayout<UInt32>.size)),
operation: "couldn't allocate buffers")
}
func startIO() {
do {
if self.audioUnit == nil {
setupAudioSession()
setupAudioUnit()
}
try self.audioSession.setActive(true)
CheckError(AudioUnitInitialize(self.audioUnit), operation: "AudioUnit Initialize Error!")
} catch {
print("Start Recording error: \(error)")
}
}
func startRecording() {
CheckError(AudioOutputUnitStart(self.audioUnit), operation: "Audio Output Unit Start Error!")
}
func stopRecording() {
CheckError(AudioOutputUnitStop(self.audioUnit), operation: "Audio Output Unit Start Error!")
}
func createButtonPressedSound() {
let url = URL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "wav")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
} catch {
print("Couldn't create AVAudioPlayer")
audioPlayer = nil
}
audioPlayer?.numberOfLoops = -1
}
func playButtonPressedSound() {
audioPlayer?.play()
}
func stopButtonPressedSound() {
audioPlayer?.stop()
}
}
|
apache-2.0
|
d2d7b975df8777574a4ab5d8cf480866
| 37.53668 | 131 | 0.539926 | 6.082267 | false | false | false | false |
dreamsxin/swift
|
test/SILGen/objc_final.swift
|
6
|
1030
|
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil | FileCheck %s
// REQUIRES: objc_interop
import Foundation
final class Foo {
@objc func foo() {}
// CHECK-LABEL: sil hidden [thunk] @_TToFC10objc_final3Foo3foo
@objc var prop: Int = 0
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC10objc_final3Foog4propSi
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC10objc_final3Foos4propSi
}
// CHECK-LABEL: sil hidden @_TF10objc_final7callFooFCS_3FooT_
func callFoo(_ x: Foo) {
// Calls to the final @objc method statically reference the native entry
// point.
// CHECK: function_ref @_TFC10objc_final3Foo3foo
x.foo()
// Final @objc properties are still accessed directly.
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: load [[PROP]] : $*Int
let prop = x.prop
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: assign {{%.*}} to [[PROP]] : $*Int
x.prop = prop
}
|
apache-2.0
|
ade96c00abf7c139f85653c8f204c644
| 33.333333 | 129 | 0.65534 | 3.249211 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Client/Frontend/Browser/Tabs/InactiveTabHeader.swift
|
2
|
3368
|
// 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
enum ExpandButtonState {
case right
case down
var image: UIImage? {
switch self {
case .right:
return UIImage(named: ImageIdentifiers.menuChevron)?.imageFlippedForRightToLeftLayoutDirection()
case .down:
return UIImage(named: ImageIdentifiers.findNext)
}
}
}
class InactiveTabHeader: UITableViewHeaderFooterView, NotificationThemeable, ReusableCell {
var state: ExpandButtonState? {
willSet(state) {
moreButton.setImage(state?.image, for: .normal)
}
}
lazy var titleLabel: UILabel = .build { titleLabel in
titleLabel.text = self.title
titleLabel.textColor = UIColor.theme.homePanel.activityStreamHeaderText
titleLabel.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .headline, maxSize: 17)
titleLabel.adjustsFontForContentSizeCategory = true
titleLabel.minimumScaleFactor = 0.6
titleLabel.numberOfLines = 1
titleLabel.adjustsFontSizeToFitWidth = true
}
lazy var moreButton: UIButton = .build { button in
button.isHidden = true
button.setImage(self.state?.image, for: .normal)
button.contentHorizontalAlignment = .trailing
}
var title: String? {
willSet(newTitle) {
titleLabel.text = newTitle
}
}
override func prepareForReuse() {
super.prepareForReuse()
applyTheme()
moreButton.setTitle(nil, for: .normal)
moreButton.accessibilityIdentifier = nil
titleLabel.text = nil
moreButton.removeTarget(nil, action: nil, for: .allEvents)
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.addSubview(titleLabel)
contentView.addSubview(moreButton)
moreButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
isAccessibilityElement = true
accessibilityTraits = .button
accessibilityIdentifier = AccessibilityIdentifiers.TabTray.inactiveTabHeader
NSLayoutConstraint.activate([
titleLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 19),
titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -19),
titleLabel.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 16),
titleLabel.trailingAnchor.constraint(equalTo: moreButton.leadingAnchor, constant: -16),
moreButton.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor),
moreButton.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -28),
])
applyTheme()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func applyTheme() {
let theme = BuiltinThemeName(rawValue: LegacyThemeManager.instance.current.name) ?? .normal
self.titleLabel.textColor = theme == .dark ? .white : .black
}
}
|
mpl-2.0
|
43082b99d3de98fe1480186bb254c40d
| 35.608696 | 110 | 0.68557 | 5.287284 | false | false | false | false |
Bouke/DNS
|
Sources/DNS/Bytes.swift
|
1
|
19485
|
import Foundation
enum EncodeError: Swift.Error {
}
enum DecodeError: Swift.Error {
case invalidMessageSize
case invalidLabelSize
case invalidLabelOffset
case unicodeDecodingError
case invalidIntegerSize
case invalidIPAddress
case invalidDataSize
case invalidQuestion
}
func deserializeName(_ data: Data, _ position: inout Data.Index) throws -> String {
var components = [String]()
let startPosition = position
while true {
guard position < data.endIndex else {
throw DecodeError.invalidLabelOffset
}
let step = data[position]
if step & 0xc0 == 0xc0 {
let offset = Int(try UInt16(data: data, position: &position) ^ 0xc000)
// Prevent cyclic references
// Its safe to assume the pointer is to an earlier label
// See https://www.ietf.org/rfc/rfc1035.txt 4.1.4
guard var pointer = data.index(data.startIndex, offsetBy: offset, limitedBy: startPosition - 1) else {
throw DecodeError.invalidLabelOffset
}
components += try deserializeName(data, &pointer).components(separatedBy: ".").filter({ $0 != "" })
break
}
guard let start = data.index(position, offsetBy: 1, limitedBy: data.endIndex),
let end = data.index(start, offsetBy: Int(step), limitedBy: data.endIndex) else {
throw DecodeError.invalidLabelSize
}
if step > 0 {
guard let component = String(bytes: Data(data[start..<end]), encoding: .utf8) else {
throw DecodeError.unicodeDecodingError
}
components.append(component)
}
position = end
if step == 0 {
break
}
}
return components.joined(separator: ".") + "."
}
public typealias Labels = [String: Data.Index]
func serializeName(_ name: String, onto buffer: inout Data, labels: inout Labels) throws {
// re-use existing label
if let index = labels[name] {
buffer += (0xc000 | UInt16(index)).bytes
return
}
// position of the new label
labels[name] = buffer.endIndex
var components = name.components(separatedBy: ".").filter { $0 != "" }
guard !components.isEmpty else {
buffer.append(0)
return
}
let codes = Array(components.removeFirst().utf8)
buffer.append(UInt8(codes.count))
buffer += codes
if components.count > 0 {
try serializeName(components.joined(separator: "."), onto: &buffer, labels: &labels)
} else {
buffer.append(0)
}
}
typealias RecordCommonFields = (name: String, type: UInt16, unique: Bool, internetClass: InternetClass, ttl: UInt32)
func deserializeRecordCommonFields(_ data: Data, _ position: inout Data.Index) throws -> RecordCommonFields {
let name = try deserializeName(data, &position)
let type = try UInt16(data: data, position: &position)
let rrClass = try UInt16(data: data, position: &position)
let internetClass = InternetClass(rrClass & 0x7fff)
let ttl = try UInt32(data: data, position: &position)
return (name, type, rrClass & 0x8000 == 0x8000, internetClass, ttl)
}
func serializeRecordCommonFields(_ common: RecordCommonFields, onto buffer: inout Data, labels: inout Labels) throws {
try serializeName(common.name, onto: &buffer, labels: &labels)
buffer.append(common.type.bytes)
buffer.append((common.internetClass | (common.unique ? 0x8000 : 0)).bytes)
buffer.append(common.ttl.bytes)
}
func deserializeRecord(_ data: Data, _ position: inout Data.Index) throws -> ResourceRecord {
let common = try deserializeRecordCommonFields(data, &position)
switch ResourceRecordType(common.type) {
case .host: return try HostRecord<IPv4>(deserialize: data, position: &position, common: common)
case .host6: return try HostRecord<IPv6>(deserialize: data, position: &position, common: common)
case .service: return try ServiceRecord(deserialize: data, position: &position, common: common)
case .text: return try TextRecord(deserialize: data, position: &position, common: common)
case .pointer: return try PointerRecord(deserialize: data, position: &position, common: common)
case .alias: return try AliasRecord(deserialize: data, position: &position, common: common)
case .startOfAuthority: return try StartOfAuthorityRecord(deserialize: data, position: &position, common: common)
case .nameServer: return try NameServerRecord(deserialize: data, position: &position, common: common)
case .mailExchange: return try MailExchangeRecord(deserialize: data, position: &position, common: common)
default: return try Record(deserialize: data, position: &position, common: common)
}
}
extension Message {
// MARK: Serialization
/// Serialize a `Message` for sending over TCP.
///
/// The DNS TCP format prepends the message size before the actual
/// message.
///
/// - Returns: `Data` to be send over TCP.
/// - Throws:
public func serializeTCP() throws -> Data {
let data = try serialize()
precondition(data.count <= UInt16.max)
return UInt16(truncatingIfNeeded: data.count).bytes + data
}
/// Serialize a `Message` for sending over UDP.
///
/// - Returns: `Data` to be send over UDP.
/// - Throws:
public func serialize() throws -> Data {
var bytes = Data()
var labels = Labels()
let qr: UInt16 = type == .response ? 1 : 0
var flags: UInt16 = qr << 15
flags |= UInt16(operationCode) << 11
flags |= (authoritativeAnswer ? 1 : 0) << 10
flags |= (truncation ? 1 : 0) << 9
flags |= (recursionDesired ? 1 : 0) << 8
flags |= (recursionAvailable ? 1 : 0) << 7
flags |= UInt16(returnCode)
// header
bytes += id.bytes
bytes += flags.bytes
bytes += UInt16(questions.count).bytes
bytes += UInt16(answers.count).bytes
bytes += UInt16(authorities.count).bytes
bytes += UInt16(additional.count).bytes
// questions
for question in questions {
try serializeName(question.name, onto: &bytes, labels: &labels)
bytes += question.type.bytes
bytes += question.internetClass.bytes
}
for answer in answers {
try answer.serialize(onto: &bytes, labels: &labels)
}
for authority in authorities {
try authority.serialize(onto: &bytes, labels: &labels)
}
for additional in additional {
try additional.serialize(onto: &bytes, labels: &labels)
}
return bytes
}
/// Deserializes a `Message` from a TCP stream.
///
/// The DNS TCP format prepends the message size before the actual
/// message.
///
/// - Parameter bytes: the received bytes.
/// - Throws:
public init(deserializeTCP bytes: Data) throws {
precondition(bytes.count >= 2)
var position = bytes.startIndex
let size = try Int(UInt16(data: bytes, position: &position))
// strip size bytes (tcp only?)
let bytes = Data(bytes[2..<2+size]) // copy? :(
precondition(bytes.count == Int(size))
try self.init(deserialize: bytes)
}
/// Deserializes a `Message` from a UDP stream.
///
/// - Parameter bytes: the bytes to deserialize.
/// - Throws:
public init(deserialize bytes: Data) throws {
guard bytes.count >= 12 else {
throw DecodeError.invalidMessageSize
}
var position = bytes.startIndex
id = try UInt16(data: bytes, position: &position)
let flags = try UInt16(data: bytes, position: &position)
type = flags >> 15 & 1 == 1 ? .response : .query
operationCode = OperationCode(flags >> 11 & 0x7)
authoritativeAnswer = flags >> 10 & 0x1 == 0x1
truncation = flags >> 9 & 0x1 == 0x1
recursionDesired = flags >> 8 & 0x1 == 0x1
recursionAvailable = flags >> 7 & 0x1 == 0x1
returnCode = ReturnCode(flags & 0x7)
let numQuestions = try UInt16(data: bytes, position: &position)
let numAnswers = try UInt16(data: bytes, position: &position)
let numAuthorities = try UInt16(data: bytes, position: &position)
let numAdditional = try UInt16(data: bytes, position: &position)
questions = try (0..<numQuestions).map { _ in try Question(deserialize: bytes, position: &position) }
answers = try (0..<numAnswers).map { _ in try deserializeRecord(bytes, &position) }
authorities = try (0..<numAuthorities).map { _ in try deserializeRecord(bytes, &position) }
additional = try (0..<numAdditional).map { _ in try deserializeRecord(bytes, &position) }
}
}
extension Record: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, type, unique, internetClass, ttl) = common
let size = Int(try UInt16(data: data, position: &position))
let dataStart = position
guard data.formIndex(&position, offsetBy: size, limitedBy: data.endIndex) else {
throw DecodeError.invalidDataSize
}
self.data = Data(data[dataStart..<position])
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, type, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer.append(contentsOf: UInt16(data.count).bytes + data)
}
}
extension NameServerRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, type, unique, internetClass, ttl) = common
let length = try UInt16(data: data, position: &position)
let expectedPosition = position + Data.Index(length)
self.nameServer = try deserializeName(data, &position)
guard position == expectedPosition else {
throw DecodeError.invalidDataSize
}
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, type, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer += [0, 0]
let startPosition = buffer.endIndex
try serializeName(nameServer, onto: &buffer, labels: &labels)
// Set the length before the data field
let length = UInt16(buffer.endIndex - startPosition)
buffer.replaceSubrange((startPosition - 2)..<startPosition, with: length.bytes)
}
}
extension MailExchangeRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, type, unique, internetClass, ttl) = common
let length = try UInt16(data: data, position: &position)
let expectedPosition = position + Data.Index(length)
self.priority = try UInt16(data: data, position: &position)
self.exchangeServer = try deserializeName(data, &position)
guard position == expectedPosition else {
throw DecodeError.invalidDataSize
}
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, type, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer += [0, 0]
let startPosition = buffer.endIndex
buffer += priority.bytes
try serializeName(exchangeServer, onto: &buffer, labels: &labels)
// Set the length before the data field
let length = UInt16(buffer.endIndex - startPosition)
buffer.replaceSubrange((startPosition - 2)..<startPosition, with: length.bytes)
}
}
extension HostRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, _, unique, internetClass, ttl) = common
let size = Int(try UInt16(data: data, position: &position))
let dataStart = position
guard data.formIndex(&position, offsetBy: size, limitedBy: data.endIndex) else {
throw DecodeError.invalidDataSize
}
guard let ipType = IPType(networkBytes: Data(data[dataStart..<position])) else {
throw DecodeError.invalidIPAddress
}
ip = ipType
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
switch ip {
case let ip as IPv4:
let data = ip.bytes
try serializeRecordCommonFields((name, ResourceRecordType.host, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer.append(UInt16(data.count).bytes)
buffer.append(data)
case let ip as IPv6:
let data = ip.bytes
try serializeRecordCommonFields((name, ResourceRecordType.host6, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer.append(UInt16(data.count).bytes)
buffer.append(data)
default:
abort()
}
}
}
extension ServiceRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, _, unique, internetClass, ttl) = common
let length = try UInt16(data: data, position: &position)
let expectedPosition = position + Data.Index(length)
priority = try UInt16(data: data, position: &position)
weight = try UInt16(data: data, position: &position)
port = try UInt16(data: data, position: &position)
server = try deserializeName(data, &position)
guard position == expectedPosition else {
throw DecodeError.invalidDataSize
}
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, ResourceRecordType.service, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer += [0, 0]
let startPosition = buffer.endIndex
buffer += priority.bytes
buffer += weight.bytes
buffer += port.bytes
try serializeName(server, onto: &buffer, labels: &labels)
// Set the length before the data field
let length = UInt16(buffer.endIndex - startPosition)
buffer.replaceSubrange((startPosition - 2)..<startPosition, with: length.bytes)
}
}
extension TextRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, _, unique, internetClass, ttl) = common
let endIndex = Int(try UInt16(data: data, position: &position)) + position
var attrs = [String: String]()
var other = [String]()
while position < endIndex {
let size = Int(try UInt8(data: data, position: &position))
let labelStart = position
guard size > 0 else {
break
}
guard data.formIndex(&position, offsetBy: size, limitedBy: data.endIndex) else {
throw DecodeError.invalidLabelSize
}
guard let label = String(bytes: Data(data[labelStart..<position]), encoding: .utf8) else {
throw DecodeError.unicodeDecodingError
}
let attr = label.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false).map { String($0) }
if attr.count == 2 {
attrs[attr[0]] = attr[1]
} else {
other.append(attr[0])
}
}
self.attributes = attrs
self.values = other
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, ResourceRecordType.text, unique, internetClass, ttl), onto: &buffer, labels: &labels)
let data = attributes.reduce(Data()) {
let attr = "\($1.key)=\($1.value)".utf8
return $0 + UInt8(attr.count).bytes + attr
}
buffer += UInt16(data.count).bytes
buffer += data
}
}
extension PointerRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, _, unique, internetClass, ttl) = common
position += 2
destination = try deserializeName(data, &position)
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, ResourceRecordType.pointer, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer += [0, 0]
let startPosition = buffer.endIndex
try serializeName(destination, onto: &buffer, labels: &labels)
// Set the length before the data field
let length = UInt16(buffer.endIndex - startPosition)
buffer.replaceSubrange((startPosition - 2)..<startPosition, with: length.bytes)
}
}
extension AliasRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, _, unique, internetClass, ttl) = common
position += 2
canonicalName = try deserializeName(data, &position)
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, ResourceRecordType.alias, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer += [0, 0]
let startPosition = buffer.endIndex
try serializeName(canonicalName, onto: &buffer, labels: &labels)
// Set the length before the data field
let length = UInt16(buffer.endIndex - startPosition)
buffer.replaceSubrange((startPosition - 2)..<startPosition, with: length.bytes)
}
}
extension StartOfAuthorityRecord: ResourceRecord {
init(deserialize data: Data, position: inout Data.Index, common: RecordCommonFields) throws {
(name, _, unique, internetClass, ttl) = common
let length = try UInt16(data: data, position: &position)
let expectedPosition = position + Data.Index(length)
mname = try deserializeName(data, &position)
rname = try deserializeName(data, &position)
serial = try UInt32(data: data, position: &position)
refresh = try Int32(data: data, position: &position)
retry = try Int32(data: data, position: &position)
expire = try Int32(data: data, position: &position)
minimum = try UInt32(data: data, position: &position)
guard position == expectedPosition else {
throw DecodeError.invalidDataSize
}
}
public func serialize(onto buffer: inout Data, labels: inout Labels) throws {
try serializeRecordCommonFields((name, ResourceRecordType.startOfAuthority, unique, internetClass, ttl), onto: &buffer, labels: &labels)
buffer += [0, 0]
let startPosition = buffer.endIndex
try serializeName(mname, onto: &buffer, labels: &labels)
try serializeName(rname, onto: &buffer, labels: &labels)
buffer += serial.bytes
buffer += refresh.bytes
buffer += retry.bytes
buffer += expire.bytes
buffer += minimum.bytes
// Set the length before the data field
let length = UInt16(buffer.endIndex - startPosition)
buffer.replaceSubrange((startPosition - 2)..<startPosition, with: length.bytes)
}
}
|
mit
|
5c7a8b2f7fe519a2a26b3ab83136e5a4
| 40.903226 | 144 | 0.641878 | 4.311795 | false | false | false | false |
MAARK/Charts
|
Source/Charts/Renderers/LegendRenderer.swift
|
3
|
20658
|
//
// LegendRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(ChartLegendRenderer)
open class LegendRenderer: Renderer
{
/// the legend object this renderer renders
@objc open var legend: Legend?
@objc public init(viewPortHandler: ViewPortHandler, legend: Legend?)
{
super.init(viewPortHandler: viewPortHandler)
self.legend = legend
}
/// Prepares the legend and calculates all needed forms, labels and colors.
@objc open func computeLegend(data: ChartData)
{
guard let legend = legend else { return }
if !legend.isLegendCustom
{
var entries: [LegendEntry] = []
// loop for building up the colors and labels used in the legend
for i in 0..<data.dataSetCount
{
guard let dataSet = data.getDataSetByIndex(i) else { continue }
var clrs: [NSUIColor] = dataSet.colors
let entryCount = dataSet.entryCount
// if we have a barchart with stacked bars
if dataSet is IBarChartDataSet &&
(dataSet as! IBarChartDataSet).isStacked
{
let bds = dataSet as! IBarChartDataSet
var sLabels = bds.stackLabels
let minEntries = min(clrs.count, bds.stackSize)
for j in 0..<minEntries
{
let label: String?
if (sLabels.count > 0 && minEntries > 0) {
let labelIndex = j % minEntries
label = sLabels.indices.contains(labelIndex) ? sLabels[labelIndex] : nil
} else {
label = nil
}
entries.append(
LegendEntry(
label: label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is IPieChartDataSet
{
let pds = dataSet as! IPieChartDataSet
for j in 0..<min(clrs.count, entryCount)
{
entries.append(
LegendEntry(
label: (pds.entryForIndex(j) as? PieChartDataEntry)?.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
if dataSet.label != nil
{
// add the legend description label
entries.append(
LegendEntry(
label: dataSet.label,
form: .none,
formSize: CGFloat.nan,
formLineWidth: CGFloat.nan,
formLineDashPhase: 0.0,
formLineDashLengths: nil,
formColor: nil
)
)
}
}
else if dataSet is ICandleChartDataSet &&
(dataSet as! ICandleChartDataSet).decreasingColor != nil
{
let candleDataSet = dataSet as! ICandleChartDataSet
entries.append(
LegendEntry(
label: nil,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.decreasingColor
)
)
entries.append(
LegendEntry(
label: dataSet.label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: candleDataSet.increasingColor
)
)
}
else
{ // all others
for j in 0..<min(clrs.count, entryCount)
{
let label: String?
// if multiple colors are set for a DataSet, group them
if j < clrs.count - 1 && j < entryCount - 1
{
label = nil
}
else
{ // add label to the last entry
label = dataSet.label
}
entries.append(
LegendEntry(
label: label,
form: dataSet.form,
formSize: dataSet.formSize,
formLineWidth: dataSet.formLineWidth,
formLineDashPhase: dataSet.formLineDashPhase,
formLineDashLengths: dataSet.formLineDashLengths,
formColor: clrs[j]
)
)
}
}
}
legend.entries = entries + legend.extraEntries
}
// calculate all dimensions of the legend
legend.calculateDimensions(labelFont: legend.font, viewPortHandler: viewPortHandler)
}
@objc open func renderLegend(context: CGContext)
{
guard let legend = legend else { return }
if !legend.enabled
{
return
}
let labelFont = legend.font
let labelTextColor = legend.textColor
let labelLineHeight = labelFont.lineHeight
let formYOffset = labelLineHeight / 2.0
var entries = legend.entries
let defaultFormSize = legend.formSize
let formToTextSpace = legend.formToTextSpace
let xEntrySpace = legend.xEntrySpace
let yEntrySpace = legend.yEntrySpace
let orientation = legend.orientation
let horizontalAlignment = legend.horizontalAlignment
let verticalAlignment = legend.verticalAlignment
let direction = legend.direction
// space between the entries
let stackSpace = legend.stackSpace
let yoffset = legend.yOffset
let xoffset = legend.xOffset
var originPosX: CGFloat = 0.0
switch horizontalAlignment
{
case .left:
if orientation == .vertical
{
originPosX = xoffset
}
else
{
originPosX = viewPortHandler.contentLeft + xoffset
}
if direction == .rightToLeft
{
originPosX += legend.neededWidth
}
case .right:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth - xoffset
}
else
{
originPosX = viewPortHandler.contentRight - xoffset
}
if direction == .leftToRight
{
originPosX -= legend.neededWidth
}
case .center:
if orientation == .vertical
{
originPosX = viewPortHandler.chartWidth / 2.0
}
else
{
originPosX = viewPortHandler.contentLeft
+ viewPortHandler.contentWidth / 2.0
}
originPosX += (direction == .leftToRight
? +xoffset
: -xoffset)
// Horizontally layed out legends do the center offset on a line basis,
// So here we offset the vertical ones only.
if orientation == .vertical
{
if direction == .leftToRight
{
originPosX -= legend.neededWidth / 2.0 - xoffset
}
else
{
originPosX += legend.neededWidth / 2.0 - xoffset
}
}
}
switch orientation
{
case .horizontal:
var calculatedLineSizes = legend.calculatedLineSizes
var calculatedLabelSizes = legend.calculatedLabelSizes
var calculatedLabelBreakPoints = legend.calculatedLabelBreakPoints
var posX: CGFloat = originPosX
var posY: CGFloat
switch verticalAlignment
{
case .top:
posY = yoffset
case .bottom:
posY = viewPortHandler.chartHeight - yoffset - legend.neededHeight
case .center:
posY = (viewPortHandler.chartHeight - legend.neededHeight) / 2.0 + yoffset
}
var lineIndex: Int = 0
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
if i < calculatedLabelBreakPoints.count &&
calculatedLabelBreakPoints[i]
{
posX = originPosX
posY += labelLineHeight + yEntrySpace
}
if posX == originPosX &&
horizontalAlignment == .center &&
lineIndex < calculatedLineSizes.count
{
posX += (direction == .rightToLeft
? calculatedLineSizes[lineIndex].width
: -calculatedLineSizes[lineIndex].width) / 2.0
lineIndex += 1
}
let isStacked = e.label == nil // grouped forms have null labels
if drawingForm
{
if direction == .rightToLeft
{
posX -= formSize
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if !isStacked
{
if drawingForm
{
posX += direction == .rightToLeft ? -formToTextSpace : formToTextSpace
}
if direction == .rightToLeft
{
posX -= calculatedLabelSizes[i].width
}
drawLabel(
context: context,
x: posX,
y: posY,
label: e.label!,
font: labelFont,
textColor: labelTextColor)
if direction == .leftToRight
{
posX += calculatedLabelSizes[i].width
}
posX += direction == .rightToLeft ? -xEntrySpace : xEntrySpace
}
else
{
posX += direction == .rightToLeft ? -stackSpace : stackSpace
}
}
case .vertical:
// contains the stacked legend size in pixels
var stack = CGFloat(0.0)
var wasStacked = false
var posY: CGFloat = 0.0
switch verticalAlignment
{
case .top:
posY = (horizontalAlignment == .center
? 0.0
: viewPortHandler.contentTop)
posY += yoffset
case .bottom:
posY = (horizontalAlignment == .center
? viewPortHandler.chartHeight
: viewPortHandler.contentBottom)
posY -= legend.neededHeight + yoffset
case .center:
posY = viewPortHandler.chartHeight / 2.0 - legend.neededHeight / 2.0 + legend.yOffset
}
for i in 0 ..< entries.count
{
let e = entries[i]
let drawingForm = e.form != .none
let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize
var posX = originPosX
if drawingForm
{
if direction == .leftToRight
{
posX += stack
}
else
{
posX -= formSize - stack
}
drawForm(
context: context,
x: posX,
y: posY + formYOffset,
entry: e,
legend: legend)
if direction == .leftToRight
{
posX += formSize
}
}
if e.label != nil
{
if drawingForm && !wasStacked
{
posX += direction == .leftToRight ? formToTextSpace : -formToTextSpace
}
else if wasStacked
{
posX = originPosX
}
if direction == .rightToLeft
{
posX -= (e.label! as NSString).size(withAttributes: [.font: labelFont]).width
}
if !wasStacked
{
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
else
{
posY += labelLineHeight + yEntrySpace
drawLabel(context: context, x: posX, y: posY, label: e.label!, font: labelFont, textColor: labelTextColor)
}
// make a step down
posY += labelLineHeight + yEntrySpace
stack = 0.0
}
else
{
stack += formSize + stackSpace
wasStacked = true
}
}
}
}
private var _formLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
/// Draws the Legend-form at the given position with the color at the given index.
@objc open func drawForm(
context: CGContext,
x: CGFloat,
y: CGFloat,
entry: LegendEntry,
legend: Legend)
{
guard
let formColor = entry.formColor,
formColor != NSUIColor.clear
else { return }
var form = entry.form
if form == .default
{
form = legend.form
}
let formSize = entry.formSize.isNaN ? legend.formSize : entry.formSize
context.saveGState()
defer { context.restoreGState() }
switch form
{
case .none:
// Do nothing
break
case .empty:
// Do not draw, but keep space for the form
break
case .default: fallthrough
case .circle:
context.setFillColor(formColor.cgColor)
context.fillEllipse(in: CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .square:
context.setFillColor(formColor.cgColor)
context.fill(CGRect(x: x, y: y - formSize / 2.0, width: formSize, height: formSize))
case .line:
let formLineWidth = entry.formLineWidth.isNaN ? legend.formLineWidth : entry.formLineWidth
let formLineDashPhase = entry.formLineDashPhase.isNaN ? legend.formLineDashPhase : entry.formLineDashPhase
let formLineDashLengths = entry.formLineDashLengths == nil ? legend.formLineDashLengths : entry.formLineDashLengths
context.setLineWidth(formLineWidth)
if formLineDashLengths != nil && formLineDashLengths!.count > 0
{
context.setLineDash(phase: formLineDashPhase, lengths: formLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(formColor.cgColor)
_formLineSegmentsBuffer[0].x = x
_formLineSegmentsBuffer[0].y = y
_formLineSegmentsBuffer[1].x = x + formSize
_formLineSegmentsBuffer[1].y = y
context.strokeLineSegments(between: _formLineSegmentsBuffer)
}
}
/// Draws the provided label at the given position.
@objc open func drawLabel(context: CGContext, x: CGFloat, y: CGFloat, label: String, font: NSUIFont, textColor: NSUIColor)
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .left, attributes: [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor])
}
}
|
apache-2.0
|
3dc8bcaac8ce42cf2ba04273a2e77ad8
| 34.926957 | 200 | 0.418724 | 7.150571 | false | false | false | false |
objecthub/swift-lispkit
|
Sources/LispKit/Base/Bitset.swift
|
1
|
17662
|
//
// Bitset.swift
// LispKit
//
// This is a slightly modified version of the code at https://github.com/lemire/SwiftBitset
// Copyright © 2019 Daniel Lemire. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
///
/// Efficient set container for non-negative integers.
///
public final class Bitset: Sequence, Equatable, CustomStringConvertible,
Hashable, ExpressibleByArrayLiteral {
static let wordSize = 8
/// How many words have been allocated?
var capacity: Int
/// How many words are used?
var wordcount: Int
/// Biset storage
var data: UnsafeMutablePointer<UInt64>
/// Initializer for empty bitset
public init(capacity: Int = 1) {
self.capacity = capacity
self.wordcount = 0
self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: capacity)
}
/// Copy initializer
public init(_ other: Bitset) {
self.capacity = other.wordcount
self.wordcount = other.wordcount
self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: other.wordcount)
for i in 0..<self.capacity {
self.data[i] = other.data[i]
}
}
deinit {
data.deallocate()
}
/// Make a bitset containing the list of integers, all values must be non-negative
/// adding the value i to the bitset will cause the use of least (i+8)/8 bytes
public init(_ allints: [Int]) {
var mymax = 0
for i in allints {
mymax = mymax < i ? i : mymax
}
self.wordcount = (mymax+63)/64 + 1
self.capacity = self.wordcount
self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: self.wordcount)
for k in 0..<wordcount {
self.data[k] = 0
}
self.addMany(allints)
}
/// Initializing from array literal
required public init(arrayLiteral elements: Int...) {
var mymax = 0
for i in elements {
mymax = mymax < i ? i : mymax
}
wordcount = (mymax+63)/64 + 1
capacity = wordcount
data = UnsafeMutablePointer<UInt64>.allocate(capacity:wordcount)
for k in 0..<wordcount {
data[k] = 0
}
for i in elements {
add(i)
}
}
// load an uncompressed bitmap from a byte buffer, in ascending order
// The expected format is equivalent to that of an array of 64-bit unsigned integers stored
// using the little endian encoding, except that zero bytes at the end are omitted.
// This function is compatible with the toData() function.
public init(bytes: Data) {
assert(Bitset.wordSize == 8) // this logic is expecting a 64-bit internal representation
let byteCount = bytes.count
if (byteCount == 0) {
self.capacity = 1
self.wordcount = 0
self.data = UnsafeMutablePointer<UInt64>.allocate(capacity:capacity)
return
}
self.capacity = (byteCount - 1) / Bitset.wordSize + 1
self.wordcount = capacity
self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: self.capacity)
func iterate<T>(_ pointer: T, _ f: (T, Int, Int) -> UInt64) -> Int {
var remaining = byteCount
var offset = 0
for w in 0..<capacity {
if remaining < Bitset.wordSize { break }
// copy entire word - assumes data is aligned to word boundary
let next = offset + Bitset.wordSize
var word: UInt64 = f(pointer, offset, w)
word = CFSwapInt64LittleToHost(word)
remaining -= Bitset.wordSize
offset = next
data[w] = word
}
return remaining
}
var remaining = byteCount
if remaining > Bitset.wordSize {
remaining = bytes.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> Int in
iterate(pointer) { (pointer, offset, _) in
pointer.load(fromByteOffset: offset, as: UInt64.self)
}
}
}
if remaining > 0 {
// copy last word fragment
// manual byte copy is about 50% faster than `copyBytes` with `withUnsafeMutableBytes`
var word: UInt64 = 0
let offset = byteCount - remaining
for b in 0..<remaining {
let byte = UInt64(clamping: bytes[offset + b])
word = word | (byte << (b * 8))
}
data[capacity-1] = word
}
// TODO: shrink bitmap according to MSB
}
// store as uncompressed bitmap as a byte buffer in ascending order, with a bytes
// size that captures the most significant bit, or an empty instance if no bits are
// present. The format is equivalent to that of an array of 64-bit unsigned integers
// stored using the little endian encoding, except that zero bytes at the end are
// omitted. This function is compatible with the init(bytes: Data) constructor.
public func toData() -> Data {
assert(Bitset.wordSize == 8) // this logic is expecting a 64-bit internal representation
let heighestWord = self.heighestWord()
if heighestWord < 0 { return Data() }
let lastWord = Int64(bitPattern: data[heighestWord])
let lastBit = Int(flsll(lastWord))
let lastBytes = lastBit == 0 ? 0 : (lastBit - 1) / 8 + 1
let size = heighestWord * Bitset.wordSize + lastBytes
var output = Data(capacity: size)
for w in 0...heighestWord {
var word = CFSwapInt64HostToLittle(data[w])
let byteCount = w == heighestWord ? lastBytes : Bitset.wordSize
let bytes = Data(bytes: &word, count: byteCount) // about 10x faster than memory copy
output.append(bytes)
}
return output
}
public typealias Element = Int
// return an empty bitset
public static var allZeros: Bitset {
return Bitset()
}
// union between two bitsets, producing a new bitset
public static func | (lhs: Bitset, rhs: Bitset) -> Bitset {
let mycopy = Bitset(lhs)
mycopy.union(rhs)
return mycopy
}
// compute the union between two bitsets inplace
public static func |= (lhs: Bitset, rhs: Bitset) {
lhs.union(rhs)
}
// difference between two bitsets, producing a new bitset
public static func - (lhs: Bitset, rhs: Bitset) -> Bitset {
let mycopy = Bitset(lhs)
mycopy.difference(rhs)
return mycopy
}
// inplace difference between two bitsets
public static func -= (lhs: Bitset, rhs: Bitset) {
lhs.difference(rhs)
}
// symmetric difference between two bitsets, producing a new bitset
public static func ^ (lhs: Bitset, rhs: Bitset) -> Bitset {
let mycopy = Bitset(lhs)
mycopy.symmetricDifference(rhs)
return mycopy
}
// inplace symmetric difference between two bitsets
public static func ^= (lhs: Bitset, rhs: Bitset) {
lhs.symmetricDifference(rhs)
}
// compute the union between two bitsets inplace
public static func &= (lhs: Bitset, rhs: Bitset) {
lhs.intersection(rhs)
}
// computes the intersection between two bitsets and return a new bitset
public static func & (lhs: Bitset, rhs: Bitset) -> Bitset {
let mycopy = Bitset(lhs)
mycopy.intersection(rhs)
return mycopy
}
// hash value for the bitset
public func hash(into hasher: inout Hasher) {
let b: UInt64 = 31
var hash: UInt64 = 0
for i in 0..<wordcount {
let w = data[i]
hash = hash &* b &+ w
}
hash = hash ^ (hash >> 33)
hash = hash &* 0xff51afd7ed558ccd
hash = hash ^ (hash >> 33)
hash = hash &* 0xc4ceb9fe1a85ec53
hasher.combine(hash)
}
// returns a string representation of the bitset
public var description: String {
var ret = prefix(100).map { $0.description }.joined(separator: ", ")
if count() >= 100 {
ret.append(", ...")
}
return "{\(ret)}"
}
// create an iterator over the values contained in the bitset
public func makeIterator() -> BitsetIterator {
return BitsetIterator(self)
}
// count how many values have been stored in the bitset (this function is not
// free of computation)
public func count() -> Int {
var sum: Int = 0
for i in 0..<wordcount {
let w = data[i]
sum = sum &+ w.nonzeroBitCount
}
return sum
}
// proxy for "count"
public func cardinality() -> Int { return count() }
// add a value to the bitset, all values must be non-negative
// adding the value i to the bitset will cause the use of least (i+8)/8 bytes
public func add(_ value: Int) {
let index = value >> 6
if index >= self.wordcount { increaseWordCount( index + 1) }
data[index] |= 1 << (UInt64(value & 63))
}
// add all the values to the bitset
// adding the value i to the bitset will cause the use of least (i+8)/8 bytes
public func addMany(_ allints: Int...) {
var mymax = 0
for i in allints {
mymax = mymax < i ? i : mymax
}
let maxindex = mymax >> 6
if maxindex >= self.wordcount {
increaseWordCount(maxindex + 1)
}
for i in allints {
add(i)
}
}
// add all the values to the bitset
// adding the value i to the bitset will cause the use of least (i+8)/8 bytes
public func addMany(_ allints: [Int]) {
var mymax = 0
for i in allints {
mymax = mymax < i ? i : mymax
}
let maxindex = mymax >> 6
if maxindex >= self.wordcount {
increaseWordCount(maxindex + 1)
}
for i in allints {
add(i)
}
}
// check that a value is in the bitset, all values must be non-negative
public func contains(_ value: Int) -> Bool {
let index = value >> 6
if index >= self.wordcount {
return false
}
return data[index] & (1 << (UInt64(value & 63))) != 0
}
public subscript(value: Int) -> Bool {
get {
return contains(value)
}
set(newValue) {
if newValue {
add(value)
} else {
remove(value)
}
}
}
// compute the intersection (in place) with another bitset
public func intersection(_ other: Bitset) {
let mincount = Swift.min(self.wordcount, other.wordcount)
for i in 0..<mincount { data[i] &= other.data[i] }
for i in mincount..<self.wordcount { data[i] = 0 }
}
// compute the size of the intersection with another bitset
public func intersectionCount(_ other: Bitset) -> Int {
let mincount = Swift.min(self.wordcount, other.wordcount)
var sum = 0
for i in 0..<mincount { sum = sum &+ ( data[i] & other.data[i]).nonzeroBitCount }
return sum
}
// compute the union (in place) with another bitset
public func union(_ other: Bitset) {
let mincount = Swift.min(self.wordcount, other.wordcount)
for i in 0..<mincount {
data[i] |= other.data[i]
}
if other.wordcount > self.wordcount {
self.matchWordCapacity(other.wordcount)
self.wordcount = other.wordcount
for i in mincount..<other.wordcount {
data[i] = other.data[i]
}
}
}
// compute the size of the union with another bitset
public func unionCount(_ other: Bitset) -> Int {
let mincount = Swift.min(self.wordcount, other.wordcount)
var sum = 0
for i in 0..<mincount {
sum = sum &+ (data[i] | other.data[i]).nonzeroBitCount
}
if other.wordcount > self.wordcount {
for i in mincount..<other.wordcount {
sum = sum &+ (other.data[i]).nonzeroBitCount
}
} else {
for i in mincount..<self.wordcount {
sum = sum &+ (data[i]).nonzeroBitCount
}
}
return sum
}
// compute the symmetric difference (in place) with another bitset
public func symmetricDifference(_ other: Bitset) {
let mincount = Swift.min(self.wordcount, other.wordcount)
for i in 0..<mincount {
data[i] ^= other.data[i]
}
if other.wordcount > self.wordcount {
self.matchWordCapacity(other.wordcount)
self.wordcount = other.wordcount
for i in mincount..<other.wordcount {
data[i] = other.data[i]
}
}
}
// compute the size union with another bitset
public func symmetricDifferenceCount(_ other: Bitset) -> Int {
let mincount = Swift.min(self.wordcount, other.wordcount)
var sum = 0
for i in 0..<mincount {
sum = sum &+ (data[i] ^ other.data[i]).nonzeroBitCount
}
if other.wordcount > self.wordcount {
for i in mincount..<other.wordcount {
sum = sum &+ other.data[i].nonzeroBitCount
}
} else {
for i in mincount..<self.wordcount {
sum = sum &+ (data[i]).nonzeroBitCount
}
}
return sum
}
// compute the difference (in place) with another bitset
public func difference(_ other: Bitset) {
let mincount = Swift.min(self.wordcount, other.wordcount)
for i in 0..<mincount {
data[i] &= ~other.data[i]
}
}
// compute the size of the difference with another bitset
public func differenceCount(_ other: Bitset) -> Int {
let mincount = Swift.min(self.wordcount, other.wordcount)
var sum = 0
for i in 0..<mincount {
sum = sum &+ ( data[i] & ~other.data[i]).nonzeroBitCount
}
for i in mincount..<self.wordcount {
sum = sum &+ (data[i]).nonzeroBitCount
}
return sum
}
// remove a value, must be non-negative
public func remove(_ value: Int) {
let index = value >> 6
if index < self.wordcount {
data[index] &= ~(1 << UInt64(value & 63))
}
}
// remove a value, if it is present it is removed, otherwise it is added, must
// be non-negative
public func flip(_ value: Int) {
let index = value >> 6
if index < self.wordcount {
data[index] ^= 1 << UInt64(value & 63)
} else {
increaseWordCount(index + 1)
data[index] |= 1 << UInt64(value & 63)
}
}
// remove many values, all must be non-negative
public func removeMany(_ allints: Int...) {
for i in allints {
remove(i)
}
}
// return the memory usage of the backing array in bytes
public func memoryUsage() -> Int {
return self.capacity * 8
}
// check whether the value is empty
public func isEmpty() -> Bool {
for i in 0..<wordcount {
let w = data[i]
if w != 0 {
return false
}
}
return true
}
// remove all elements, optionally keeping the capacity intact
public func removeAll(keepingCapacity keepCapacity: Bool = false) {
wordcount = 0
if !keepCapacity {
data.deallocate()
capacity = 8 // reset to some default
data = UnsafeMutablePointer<UInt64>.allocate(capacity:capacity)
}
}
// Returns the next element in the bitset, starting the search from `current`
public func next(current: Int = 0) -> Int? {
var value = current
var x = value >> 6
if x >= self.wordcount {
return nil
}
var w = self.data[x]
w >>= UInt64(value & 63)
if w != 0 {
value = value &+ w.trailingZeroBitCount
return value
}
x = x &+ 1
while x < self.wordcount {
let w = self.data[x]
if w != 0 {
value = x &* 64 &+ w.trailingZeroBitCount
return value
}
x = x &+ 1
}
return nil
}
private static func nextCapacity(mincap: Int) -> Int {
return 2 * mincap
}
// caller is responsible to ensure that index < wordcount otherwise this function fails!
func increaseWordCount(_ newWordCount: Int) {
if(newWordCount <= wordcount) {
print(newWordCount, wordcount)
}
if newWordCount > capacity {
growWordCapacity(Bitset.nextCapacity(mincap : newWordCount))
}
for i in wordcount..<newWordCount {
data[i] = 0
}
wordcount = newWordCount
}
func growWordCapacity(_ newcapacity: Int) {
let newdata = UnsafeMutablePointer<UInt64>.allocate(capacity:newcapacity)
for i in 0..<self.wordcount {
newdata[i] = self.data[i]
}
data.deallocate()
data = newdata
self.capacity = newcapacity
}
func matchWordCapacity(_ newcapacity: Int) {
if newcapacity > self.capacity {
growWordCapacity(newcapacity)
}
}
func heighestWord() -> Int {
for i in (0..<wordcount).reversed() {
let w = data[i]
if w.nonzeroBitCount > 0 { return i }
}
return -1
}
// checks whether the two bitsets have the same content
public static func == (lhs: Bitset, rhs: Bitset) -> Bool {
if lhs.wordcount > rhs.wordcount {
for i in rhs.wordcount..<lhs.wordcount where lhs.data[i] != 0 {
return false
}
} else if lhs.wordcount < rhs.wordcount {
for i in lhs.wordcount..<rhs.wordcount where rhs.data[i] != 0 {
return false
}
}
let mincount = Swift.min(rhs.wordcount, lhs.wordcount)
for i in 0..<mincount where rhs.data[i] != lhs.data[i] {
return false
}
return true
}
}
public struct BitsetIterator: IteratorProtocol {
let bitset: Bitset
var value: Int = -1
init(_ bitset: Bitset) {
self.bitset = bitset
}
public mutating func next() -> Int? {
value = value &+ 1
var x = value >> 6
if x >= bitset.wordcount {
return nil
}
var w = bitset.data[x]
w >>= UInt64(value & 63)
if w != 0 {
value = value &+ w.trailingZeroBitCount
return value
}
x = x &+ 1
while x < bitset.wordcount {
let w = bitset.data[x]
if w != 0 {
value = x &* 64 &+ w.trailingZeroBitCount
return value
}
x = x &+ 1
}
return nil
}
}
|
apache-2.0
|
821b2b81a3fe9e7fb021766734e176b3
| 28.240066 | 94 | 0.624653 | 3.763264 | false | false | false | false |
yrchen/edx-app-ios
|
Source/CourseDashboardCell.swift
|
1
|
3284
|
//
// CourseDashboardCell.swift
// edX
//
// Created by Jianfeng Qiu on 13/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
class CourseDashboardCell: UITableViewCell {
static let identifier = "CourseDashboardCellIdentifier"
//TODO: all these should be adjusted once the final UI is ready
private let ICON_SIZE : CGFloat = OEXTextStyle.pointSizeForTextSize(OEXTextSize.XXLarge)
private let ICON_MARGIN : CGFloat = 30.0
private let LABEL_MARGIN : CGFloat = 75.0
private let LABEL_SIZE_HEIGHT = 20.0
private let CONTAINER_SIZE_HEIGHT = 60.0
private let CONTAINER_MARGIN_BOTTOM = 15.0
private let INDICATOR_SIZE_WIDTH = 10.0
private let container = UIView()
private let iconView = UIImageView()
private let titleLabel = UILabel()
private let detailLabel = UILabel()
private let bottomLine = UIView()
private var titleTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .Base, color : OEXStyles.sharedStyles().neutralXDark())
}
private var detailTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .XXSmall, color : OEXStyles.sharedStyles().neutralBase())
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureViews()
}
func useItem(item : CourseDashboardItem) {
self.titleLabel.attributedText = titleTextStyle.attributedStringWithText(item.title)
self.detailLabel.attributedText = detailTextStyle.attributedStringWithText(item.detail)
self.iconView.image = item.icon.imageWithFontSize(ICON_SIZE)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureViews() {
self.bottomLine.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
applyStandardSeparatorInsets()
self.container.addSubview(iconView)
self.container.addSubview(titleLabel)
self.container.addSubview(detailLabel)
self.contentView.addSubview(container)
self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
iconView.tintColor = OEXStyles.sharedStyles().neutralLight()
container.snp_makeConstraints { make -> Void in
make.edges.equalTo(contentView)
}
iconView.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(container).offset(ICON_MARGIN)
make.centerY.equalTo(container)
}
titleLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(container).offset(LABEL_MARGIN)
make.trailing.lessThanOrEqualTo(container)
make.top.equalTo(container).offset(LABEL_SIZE_HEIGHT)
make.height.equalTo(LABEL_SIZE_HEIGHT)
}
detailLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(titleLabel)
make.trailing.lessThanOrEqualTo(container)
make.top.equalTo(titleLabel.snp_bottom)
make.height.equalTo(LABEL_SIZE_HEIGHT)
}
}
}
|
apache-2.0
|
0d2327d8a3e3796f58c03548da0bcef4
| 35.488889 | 109 | 0.666565 | 4.923538 | false | false | false | false |
insidegui/WWDC
|
WWDC/PreferencesCoordinator.swift
|
1
|
2088
|
//
// PreferencesCoordinator.swift
// WWDC
//
// Created by Guilherme Rambo on 20/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RxCocoa
import RxSwift
import ConfCore
enum PreferencesTab: Int {
case general
case playback
}
final class PreferencesCoordinator {
private let disposeBag = DisposeBag()
private let windowController: PreferencesWindowController
private let tabController: WWDCTabViewController<PreferencesTab>
private let generalController: GeneralPreferencesViewController
private let playbackController: PlaybackPreferencesViewController
#if ICLOUD
var userDataSyncEngine: UserDataSyncEngine? {
get {
return generalController.userDataSyncEngine
}
set {
generalController.userDataSyncEngine = newValue
}
}
#endif
init(syncEngine: SyncEngine) {
windowController = PreferencesWindowController()
tabController = WWDCTabViewController(windowController: windowController)
// General
generalController = GeneralPreferencesViewController.loadFromStoryboard(syncEngine: syncEngine)
generalController.identifier = NSUserInterfaceItemIdentifier(rawValue: "General")
let generalItem = NSTabViewItem(viewController: generalController)
generalItem.label = "General"
tabController.addTabViewItem(generalItem)
// Playback
playbackController = PlaybackPreferencesViewController.loadFromStoryboard()
playbackController.identifier = NSUserInterfaceItemIdentifier(rawValue: "videos")
let playbackItem = NSTabViewItem(viewController: playbackController)
playbackItem.label = "Playback"
tabController.addTabViewItem(playbackItem)
windowController.contentViewController = tabController
}
private func commonInit() {
}
func show(in tab: PreferencesTab = .general) {
windowController.window?.center()
windowController.showWindow(nil)
tabController.activeTab = tab
}
}
|
bsd-2-clause
|
8a8308c054beab93a72bb9e9fe367606
| 27.589041 | 103 | 0.724485 | 5.86236 | false | false | false | false |
luismatute/On-The-Map
|
On The Map/User.swift
|
1
|
690
|
//
// User.swift
// On The Map
//
// Created by Luis Matute on 6/2/15.
// Copyright (c) 2015 Luis Matute. All rights reserved.
//
import Foundation
struct User {
var id = ""
var sessionID = ""
var firstName = ""
var lastName = ""
init(dict: [String: AnyObject]) {
if let session = dict[UdacityClient.JSONResponseKeys.Session] as? [String: AnyObject] {
if let account = dict[UdacityClient.JSONResponseKeys.Account] as? [String: AnyObject] {
id = account[UdacityClient.JSONResponseKeys.UserID] as! String
sessionID = session[UdacityClient.JSONResponseKeys.SessionID] as! String
}
}
}
}
|
mit
|
98b84d69944e4734519c59c67c31e4e3
| 26.64 | 99 | 0.614493 | 4.156627 | false | false | false | false |
aaronraimist/firefox-ios
|
Client/Frontend/UIConstants.swift
|
1
|
5059
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
public struct UIConstants {
static let AboutHomePage = NSURL(string: "\(WebServer.sharedInstance.base)/about/home/")!
static let AppBackgroundColor = UIColor.blackColor()
static let SystemBlueColor = UIColor(red: 0 / 255, green: 122 / 255, blue: 255 / 255, alpha: 1)
static let PrivateModePurple = UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1)
static let PrivateModeLocationBackgroundColor = UIColor(red: 31 / 255, green: 31 / 255, blue: 31 / 255, alpha: 1)
static let PrivateModeLocationBorderColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.15)
static let PrivateModeActionButtonTintColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.8)
static let PrivateModeTextHighlightColor = UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1)
static let PrivateModeInputHighlightColor = UIColor(red: 120 / 255, green: 120 / 255, blue: 165 / 255, alpha: 1)
static let PrivateModeReaderModeBackgroundColor = UIColor(red: 89 / 255, green: 89 / 255, blue: 89 / 255, alpha: 1)
static let PrivateModeToolbarTintColor = UIColor(red: 74 / 255, green: 74 / 255, blue: 74 / 255, alpha: 1)
static let ToolbarHeight: CGFloat = 44
static let DefaultRowHeight: CGFloat = 58
static let DefaultPadding: CGFloat = 10
static let SnackbarButtonHeight: CGFloat = 48
// Static fonts
static let DefaultChromeSize: CGFloat = 14
static let DefaultChromeSmallSize: CGFloat = 11
static let PasscodeEntryFontSize: CGFloat = 36
static let DefaultChromeFont: UIFont = UIFont.systemFontOfSize(DefaultChromeSize, weight: UIFontWeightRegular)
static let DefaultChromeBoldFont = UIFont.boldSystemFontOfSize(DefaultChromeSize)
static let DefaultChromeSmallFontBold = UIFont.boldSystemFontOfSize(DefaultChromeSmallSize)
static let PasscodeEntryFont = UIFont.systemFontOfSize(PasscodeEntryFontSize, weight: UIFontWeightBold)
// These highlight colors are currently only used on Snackbar buttons when they're pressed
static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9)
static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0)
static let PanelBackgroundColor = UIColor.whiteColor()
static let SeparatorColor = UIColor(rgb: 0xcccccc)
static let HighlightBlue = UIColor(red:76/255, green:158/255, blue:255/255, alpha:1)
static let DestructiveRed = UIColor(red: 255/255, green: 64/255, blue: 0/255, alpha: 1.0)
static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.25)
static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1)
// These colours are used on the Menu
static let MenuToolbarBackgroundColorNormal = UIColor(red: 241/255, green: 241/255, blue: 241/255, alpha: 1.0)
static let MenuToolbarBackgroundColorPrivate = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1.0)
static let MenuToolbarTintColorNormal = BackgroundColor
static let MenuToolbarTintColorPrivate = UIColor.whiteColor()
static let MenuBackgroundColorNormal = UIColor(red: 223/255, green: 223/255, blue: 223/255, alpha: 1.0)
static let MenuBackgroundColorPrivate = UIColor(red: 59/255, green: 59/255, blue: 59/255, alpha: 1.0)
static let MenuSelectedItemTintColor = UIColor(red: 0.30, green: 0.62, blue: 1.0, alpha: 1.0)
// settings
static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0)
static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0)
static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0)
static let TableViewDisabledRowTextColor = UIColor.lightGrayColor()
static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4)
static let TableViewHeaderFooterHeight = CGFloat(44)
static let TableViewRowErrorTextColor = UIColor(red: 255/255, green: 0/255, blue: 26/255, alpha: 1.0)
static let TableViewRowWarningTextColor = UIColor(red: 245/255, green: 166/255, blue: 35/255, alpha: 1.0)
static let TableViewRowActionAccessoryColor = UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1.0)
// Firefox Orange
static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1)
// Passcode dot gray
static let PasscodeDotColor = UIColor(rgb: 0x4A4A4A)
/// JPEG compression quality for persisted screenshots. Must be between 0-1.
static let ScreenshotQuality: Float = 0.3
static let ActiveScreenshotQuality: CGFloat = 0.5
static let OKString = NSLocalizedString("OK", comment: "OK button")
static let CancelString = NSLocalizedString("Cancel", comment: "Label for Cancel button")
}
|
mpl-2.0
|
5198db88cc25b80a99f9326cf9ec0419
| 63.037975 | 119 | 0.730381 | 3.946178 | false | false | false | false |
zisko/swift
|
test/decl/typealias/protocol.swift
|
1
|
6830
|
// RUN: %target-typecheck-verify-swift
// Tests for typealias inside protocols
protocol Bad {
associatedtype X<T> // expected-error {{associated types must not have a generic parameter list}}
typealias Y<T> // expected-error {{expected '=' in type alias declaration}}
}
protocol Col {
associatedtype Elem
typealias E = Elem?
var elem: Elem { get }
}
protocol CB {
associatedtype C : Col
// Self at top level
typealias S = Self
func cloneDefinitely() -> S
// Self in bound generic position
typealias OS = Self?
func cloneMaybe() -> OS
// Associated type of archetype
typealias E = C.Elem
func setIt(_ element: E)
// Typealias of archetype
typealias EE = C.E
func setItSometimes(_ element: EE)
// Associated type in bound generic position
typealias OE = C.Elem?
func setItMaybe(_ element: OE)
// Complex type expression
typealias FE = (C) -> (C.Elem) -> Self
func teleport(_ fn: FE)
}
// Generic signature requirement involving protocol typealias
func go1<T : CB, U : Col>(_ col: U, builder: T) where U.Elem == T.E { // OK
builder.setIt(col.elem)
}
func go2<T : CB, U : Col>(_ col: U, builder: T) where U.Elem == T.C.Elem { // OK
builder.setIt(col.elem)
}
// Test for same type requirement with typealias == concrete
func go3<T : CB>(_ builder: T) where T.E == Int {
builder.setIt(1)
}
// Test for conformance to protocol with associatedtype and another with
// typealias with same name
protocol MyIterator {
associatedtype Elem
func next() -> Elem?
}
protocol MySeq {
associatedtype I : MyIterator
typealias Elem = Self.I.Elem
func makeIterator() -> I
func getIndex(_ i: Int) -> Elem
func first() -> Elem
}
extension MySeq where Self : MyIterator {
func makeIterator() -> Self {
return self
}
}
func plusOne<S: MySeq>(_ s: S, i: Int) -> Int where S.Elem == Int {
return s.getIndex(i) + 1
}
struct OneIntSeq: MySeq, MyIterator {
let e : Float
func next() -> Float? {
return e
}
func getIndex(_ i: Int) -> Float {
return e
}
}
protocol MyIntIterator {
typealias Elem = Int
}
struct MyIntSeq : MyIterator, MyIntIterator {
func next() -> Elem? {
return 0
}
}
protocol MyIntIterator2 {}
extension MyIntIterator2 {
typealias Elem = Int
}
struct MyIntSeq2 : MyIterator, MyIntIterator2 {
func next() -> Elem? {
return 0
}
}
// test for conformance correctness using typealias in extension
extension MySeq {
func first() -> Elem {
return getIndex(0)
}
}
// Typealiases whose underlying type is a structural type written in terms of
// associated types
protocol P1 {
associatedtype A
typealias F = (A) -> ()
}
protocol P2 {
associatedtype B
}
func go3<T : P1, U : P2>(_ x: T) -> U where T.F == U.B {
}
// Specific diagnosis for things that look like Swift 2.x typealiases
protocol P3 {
typealias T // expected-error {{type alias is missing an assigned type; use 'associatedtype' to define an associated type requirement}}
typealias U : P2 // expected-error {{type alias is missing an assigned type; use 'associatedtype' to define an associated type requirement}}
}
// Test for not crashing on recursive aliases
protocol Circular {
typealias Y = Self.Y // expected-error {{type alias 'Y' is not a member type of 'Self'}}
typealias Y2 = Y2 // expected-error {{type alias 'Y2' references itself}}
// expected-note@-1 {{type declared here}}
typealias Y3 = Y4 // expected-note {{type declared here}}
typealias Y4 = Y3 // expected-error {{type alias 'Y3' references itself}}
}
// Qualified and unqualified references to protocol typealiases from concrete type
protocol P5 {
associatedtype A
typealias X = Self
typealias T1 = Int
typealias T2 = A
var a: T2 { get }
}
protocol P6 {
typealias A = Int
typealias B = Self
}
struct T5 : P5 {
// This is OK -- the typealias is fully concrete
var a: P5.T1 // OK
// Invalid -- cannot represent associated type of existential
var v2: P5.T2 // expected-error {{type alias 'T2' can only be used with a concrete type or generic parameter base}}
var v3: P5.X // expected-error {{type alias 'X' can only be used with a concrete type or generic parameter base}}
// Unqualified reference to typealias from a protocol conformance
var v4: T1 // OK
var v5: T2 // OK
// Qualified reference
var v6: T5.T1 // OK
var v7: T5.T2 // OK
var v8 = P6.A.self
var v9 = P6.B.self // expected-error {{type alias 'B' can only be used with a concrete type or generic parameter base}}
}
// Unqualified lookup finds typealiases in protocol extensions
protocol P7 {
associatedtype A
typealias Z = A
}
extension P7 {
typealias Y = A
}
struct S7 : P7 {
typealias A = Int
func inTypeContext(y: Y) { }
func inExpressionContext() {
_ = Y.self
_ = Z.self
_ = T5.T1.self
_ = T5.T2.self
}
}
protocol P8 {
associatedtype B
@available(*, unavailable, renamed: "B")
typealias A = B // expected-note{{'A' has been explicitly marked unavailable here}}
}
func testP8<T: P8>(_: T) where T.A == Int { } // expected-error{{'A' has been renamed to 'B'}}{{34-35=B}}
// Associated type resolution via lookup should find typealiases in protocol extensions
protocol Edible {
associatedtype Snack
}
protocol CandyWrapper {
associatedtype Wrapped
}
extension CandyWrapper where Wrapped : Edible {
typealias Snack = Wrapped.Snack
}
struct Candy {}
struct CandyBar : CandyWrapper {
typealias Wrapped = CandyEdible
}
struct CandyEdible : Edible {
typealias Snack = Candy
}
// Edible.Snack is witnessed by 'typealias Snack' inside the
// constrained extension of CandyWrapper above
extension CandyBar : Edible {}
protocol P9 {
typealias A = Int
}
func testT9a<T: P9, U>(_: T, _: U) where T.A == U { }
func testT9b<T: P9>(_: T) where T.A == Float { } // expected-error{{'T.A' cannot be equal to both 'Float' and 'P9.A' (aka 'Int')}}
struct X<T> { }
protocol P10 {
associatedtype A
typealias T = Int
@available(*, deprecated, message: "just use Int, silly")
typealias V = Int
}
extension P10 {
typealias U = Float
}
extension P10 where T == Int { } // expected-warning{{neither type in same-type constraint ('P10.T' (aka 'Int') or 'Int') refers to a generic parameter or associated type}}
extension P10 where A == X<T> { }
extension P10 where A == X<U> { } // expected-error{{use of undeclared type 'U'}}
extension P10 where A == X<Self.U> { }
extension P10 where V == Int { } // expected-warning 3{{'V' is deprecated: just use Int, silly}}
// expected-warning@-1{{neither type in same-type constraint ('P10.V' (aka 'Int') or 'Int') refers to a generic parameter or associated type}}
// rdar://problem/36003312
protocol P11 {
typealias A = Y11
}
struct X11<T: P11> { }
struct Y11: P11 { }
extension P11 {
func foo(_: X11<Self.A>) { }
}
|
apache-2.0
|
80e56c2bd138e04182b908bfd42c298b
| 22.390411 | 172 | 0.673353 | 3.477597 | false | false | false | false |
salesforce-ux/design-system-ios
|
Demo-Swift/slds-sample-app/library/extensions/UIView+Constraints.swift
|
1
|
11797
|
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
import Foundation
extension UIView {
enum XAlignmentType {
case left
case center
case right
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
enum YAlignmentType {
case top
case center
case bottom
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
enum DirectionType {
case above
case below
case left
case right
}
// MARK: helpers
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func setX (_ alignment: XAlignmentType) -> NSLayoutAttribute {
switch alignment {
case .left:
return .left
case .right:
return .right
default:
return .centerX
}
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func setY (_ alignment: YAlignmentType) -> NSLayoutAttribute {
switch alignment {
case .top:
return .top
case .center:
return .centerY
default:
return .bottom
}
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
var widthConstraint : NSLayoutConstraint {
for constraint in self.constraints {
if constraint.firstAttribute == .width {
return constraint
}
}
self.constrainSize(width: 0)
return self.widthConstraint
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
var heightConstraint : NSLayoutConstraint {
for constraint in self.constraints {
if constraint.firstAttribute == .height {
return constraint
}
}
self.constrainSize(height: 0)
return self.heightConstraint
}
// MARK - Slim API
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func constrainChild( _ child: UIView, xAlignment: XAlignmentType, yAlignment: YAlignmentType, width: CGFloat?=nil, height: CGFloat?=nil, xOffset: CGFloat?=nil, yOffset: CGFloat?=nil) {
child.translatesAutoresizingMaskIntoConstraints = false
var xOff = xOffset == nil ? 0 : xOffset
var yOff = yOffset == nil ? 0 : yOffset
xOff = xAlignment == .right ? xOff?.negated() : xOff
yOff = yAlignment == .bottom ? yOff?.negated() : yOff
self.addConstraint(NSLayoutConstraint(item: child,
attribute: setX(xAlignment),
relatedBy: .equal,
toItem: self,
attribute: setX(xAlignment),
multiplier: 1.0,
constant: xOff!))
self.addConstraint(NSLayoutConstraint(item: child,
attribute: setY(yAlignment),
relatedBy: .equal,
toItem: self,
attribute: setY(yAlignment),
multiplier: 1.0,
constant: yOff!))
child.constrainSize(width: width, height: height)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func constrainAbove(_ item: UIView, xAlignment: XAlignmentType, width: CGFloat?=nil, height: CGFloat?=nil, xOffset: CGFloat?=nil, yOffset: CGFloat?=nil) {
self.constrainRelation(item,
direction: .above,
xAlignment: xAlignment,
xOffset: xOffset,
yOffset: yOffset)
self.constrainSize(width: width, height: height)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func constrainBelow(_ item: UIView, xAlignment: XAlignmentType, width: CGFloat?=nil, height: CGFloat?=nil, xOffset: CGFloat?=nil, yOffset: CGFloat?=nil) {
self.constrainRelation(item,
direction: .below,
xAlignment: xAlignment,
xOffset: xOffset,
yOffset: yOffset)
self.constrainSize(width: width, height: height)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func constrainRightOf(_ item: UIView, yAlignment: YAlignmentType, width: CGFloat?=nil, height: CGFloat?=nil, xOffset: CGFloat?=nil, yOffset: CGFloat?=nil) {
self.constrainRelation(item,
direction: .right,
yAlignment: yAlignment,
xOffset: xOffset,
yOffset: yOffset)
self.constrainSize(width: width, height: height)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func constrainLeftOf(_ item: UIView, yAlignment: YAlignmentType, width: CGFloat?=nil, height: CGFloat?=nil, xOffset: CGFloat?=nil, yOffset: CGFloat?=nil) {
self.constrainRelation(item,
direction: .left,
yAlignment: yAlignment,
xOffset: xOffset,
yOffset: yOffset)
self.constrainSize(width: width, height: height)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func constrainRelation(_ item: UIView, direction: DirectionType, xAlignment: XAlignmentType?=nil, yAlignment: YAlignmentType?=nil, width: CGFloat?=nil, height: CGFloat?=nil, xOffset: CGFloat?=nil, yOffset: CGFloat?=nil) {
self.translatesAutoresizingMaskIntoConstraints = false
guard let parent = self.superview else {
return
}
var xOff = xOffset == nil ? 0 : xOffset
var yOff = yOffset == nil ? 0 : yOffset
var att1 : NSLayoutAttribute
var att2 : NSLayoutAttribute
var att3 : NSLayoutAttribute
var att4 : NSLayoutAttribute
switch direction {
case .above:
att1 = setX(xAlignment!)
att2 = setX(xAlignment!)
att3 = .bottom
att4 = .top
yOff = yOff?.negated()
case .below :
att1 = setX(xAlignment!)
att2 = setX(xAlignment!)
att3 = .top
att4 = .bottom
case .right :
att1 = .left
att2 = .right
att3 = setY(yAlignment!)
att4 = setY(yAlignment!)
case .left :
att1 = .right
att2 = .left
att3 = setY(yAlignment!)
att4 = setY(yAlignment!)
xOff = xOff?.negated()
}
if yAlignment == .bottom {
yOff = yOff?.negated()
}
parent.addConstraint(NSLayoutConstraint(item: self,
attribute: att1,
relatedBy: .equal,
toItem: item,
attribute: att2,
multiplier: 1.0,
constant: xOff!))
parent.addConstraint(NSLayoutConstraint(item: self,
attribute: att3,
relatedBy: .equal,
toItem: item,
attribute: att4,
multiplier: 1.0,
constant: yOff!))
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func constrainSize( width: CGFloat?=nil, height: CGFloat?=nil ) {
if width != nil {
self.addConstraint(NSLayoutConstraint(item: self,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: width!))
}
if height != nil {
self.addConstraint(NSLayoutConstraint(item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: height!))
}
}
}
|
bsd-3-clause
|
8a2d766a73f476407381374688b5e48b
| 37.612648 | 225 | 0.38571 | 6.709478 | false | false | false | false |
riteshhgupta/RGListKit
|
Pods/ReactiveSwift/Sources/Event.swift
|
3
|
17271
|
import Result
import Foundation
extension Signal {
/// Represents a signal event.
///
/// Signals must conform to the grammar:
/// `value* (failed | completed | interrupted)?`
public enum Event {
/// A value provided by the signal.
case value(Value)
/// The signal terminated because of an error. No further events will be
/// received.
case failed(Error)
/// The signal successfully terminated. No further events will be received.
case completed
/// Event production on the signal has been interrupted. No further events
/// will be received.
///
/// - important: This event does not signify the successful or failed
/// completion of the signal.
case interrupted
/// Whether this event is a completed event.
public var isCompleted: Bool {
switch self {
case .completed:
return true
case .value, .failed, .interrupted:
return false
}
}
/// Whether this event indicates signal termination (i.e., that no further
/// events will be received).
public var isTerminating: Bool {
switch self {
case .value:
return false
case .failed, .completed, .interrupted:
return true
}
}
/// Lift the given closure over the event's value.
///
/// - important: The closure is called only on `value` type events.
///
/// - parameters:
/// - f: A closure that accepts a value and returns a new value
///
/// - returns: An event with function applied to a value in case `self` is a
/// `value` type of event.
public func map<U>(_ f: (Value) -> U) -> Signal<U, Error>.Event {
switch self {
case let .value(value):
return .value(f(value))
case let .failed(error):
return .failed(error)
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Lift the given closure over the event's error.
///
/// - important: The closure is called only on failed type event.
///
/// - parameters:
/// - f: A closure that accepts an error object and returns
/// a new error object
///
/// - returns: An event with function applied to an error object in case
/// `self` is a `.Failed` type of event.
public func mapError<F>(_ f: (Error) -> F) -> Signal<Value, F>.Event {
switch self {
case let .value(value):
return .value(value)
case let .failed(error):
return .failed(f(error))
case .completed:
return .completed
case .interrupted:
return .interrupted
}
}
/// Unwrap the contained `value` value.
public var value: Value? {
if case let .value(value) = self {
return value
} else {
return nil
}
}
/// Unwrap the contained `Error` value.
public var error: Error? {
if case let .failed(error) = self {
return error
} else {
return nil
}
}
}
}
extension Signal.Event where Value: Equatable, Error: Equatable {
public static func == (lhs: Signal<Value, Error>.Event, rhs: Signal<Value, Error>.Event) -> Bool {
switch (lhs, rhs) {
case let (.value(left), .value(right)):
return left == right
case let (.failed(left), .failed(right)):
return left == right
case (.completed, .completed):
return true
case (.interrupted, .interrupted):
return true
default:
return false
}
}
}
extension Signal.Event: CustomStringConvertible {
public var description: String {
switch self {
case let .value(value):
return "VALUE \(value)"
case let .failed(error):
return "FAILED \(error)"
case .completed:
return "COMPLETED"
case .interrupted:
return "INTERRUPTED"
}
}
}
/// Event protocol for constraining signal extensions
public protocol EventProtocol {
/// The value type of an event.
associatedtype Value
/// The error type of an event. If errors aren't possible then `NoError` can
/// be used.
associatedtype Error: Swift.Error
/// Extracts the event from the receiver.
var event: Signal<Value, Error>.Event { get }
}
extension Signal.Event: EventProtocol {
public var event: Signal<Value, Error>.Event {
return self
}
}
extension Signal.Event {
internal typealias Transformation<U, E: Swift.Error> = (@escaping Signal<U, E>.Observer.Action) -> (Signal<Value, Error>.Event) -> Void
internal static func filter(_ isIncluded: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action in
return { event in
switch event {
case let .value(value):
if isIncluded(value) {
action(.value(value))
}
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func filterMap<U>(_ transform: @escaping (Value) -> U?) -> Transformation<U, Error> {
return { action in
return { event in
switch event {
case let .value(value):
if let newValue = transform(value) {
action(.value(newValue))
}
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func map<U>(_ transform: @escaping (Value) -> U) -> Transformation<U, Error> {
return { action in
return { event in
switch event {
case let .value(value):
action(.value(transform(value)))
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func mapError<E>(_ transform: @escaping (Error) -> E) -> Transformation<Value, E> {
return { action in
return { event in
switch event {
case let .value(value):
action(.value(value))
case .completed:
action(.completed)
case let .failed(error):
action(.failed(transform(error)))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static var materialize: Transformation<Signal<Value, Error>.Event, NoError> {
return { action in
return { event in
action(.value(event))
switch event {
case .interrupted:
action(.interrupted)
case .completed, .failed:
action(.completed)
case .value:
break
}
}
}
}
internal static func attemptMap<U>(_ transform: @escaping (Value) -> Result<U, Error>) -> Transformation<U, Error> {
return { action in
return { event in
switch event {
case let .value(value):
switch transform(value) {
case let .success(value):
action(.value(value))
case let .failure(error):
action(.failed(error))
}
case let .failed(error):
action(.failed(error))
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func attempt(_ action: @escaping (Value) -> Result<(), Error>) -> Transformation<Value, Error> {
return attemptMap { value -> Result<Value, Error> in
return action(value).map { _ in value }
}
}
}
extension Signal.Event where Error == AnyError {
internal static func attempt(_ action: @escaping (Value) throws -> Void) -> Transformation<Value, AnyError> {
return attemptMap { value in
try action(value)
return value
}
}
internal static func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> Transformation<U, AnyError> {
return attemptMap { value in
ReactiveSwift.materialize { try transform(value) }
}
}
}
extension Signal.Event {
internal static func take(first count: Int) -> Transformation<Value, Error> {
assert(count >= 1)
return { action in
var taken = 0
return { event in
guard let value = event.value else {
action(event)
return
}
if taken < count {
taken += 1
action(.value(value))
}
if taken == count {
action(.completed)
}
}
}
}
internal static func take(last count: Int) -> Transformation<Value, Error> {
return { action in
var buffer: [Value] = []
buffer.reserveCapacity(count)
return { event in
switch event {
case let .value(value):
// To avoid exceeding the reserved capacity of the buffer,
// we remove then add. Remove elements until we have room to
// add one more.
while (buffer.count + 1) > count {
buffer.remove(at: 0)
}
buffer.append(value)
case let .failed(error):
action(.failed(error))
case .completed:
buffer.forEach { action(.value($0)) }
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func take(while shouldContinue: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action in
return { event in
if let value = event.value, !shouldContinue(value) {
action(.completed)
} else {
action(event)
}
}
}
}
internal static func skip(first count: Int) -> Transformation<Value, Error> {
precondition(count > 0)
return { action in
var skipped = 0
return { event in
if case .value = event, skipped < count {
skipped += 1
} else {
action(event)
}
}
}
}
internal static func skip(while shouldContinue: @escaping (Value) -> Bool) -> Transformation<Value, Error> {
return { action in
var isSkipping = true
return { event in
switch event {
case let .value(value):
isSkipping = isSkipping && shouldContinue(value)
if !isSkipping {
fallthrough
}
case .failed, .completed, .interrupted:
action(event)
}
}
}
}
}
extension Signal.Event where Value: EventProtocol {
internal static var dematerialize: Transformation<Value.Value, Value.Error> {
return { action in
return { event in
switch event {
case let .value(innerEvent):
action(innerEvent.event)
case .failed:
fatalError("NoError is impossible to construct")
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
extension Signal.Event where Value: OptionalProtocol {
internal static var skipNil: Transformation<Value.Wrapped, Error> {
return filterMap { $0.optional }
}
}
/// A reference type which wraps an array to auxiliate the collection of values
/// for `collect` operator.
private final class CollectState<Value> {
var values: [Value] = []
/// Collects a new value.
func append(_ value: Value) {
values.append(value)
}
/// Check if there are any items remaining.
///
/// - note: This method also checks if there weren't collected any values
/// and, in that case, it means an empty array should be sent as the
/// result of collect.
var isEmpty: Bool {
/// We use capacity being zero to determine if we haven't collected any
/// value since we're keeping the capacity of the array to avoid
/// unnecessary and expensive allocations). This also guarantees
/// retro-compatibility around the original `collect()` operator.
return values.isEmpty && values.capacity > 0
}
/// Removes all values previously collected if any.
func flush() {
// Minor optimization to avoid consecutive allocations. Can
// be useful for sequences of regular or similar size and to
// track if any value was ever collected.
values.removeAll(keepingCapacity: true)
}
}
extension Signal.Event {
internal static var collect: Transformation<[Value], Error> {
return collect { _, _ in false }
}
internal static func collect(count: Int) -> Transformation<[Value], Error> {
precondition(count > 0)
return collect { values in values.count == count }
}
internal static func collect(_ shouldEmit: @escaping (_ collectedValues: [Value]) -> Bool) -> Transformation<[Value], Error> {
return { action in
let state = CollectState<Value>()
return { event in
switch event {
case let .value(value):
state.append(value)
if shouldEmit(state.values) {
action(.value(state.values))
state.flush()
}
case .completed:
if !state.isEmpty {
action(.value(state.values))
}
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> Transformation<[Value], Error> {
return { action in
let state = CollectState<Value>()
return { event in
switch event {
case let .value(value):
if shouldEmit(state.values, value) {
action(.value(state.values))
state.flush()
}
state.append(value)
case .completed:
if !state.isEmpty {
action(.value(state.values))
}
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
/// Implementation detail of `combinePrevious`. A default argument of a `nil` initial
/// is deliberately avoided, since in the case of `Value` being an optional, the
/// `nil` literal would be materialized as `Optional<Value>.none` instead of `Value`,
/// thus changing the semantic.
internal static func combinePrevious(initial: Value?) -> Transformation<(Value, Value), Error> {
return { action in
var previous = initial
return { event in
switch event {
case let .value(value):
if let previous = previous {
action(.value((previous, value)))
}
previous = value
case .completed:
action(.completed)
case let .failed(error):
action(.failed(error))
case .interrupted:
action(.interrupted)
}
}
}
}
internal static func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> Transformation<Value, Error> {
return { action in
var previous: Value?
return { event in
switch event {
case let .value(value):
if let previous = previous, isEquivalent(previous, value) {
return
}
previous = value
fallthrough
case .completed, .interrupted, .failed:
action(event)
}
}
}
}
internal static func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Transformation<Value, Error> {
return { action in
var seenValues: Set<Identity> = []
return { event in
switch event {
case let .value(value):
let identity = transform(value)
let (inserted, _) = seenValues.insert(identity)
if inserted {
fallthrough
}
case .failed, .completed, .interrupted:
action(event)
}
}
}
}
internal static func scan<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Transformation<U, Error> {
return { action in
var accumulator = initialResult
return { event in
action(event.map { value in
nextPartialResult(&accumulator, value)
return accumulator
})
}
}
}
internal static func scan<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Transformation<U, Error> {
return scan(into: initialResult) { $0 = nextPartialResult($0, $1) }
}
internal static func reduce<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> Transformation<U, Error> {
return { action in
var accumulator = initialResult
return { event in
switch event {
case let .value(value):
nextPartialResult(&accumulator, value)
case .completed:
action(.value(accumulator))
action(.completed)
case .interrupted:
action(.interrupted)
case let .failed(error):
action(.failed(error))
}
}
}
}
internal static func reduce<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> Transformation<U, Error> {
return reduce(into: initialResult) { $0 = nextPartialResult($0, $1) }
}
internal static func observe(on scheduler: Scheduler) -> Transformation<Value, Error> {
return { action in
return { event in
scheduler.schedule {
action(event)
}
}
}
}
internal static func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> Transformation<Value, Error> {
precondition(interval >= 0)
return { action in
return { event in
switch event {
case .failed, .interrupted:
scheduler.schedule {
action(event)
}
case .value, .completed:
let date = scheduler.currentDate.addingTimeInterval(interval)
scheduler.schedule(after: date) {
action(event)
}
}
}
}
}
}
extension Signal.Event where Error == NoError {
internal static func promoteError<F>(_: F.Type) -> Transformation<Value, F> {
return { action in
return { event in
switch event {
case let .value(value):
action(.value(value))
case .failed:
fatalError("NoError is impossible to construct")
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
extension Signal.Event where Value == Never {
internal static func promoteValue<U>(_: U.Type) -> Transformation<U, Error> {
return { action in
return { event in
switch event {
case .value:
fatalError("Never is impossible to construct")
case let .failed(error):
action(.failed(error))
case .completed:
action(.completed)
case .interrupted:
action(.interrupted)
}
}
}
}
}
|
mit
|
c0b64b3b424289d54baa5f00575de449
| 22.854972 | 141 | 0.642001 | 3.564706 | false | false | false | false |
MatthiasU/TimeKeeper
|
TimeKeeper/View/TimeKeeperMenu.swift
|
1
|
2235
|
//
// TimeKeeperMenu.swift
// TimeKeeper
//
// Created by Matthias Uttendorfer on 11/06/16.
// Copyright © 2016 Matthias Uttendorfer. All rights reserved.
//
import Cocoa
class TimeKeeperMenu: NSMenu {
var timePicker:StartTimePicker?
var timeMenuDelegate: TimeKeeperMenuDelegate?
override init(title aTitle: String) {
super.init(title: aTitle)
setupMenuItems()
}
convenience init() {
self.init(title: "")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setupMenuItems() {
// Add Menu Item for Quiting
let quitMenuItem = NSMenuItem()
quitMenuItem.title = "Quit"
quitMenuItem.target = self
quitMenuItem.action = #selector(quit)
quitMenuItem.keyEquivalent = "Q"
self.addItem(quitMenuItem)
let startTimeItem = NSMenuItem()
startTimeItem.title = "Start Time"
startTimeItem.target = self
startTimeItem.action = #selector(openConfigureMenu)
startTimeItem.keyEquivalent = "C"
self.addItem(startTimeItem)
}
// MARK: Selector Calls
func quit() {
NSApplication.shared().terminate(self)
}
func openConfigureMenu() {
let alert = NSAlert();
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
Bundle.main.loadNibNamed("StartTimePicker", owner: self, topLevelObjects: nil)
alert.accessoryView = timePicker
alert.alertStyle = .informational
let result = alert.runModal()
if result == NSAlertFirstButtonReturn {
// ok was pressed
guard let hour = timePicker?.hourValue.stringValue else {
return;
}
guard let minute = timePicker?.minuteValue.stringValue else {
return;
}
guard let hourAsInt = Int(hour) else {
return
}
guard let minuteAsInt = Int(minute) else {
return
}
let newTime = Time(hours: hourAsInt, minutes: minuteAsInt)
if let aDelegate = timeMenuDelegate {
aDelegate.timeKeeperMenuDidChangeStartTime(self, newTime: newTime)
}
}
}
}
protocol TimeKeeperMenuDelegate {
func timeKeeperMenuDidChangeStartTime(_ menu: TimeKeeperMenu, newTime: Time)
}
|
gpl-3.0
|
dc7592f9c2dd0e0eec366a1a6b1a8527
| 22.515789 | 82 | 0.65846 | 4.397638 | false | false | false | false |
bumpersfm/handy
|
Handy/UILabel.swift
|
1
|
1712
|
//
// UILabel.swift
// Pods
//
// Created by Dani Postigo on 8/31/16.
//
//
import Foundation
import UIKit
extension UILabel {
public convenience init(font: UIFont, color: UIColor = UIColor.blackColor()) {
self.init(); self.font = font; self.textColor = color
}
public convenience init(color: UIColor) {
self.init(); self.textColor = color
}
public convenience init(text: String) { self.init(title: text) }
public convenience init(title: String, font: UIFont? = nil, color: UIColor? = nil) {
self.init()
self.text = title
self.font = font
self.textColor = color
}
public convenience init(attributedText: NSAttributedString) {
self.init(); self.attributedText = attributedText
}
public convenience init(title: String, attributes: [String:AnyObject]) {
self.init(attributedText: NSAttributedString(string: title, attributes: attributes))
}
public convenience init(attributes: [String:AnyObject]) {
self.init(attributedText: NSAttributedString(string: " ", attributes: attributes))
}
public func set(attributedString string: String) {
if let attributedText = self.attributedText {
self.attributedText = NSAttributedString(string: string, attributes: attributedText.attributesAtIndex(0, longestEffectiveRange: nil, inRange: NSMakeRange(0, attributedText.length)))
}
}
public var attributedString: String? {
get {
return self.attributedText?.string
}
set {
if let newValue = newValue {
self.set(attributedString: newValue)
}
}
}
}
|
mit
|
20d4b998c45d2abf789ab433af452539
| 29.035088 | 193 | 0.633762 | 4.690411 | false | false | false | false |
natecook1000/swift
|
stdlib/public/core/AssertCommon.swift
|
1
|
8527
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Implementation Note: this file intentionally uses very LOW-LEVEL
// CONSTRUCTS, so that assert and fatal may be used liberally in
// building library abstractions without fear of infinite recursion.
//
// FIXME: We could go farther with this simplification, e.g. avoiding
// UnsafeMutablePointer
@_transparent
public // @testable
func _isDebugAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 0
}
@usableFromInline @_transparent
internal func _isReleaseAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 1
}
@_transparent
public // @testable
func _isFastAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 2
}
@_transparent
public // @testable
func _isStdlibInternalChecksEnabled() -> Bool {
#if INTERNAL_CHECKS_ENABLED
return true
#else
return false
#endif
}
@usableFromInline @_transparent
internal
func _fatalErrorFlags() -> UInt32 {
// The current flags are:
// (1 << 0): Report backtrace on fatal error
#if os(iOS) || os(tvOS) || os(watchOS)
return 0
#else
return _isDebugAssertConfiguration() ? 1 : 0
#endif
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@usableFromInline
@inline(never)
internal func _assertionFailure(
_ prefix: StaticString, _ message: StaticString,
file: StaticString, line: UInt,
flags: UInt32
) -> Never {
prefix.withUTF8Buffer {
(prefix) -> Void in
message.withUTF8Buffer {
(message) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_swift_stdlib_reportFatalErrorInFile(
prefix.baseAddress!, CInt(prefix.count),
message.baseAddress!, CInt(message.count),
file.baseAddress!, CInt(file.count), UInt32(line),
flags)
Builtin.int_trap()
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@usableFromInline
@inline(never)
internal func _assertionFailure(
_ prefix: StaticString, _ message: String,
file: StaticString, line: UInt,
flags: UInt32
) -> Never {
prefix.withUTF8Buffer {
(prefix) -> Void in
message._withUnsafeBufferPointerToUTF8 {
(messageUTF8) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_swift_stdlib_reportFatalErrorInFile(
prefix.baseAddress!, CInt(prefix.count),
messageUTF8.baseAddress!, CInt(messageUTF8.count),
file.baseAddress!, CInt(file.count), UInt32(line),
flags)
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@usableFromInline
@inline(never)
internal func _assertionFailure(
_ prefix: StaticString, _ message: String,
flags: UInt32
) -> Never {
prefix.withUTF8Buffer {
(prefix) -> Void in
message._withUnsafeBufferPointerToUTF8 {
(messageUTF8) -> Void in
_swift_stdlib_reportFatalError(
prefix.baseAddress!, CInt(prefix.count),
messageUTF8.baseAddress!, CInt(messageUTF8.count),
flags)
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of stdlib
/// assertions.
///
/// This function should not be inlined because it is cold and it inlining just
/// bloats code.
@usableFromInline
@inline(never)
@_semantics("arc.programtermination_point")
internal func _fatalErrorMessage(
_ prefix: StaticString, _ message: StaticString,
file: StaticString, line: UInt,
flags: UInt32
) -> Never {
#if INTERNAL_CHECKS_ENABLED
prefix.withUTF8Buffer {
(prefix) in
message.withUTF8Buffer {
(message) in
file.withUTF8Buffer {
(file) in
_swift_stdlib_reportFatalErrorInFile(
prefix.baseAddress!, CInt(prefix.count),
message.baseAddress!, CInt(message.count),
file.baseAddress!, CInt(file.count), UInt32(line),
flags)
}
}
}
#else
prefix.withUTF8Buffer {
(prefix) in
message.withUTF8Buffer {
(message) in
_swift_stdlib_reportFatalError(
prefix.baseAddress!, CInt(prefix.count),
message.baseAddress!, CInt(message.count),
flags)
}
}
#endif
Builtin.int_trap()
}
/// Prints a fatal error message when an unimplemented initializer gets
/// called by the Objective-C runtime.
@_transparent
public // COMPILER_INTRINSIC
func _unimplementedInitializer(className: StaticString,
initName: StaticString = #function,
file: StaticString = #file,
line: UInt = #line,
column: UInt = #column
) -> Never {
// This function is marked @_transparent so that it is inlined into the caller
// (the initializer stub), and, depending on the build configuration,
// redundant parameter values (#file etc.) are eliminated, and don't leak
// information about the user's source.
if _isDebugAssertConfiguration() {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
file.withUTF8Buffer {
(file) in
_swift_stdlib_reportUnimplementedInitializerInFile(
className.baseAddress!, CInt(className.count),
initName.baseAddress!, CInt(initName.count),
file.baseAddress!, CInt(file.count),
UInt32(line), UInt32(column),
/*flags:*/ 0)
}
}
}
} else {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
_swift_stdlib_reportUnimplementedInitializer(
className.baseAddress!, CInt(className.count),
initName.baseAddress!, CInt(initName.count),
/*flags:*/ 0)
}
}
}
Builtin.int_trap()
}
@inlinable // FIXME(sil-serialize-all)
public // COMPILER_INTRINSIC
func _undefined<T>(
_ message: @autoclosure () -> String = String(),
file: StaticString = #file, line: UInt = #line
) -> T {
_assertionFailure("Fatal error", message(), file: file, line: line, flags: 0)
}
/// Called when falling off the end of a switch and the type can be represented
/// as a raw value.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code. It doesn't take a source location because it's most important
/// in release builds anyway (old apps that are run on new OSs).
@inline(never)
@usableFromInline // COMPILER_INTRINSIC
internal func _diagnoseUnexpectedEnumCaseValue<SwitchedValue, RawValue>(
type: SwitchedValue.Type,
rawValue: RawValue
) -> Never {
_assertionFailure("Fatal error",
"unexpected enum case '\(type)(rawValue: \(rawValue))'",
flags: _fatalErrorFlags())
}
/// Called when falling off the end of a switch and the value is not safe to
/// print.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code. It doesn't take a source location because it's most important
/// in release builds anyway (old apps that are run on new OSs).
@inline(never)
@usableFromInline // COMPILER_INTRINSIC
internal func _diagnoseUnexpectedEnumCase<SwitchedValue>(
type: SwitchedValue.Type
) -> Never {
_assertionFailure(
"Fatal error",
"unexpected enum case while switching on value of type '\(type)'",
flags: _fatalErrorFlags())
}
|
apache-2.0
|
4b0a7c3b5009183fcd75eca2dccdd6f3
| 28.403448 | 80 | 0.655917 | 4.317468 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/ViewRelated/Gutenberg/Processors/GutenbergFileUploadProcessor.swift
|
2
|
1928
|
import Foundation
import Aztec
class GutenbergFileUploadProcessor: Processor {
private struct FileBlockKeys {
static var name = "wp:file"
static var id = "id"
static var href = "href"
}
let mediaUploadID: Int32
let remoteURLString: String
let serverMediaID: Int
init(mediaUploadID: Int32, serverMediaID: Int, remoteURLString: String) {
self.mediaUploadID = mediaUploadID
self.serverMediaID = serverMediaID
self.remoteURLString = remoteURLString
}
lazy var fileHtmlProcessor = HTMLProcessor(for: "a", replacer: { (file) in
var attributes = file.attributes
attributes.set(.string(self.remoteURLString), forKey: FileBlockKeys.href)
var html = "<a "
let attributeSerializer = ShortcodeAttributeSerializer()
html += attributeSerializer.serialize(attributes)
html += ">\(file.content ?? "")</a>"
return html
})
lazy var fileBlockProcessor = GutenbergBlockProcessor(for: FileBlockKeys.name, replacer: { fileBlock in
guard let mediaID = fileBlock.attributes[FileBlockKeys.id] as? Int,
mediaID == self.mediaUploadID else {
return nil
}
var block = "<!-- \(FileBlockKeys.name) "
var attributes = fileBlock.attributes
attributes[FileBlockKeys.id] = self.serverMediaID
attributes[FileBlockKeys.href] = self.remoteURLString
if let jsonData = try? JSONSerialization.data(withJSONObject: attributes, options: .sortedKeys),
let jsonString = String(data: jsonData, encoding: .utf8) {
block += jsonString
}
block += " -->"
block += self.fileHtmlProcessor.process(fileBlock.content)
block += "<!-- /\(FileBlockKeys.name) -->"
return block
})
func process(_ text: String) -> String {
return fileBlockProcessor.process(text)
}
}
|
gpl-2.0
|
1760f3c432a542170548d8b7b0784854
| 34.054545 | 107 | 0.642116 | 4.525822 | false | false | false | false |
wess/reddift
|
reddiftSample/CommentViewController.swift
|
1
|
9235
|
//
// CommentViewController.swift
// reddift
//
// Created by sonson on 2015/04/17.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class CommentViewController: UITableViewController, UZTextViewCellDelegate {
var session:Session? = nil
var subreddit:Subreddit? = nil
var link:Link? = nil
var comments:[Thing] = []
var paginator:Paginator? = Paginator()
var contents:[CellContent] = []
deinit{
println("deinit")
}
func updateStrings(newComments:[Thing]) -> [CellContent] {
return newComments.map { (thing:Thing) -> CellContent in
if let comment = thing as? Comment {
return CellContent(string:comment.body, width:self.view.frame.size.width, hasRelies:false)
}
else {
return CellContent(string:"more", width:self.view.frame.size.width, hasRelies:false)
}
}
}
func vote(direction:VoteDirection) {
if let link = self.link {
session?.setVote(direction, name: link.name, completion: { (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
}
})
}
}
func save(save:Bool) {
if let link = self.link {
session?.setSave(save, name: link.name, completion: { (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
}
})
}
}
func hide(hide:Bool) {
if let link = self.link {
session?.setHide(hide, name: link.name, completion: { (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
}
})
}
}
func downVote(sender:AnyObject?) {
vote(.Down)
}
func upVote(sender:AnyObject?) {
vote(.Up)
}
func cancelVote(sender:AnyObject?) {
vote(.No)
}
func doSave(sender:AnyObject?) {
save(true)
}
func doUnsave(sender:AnyObject?) {
save(false)
}
func doHide(sender:AnyObject?) {
hide(true)
}
func doUnhide(sender:AnyObject?) {
hide(false)
}
func updateToolbar() {
var items:[UIBarButtonItem] = []
let space = UIBarButtonItem(barButtonSystemItem:.FlexibleSpace, target: nil, action: nil)
if let link = self.link {
items.append(space)
// voting status
if let likes = link.likes {
if likes {
items.append(UIBarButtonItem(image: UIImage(named: "thumbDown"), style:.Plain, target: self, action: "downVote:"))
items.append(space)
items.append(UIBarButtonItem(image: UIImage(named: "thumbUpFill"), style:.Plain, target: self, action: "cancelVote:"))
}
else {
items.append(UIBarButtonItem(image: UIImage(named: "thumbDownFill"), style:.Plain, target: self, action: "cancelVote:"))
items.append(space)
items.append(UIBarButtonItem(image: UIImage(named: "thumbUp"), style:.Plain, target: self, action: "upVote:"))
}
}
else {
items.append(UIBarButtonItem(image: UIImage(named: "thumbDown"), style:.Plain, target: self, action: "downVote:"))
items.append(space)
items.append(UIBarButtonItem(image: UIImage(named: "thumbUp"), style:.Plain, target: self, action: "upVote:"))
}
items.append(space)
// save
if link.saved {
items.append(UIBarButtonItem(image: UIImage(named: "favoriteFill"), style:.Plain, target: self, action:"doUnsave:"))
}
else {
items.append(UIBarButtonItem(image: UIImage(named: "favorite"), style:.Plain, target: self, action:"doSave:"))
}
items.append(space)
// hide
if link.hidden {
items.append(UIBarButtonItem(image: UIImage(named: "eyeFill"), style:.Plain, target: self, action: "doUnhide:"))
}
else {
items.append(UIBarButtonItem(image: UIImage(named: "eye"), style:.Plain, target: self, action: "doHide:"))
}
items.append(space)
// comment button
items.append(UIBarButtonItem(image: UIImage(named: "comment"), style:.Plain, target: nil, action: nil))
items.append(space)
}
self.toolbarItems = items
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "UZTextViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
self.tableView.registerNib(UINib(nibName: "UZTextViewWithMoreButtonCell", bundle: nil), forCellReuseIdentifier: "MoreCell")
updateToolbar()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.toolbarHidden = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let link = self.link {
session?.getArticles(link, sort:CommentSort.New, comments:nil, completion: { (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
if let redditAnyArray = result.value as? [RedditAny] {
if indices(redditAnyArray) ~= 0 {
let _ = redditAnyArray[0]
}
if indices(redditAnyArray) ~= 1 {
if let listing = redditAnyArray[1] as? Listing {
println(listing)
var newComments:[Thing] = []
for obj in listing.children {
if let comment = obj as? Comment {
newComments += extendAllReplies(comment)
}
}
self.comments += newComments
self.contents += self.updateStrings(newComments)
self.paginator = listing.paginator
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
});
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contents.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indices(contents) ~= indexPath.row {
return contents[indexPath.row].textHeight
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell! = nil
if indices(contents) ~= indexPath.row {
cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
if let cell = cell as? UZTextViewCell {
cell.delegate = self
cell.textView?.attributedString = contents[indexPath.row].attributedString
cell.content = comments[indexPath.row]
}
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indices(comments) ~= indexPath.row {
if let more = comments[indexPath.row] as? More, link = self.link {
println(more)
session?.getMoreChildren(more.children, link:link, sort:CommentSort.New, completion:{ (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
println(result.value)
}
});
}
}
}
func pushedMoreButton(cell:UZTextViewCell) {
}
}
|
mit
|
9b43bc6453e19d51a6b564370a37988b
| 35.350394 | 140 | 0.522582 | 5.078658 | false | false | false | false |
xxxAIRINxxx/Cmg
|
Sources/GeometryAdjustment.swift
|
1
|
6025
|
//
// GeometryAdjustment.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public struct AffineTransform: Filterable, FilterInputCollectionType,
InputAffineTransformAvailable {
public let filter: CIFilter = CIFilter(name: "CIAffineTransform")!
public var inputTransform: AffineTransformInput
public init() {
self.inputTransform = AffineTransformInput()
}
public func inputs() -> [FilterInputable] {
return [
self.inputTransform
]
}
}
public struct Crop: Filterable, FilterInputCollectionType,
InputRectangleAvailable {
public let filter: CIFilter = CIFilter(name: "CICrop")!
public let inputRectangle: VectorInput
public init(imageSize: CGSize) {
self.inputRectangle = VectorInput(.extent(extent: Vector4(size: imageSize)), self.filter, "inputRectangle")
}
public func inputs() -> [FilterInputable] {
return [
self.inputRectangle
]
}
}
public struct LanczosScaleTransform: Filterable, FilterInputCollectionType,
InputScaleAvailable, InputAspectRatioAvailable {
public let filter: CIFilter = CIFilter(name: "CILanczosScaleTransform")!
public let inputScale: ScalarInput
public let inputAspectRatio: ScalarInput
public init() {
self.inputScale = ScalarInput(filter: self.filter, key: kCIInputScaleKey)
self.inputAspectRatio = ScalarInput(filter: self.filter, key: kCIInputAspectRatioKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputScale,
self.inputAspectRatio
]
}
}
public struct PerspectiveCorrection: Filterable, FilterInputCollectionType,
InputTopLeftAvailable, InputTopRightAvailable, InputBottomRightAvailable,
InputBottomLeftAvailable {
public let filter: CIFilter = CIFilter(name: "CIPerspectiveCorrection")!
public let inputTopLeft: VectorInput
public let inputTopRight: VectorInput
public let inputBottomLeft: VectorInput
public let inputBottomRight: VectorInput
public init(imageSize: CGSize) {
self.inputTopLeft = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputTopLeft")
self.inputTopRight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputTopRight")
self.inputBottomLeft = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputBottomLeft")
self.inputBottomRight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputBottomRight")
}
public func inputs() -> [FilterInputable] {
return [
self.inputTopLeft,
self.inputTopRight,
self.inputBottomLeft,
self.inputBottomRight
]
}
}
public struct PerspectiveTransform: Filterable, FilterInputCollectionType,
InputTopLeftAvailable, InputTopRightAvailable, InputBottomRightAvailable,
InputBottomLeftAvailable {
public let filter: CIFilter = CIFilter(name: "CIPerspectiveTransform")!
public let inputTopLeft: VectorInput
public let inputTopRight: VectorInput
public let inputBottomLeft: VectorInput
public let inputBottomRight: VectorInput
public init(imageSize: CGSize) {
self.inputTopLeft = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputTopLeft")
self.inputTopRight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputTopRight")
self.inputBottomLeft = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputBottomLeft")
self.inputBottomRight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputBottomRight")
}
public func inputs() -> [FilterInputable] {
return [
self.inputTopLeft,
self.inputTopRight,
self.inputBottomLeft,
self.inputBottomRight
]
}
}
public struct PerspectiveTransformWithExtent: Filterable, FilterInputCollectionType,
InputExtentAvailable, InputTopLeftAvailable, InputTopRightAvailable,
InputBottomRightAvailable, InputBottomLeftAvailable {
public let filter: CIFilter = CIFilter(name: "CIPerspectiveTransformWithExtent")!
public let inputExtent: VectorInput
public let inputTopLeft: VectorInput
public let inputTopRight: VectorInput
public let inputBottomLeft: VectorInput
public let inputBottomRight: VectorInput
public init(imageSize: CGSize) {
self.inputExtent = VectorInput(.extent(extent: Vector4(size: imageSize)), self.filter, kCIInputExtentKey)
self.inputTopLeft = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputTopLeft")
self.inputTopRight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputTopRight")
self.inputBottomLeft = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputBottomLeft")
self.inputBottomRight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputBottomRight")
}
public func inputs() -> [FilterInputable] {
return [
self.inputExtent,
self.inputTopLeft,
self.inputTopRight,
self.inputBottomLeft,
self.inputBottomRight
]
}
}
public struct StraightenFilter: Filterable, FilterInputCollectionType,
InputAngleAvailable {
public let filter: CIFilter = CIFilter(name: "CIStraightenFilter")!
public let inputAngle: ScalarInput
public init() {
self.inputAngle = ScalarInput(filter: self.filter, key: kCIInputAngleKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputAngle
]
}
}
|
mit
|
dd1b274246a5e5d44df6df89cfe1ef25
| 33.820809 | 126 | 0.699203 | 4.978512 | false | false | false | false |
mlibai/XZKit
|
Projects/XZKit/XZKitTests/XZKitConstantsSwiftTests.swift
|
1
|
1995
|
//
// XZKitConstantsSwiftTests.swift
// XZKitTests
//
// Created by 徐臻 on 2020/1/30.
// Copyright © 2020 Xezun Inc. All rights reserved.
//
import XCTest
import XZKit
class XZKitConstantsSwiftTests: XCTestCase {
override func setUp() {
XZLog("isDebugMode: %@", isDebugMode);
}
override func tearDown() {
}
func testConstants() {
// 当前时间戳。
XZLog("%@", TimeInterval.since1970);
// OptionSet.none
let state: UIControl.State = [];
XZLog("%@", state);
}
func testString() {
let string1 = String.init(formats: "%@ %02ld %.2f", "对象", 2, CGFloat.pi);
let string2 = String.init(formats: "%@ %@ %@", "对象", 2, CGFloat.pi);
XZLog("string1: \(string1), \nstring2: \(string2)")
XZLog("cast NSNull to string: %@", String(casting: NSNull()))
XZLog("cast object to string: %@", String(casting: self))
XZLog("cast option to string: %@", self.accessibilityAttributedLabel)
NSLog("----%@", self);
XZLog("%@", String(isolating: "We are Super Man.", direction: .leftToRight));
XZLog("%@", String(isolating: "We are Super Man.", direction: .rightToLeft));
XZLog("%@", String(isolating: "We are Super Man.", direction: .firstStrong));
XZLog("%@", " 234f \n".trimmingCharacters(in: " \t\n"))
XZLog("%@", "我是中国人".transformingMandarinToLatin);
XZLog("%@", "https://www.baidu.com/?keyword=中国#2".addingURIEncoding)
XZLog("%@", "https://www.baidu.com/?keyword=中国#2".addingURIComponentEncoding)
XZLog("%@", """
第一行:ABC
第二行:EDF
""")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
mit
|
8e1d8886d81c3a33cf3295194901f5a7
| 27.895522 | 85 | 0.545971 | 4.181425 | false | true | false | false |
kaich/CKAlertView
|
CKAlertView/Classes/Core/CKAlertViewInteractiveHandler.swift
|
1
|
3344
|
//
// CKAlertViewInteractiveAnimator.swift
// Pods
//
// Created by mac on 17/3/1.
//
//
import UIKit
import AudioToolbox
public protocol CKAlertViewInteractive {
init(alertView :CKAlertView?)
var alertView :CKAlertView? {get}
func setupAfterLoaded()
}
//吸附
class CKAlertViewAttachmentInteractiveHandler: CKAlertViewInteractive {
public var alertView :CKAlertView?
fileprivate var containerView: UIView! {
return self.alertView?.containerView
}
fileprivate var view: UIView! {
return self.alertView?.view
}
fileprivate lazy var interactiveAnimator: UIDynamicAnimator = UIDynamicAnimator(referenceView: self.view)
fileprivate var attachmentBehavior: UIAttachmentBehavior!
var finalPosition = CGPoint.zero
required public init(alertView: CKAlertView?) {
self.alertView = alertView
}
public func setupAfterLoaded() {
alertView?.forceGestureBlock = { (gesutre) in
self.handleAttachmentGesture(gesutre)
}
}
var locationPoint :CGPoint = CGPoint.zero
@IBAction func handleAttachmentGesture(_ sender: UIGestureRecognizer) {
if #available(iOS 9.0, *) {
if let forceGesture = sender as? CKForceGestureRecognizer {
let location = sender.location(in: view)
let boxLocation = sender.location(in: containerView)
switch sender.state {
case .began:
interactiveAnimator.removeAllBehaviors()
let centerOffset = UIOffset(horizontal: boxLocation.x - containerView.bounds.midX, vertical: boxLocation.y - containerView.bounds.midY)
attachmentBehavior = UIAttachmentBehavior(item: containerView, offsetFromCenter: centerOffset, attachedToAnchor: location)
interactiveAnimator.addBehavior(attachmentBehavior)
case .ended:
interactiveAnimator.removeAllBehaviors()
if forceGesture.isForceEnd {
AudioServicesPlaySystemSound(1520)
stickState()
}
else {
resetState()
}
default:
attachmentBehavior.anchorPoint = location
finalPosition = containerView.center
break
}
}
}
}
func resetState() {
interactiveAnimator.removeAllBehaviors()
UIView.animate(withDuration: 0.45, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.containerView.center = self.view.center
self.containerView.transform = CGAffineTransform.identity
}) { (_) in
}
}
func stickState() {
interactiveAnimator.removeAllBehaviors()
UIView.animate(withDuration: 0.45, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.containerView.center = self.finalPosition
}) { (_) in
}
}
}
|
mit
|
4003b5b33a0805d43977070f8cf016e4
| 30.809524 | 155 | 0.584431 | 5.728988 | false | false | false | false |
gtrabanco/JSQDataSourcesKit
|
JSQDataSourcesKit/JSQDataSourcesKit/FetchedResultsDelegate.swift
|
2
|
11969
|
//
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright (c) 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import UIKit
import CoreData
/// A `CollectionViewFetchedResultsDelegateProvider` is responsible for providing a delegate object
/// for an instance of `NSFetchedResultsController` that manages data to display in a collection view.
/// <br/><br/>
/// **The delegate provider has the following type parameters:**
/// <br/>
/// ````
/// <DataItem>
/// ````
/// <br/>
/// Here, the `DataItem` type parameter acts as a phatom type.
/// This type should correpsond to the type of objects that the `NSFetchedResultsController` fetches.
public final class CollectionViewFetchedResultsDelegateProvider <DataItem> {
// MARK: Properties
/// The collection view that displays the data from the `NSFetchedResultsController` for which this provider provides a delegate.
public weak var collectionView: UICollectionView?
/// Returns the object that is notified when the fetched results changed.
public var delegate: NSFetchedResultsControllerDelegate { return bridgedDelegate }
// MARK: Initialization
/// Constructs a new delegate provider for a fetched results controller.
///
/// :param: collectionView The collection view to be updated when the fetched results change.
/// :param: controller The fetched results controller whose delegate will be provided by this provider.
///
/// :returns: A new `CollectionViewFetchedResultsDelegateProvider` instance.
public init(collectionView: UICollectionView, controller: NSFetchedResultsController? = nil) {
self.collectionView = collectionView
controller?.delegate = delegate
}
// MARK: Private
private typealias SectionIndex = Int
private typealias SectionChangesDictionary = [NSFetchedResultsChangeType : SectionIndex]
private typealias ObjectIndexPaths = [NSIndexPath]
private typealias ObjectChangesDictionary = [NSFetchedResultsChangeType : ObjectIndexPaths]
private var sectionChanges = [SectionChangesDictionary]()
private var objectChanges = [ObjectChangesDictionary]()
private lazy var bridgedDelegate: BridgedFetchedResultsDelegate = BridgedFetchedResultsDelegate(
willChangeContent: { [unowned self] (controller) -> Void in
self.sectionChanges.removeAll()
self.objectChanges.removeAll()
},
didChangeSection: { [unowned self] (controller, sectionInfo, sectionIndex, changeType) -> Void in
let changes: SectionChangesDictionary = [changeType : sectionIndex]
self.sectionChanges.append(changes)
},
didChangeObject: { [unowned self] (controller, anyObject, indexPath: NSIndexPath?, changeType, newIndexPath: NSIndexPath?) -> Void in
var changes = ObjectChangesDictionary()
switch changeType {
case .Insert:
if let insertIndexPath = newIndexPath {
changes[changeType] = [insertIndexPath]
}
case .Delete:
if let deleteIndexPath = indexPath {
changes[changeType] = [deleteIndexPath]
}
case .Update:
if let i = indexPath {
changes[changeType] = [i]
}
case .Move:
if let old = indexPath, new = newIndexPath {
changes[changeType] = [old, new]
}
}
self.objectChanges.append(changes)
},
didChangeContent: { [unowned self] (controller) -> Void in
self.collectionView?.performBatchUpdates({ () -> Void in
self.applyObjectChanges()
self.applySectionChanges()
},
completion:{ (finished) -> Void in
if self.sectionChanges.count > 0 {
// if sections have changed, reload to update supplementary views
self.collectionView?.reloadData()
}
self.sectionChanges.removeAll()
self.objectChanges.removeAll()
})
})
private func applyObjectChanges() {
for eachChange in objectChanges {
for (changeType: NSFetchedResultsChangeType, indexes: [NSIndexPath]) in eachChange {
switch(changeType) {
case .Insert: collectionView?.insertItemsAtIndexPaths(indexes)
case .Delete: collectionView?.deleteItemsAtIndexPaths(indexes)
case .Update: collectionView?.reloadItemsAtIndexPaths(indexes)
case .Move:
if let first = indexes.first, last = indexes.last {
collectionView?.moveItemAtIndexPath(first, toIndexPath: last)
}
}
}
}
}
private func applySectionChanges() {
for eachChange in sectionChanges {
for (changeType: NSFetchedResultsChangeType, index: SectionIndex) in eachChange {
let section = NSIndexSet(index: index)
switch(changeType) {
case .Insert: collectionView?.insertSections(section)
case .Delete: collectionView?.deleteSections(section)
case .Update: collectionView?.reloadSections(section)
case .Move: break
}
}
}
}
}
/// A `TableViewFetchedResultsDelegateProvider` is responsible for providing a delegate object
/// for an instance of `NSFetchedResultsController` that manages data to display in a table view.
/// <br/><br/>
/// **The delegate provider has the following type parameters:**
/// <br/>
/// ````
/// DataItem, CellFactory: TableViewCellFactoryType
/// where CellFactory.DataItem == DataItem>
/// ````
public final class TableViewFetchedResultsDelegateProvider <DataItem, CellFactory: TableViewCellFactoryType
where CellFactory.DataItem == DataItem> {
// MARK: Properties
/// The table view that displays the data from the `NSFetchedResultsController` for which this provider provides a delegate.
public weak var tableView: UITableView?
/// Returns the cell factory for this delegate provider.
public let cellFactory: CellFactory
/// Returns the object that is notified when the fetched results changed.
public var delegate: NSFetchedResultsControllerDelegate { return bridgedDelegate }
// MARK: Initialization
/// Constructs a new delegate provider for a fetched results controller.
///
/// :param: tableView The table view to be updated when the fetched results change.
/// :param: cellFactory The cell factory from which the fetched results controller delegate will configure cells.
/// :param: controller The fetched results controller whose delegate will be provided by this provider.
///
/// :returns: A new `TableViewFetchedResultsDelegateProvider` instance.
public init(tableView: UITableView, cellFactory: CellFactory, controller: NSFetchedResultsController? = nil) {
self.tableView = tableView
self.cellFactory = cellFactory
controller?.delegate = delegate
}
// MARK: Private
private lazy var bridgedDelegate: BridgedFetchedResultsDelegate = BridgedFetchedResultsDelegate(
willChangeContent: { [unowned self] (controller) -> Void in
self.tableView?.beginUpdates()
},
didChangeSection: { [unowned self] (controller, sectionInfo, sectionIndex, changeType) -> Void in
switch changeType {
case .Insert:
self.tableView?.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView?.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
break
}
},
didChangeObject: { [unowned self] (controller, anyObject, indexPath, changeType, newIndexPath) -> Void in
switch changeType {
case .Insert:
if let insertIndexPath = newIndexPath {
self.tableView?.insertRowsAtIndexPaths([insertIndexPath], withRowAnimation: .Fade)
}
case .Delete:
if let deleteIndexPath = indexPath {
self.tableView?.deleteRowsAtIndexPaths([deleteIndexPath], withRowAnimation: .Fade)
}
case .Update:
if let i = indexPath, cell = self.tableView?.cellForRowAtIndexPath(i) as? CellFactory.Cell, view = self.tableView {
self.cellFactory.configureCell(cell, forItem: anyObject as! DataItem, inTableView: view, atIndexPath: i)
}
case .Move:
if let deleteIndexPath = indexPath {
self.tableView?.deleteRowsAtIndexPaths([deleteIndexPath], withRowAnimation: .Fade)
}
if let insertIndexPath = newIndexPath {
self.tableView?.insertRowsAtIndexPaths([insertIndexPath], withRowAnimation: .Fade)
}
}
},
didChangeContent: { [unowned self] (controller) -> Void in
self.tableView?.endUpdates()
})
}
/**
* This separate type is required for Objective-C interoperability (interacting with Cocoa).
* Because the DelegateProvider is generic it cannot be bridged to Objective-C.
* That is, it cannot be assigned to `NSFetchedResultsController.delegate`
*/
@objc private final class BridgedFetchedResultsDelegate: NSFetchedResultsControllerDelegate {
typealias WillChangeContentHandler = (NSFetchedResultsController) -> Void
typealias DidChangeSectionHandler = (NSFetchedResultsController, NSFetchedResultsSectionInfo, Int, NSFetchedResultsChangeType) -> Void
typealias DidChangeObjectHandler = (NSFetchedResultsController, AnyObject, NSIndexPath?, NSFetchedResultsChangeType, NSIndexPath?) -> Void
typealias DidChangeContentHandler = (NSFetchedResultsController) -> Void
let willChangeContent: WillChangeContentHandler
let didChangeSection: DidChangeSectionHandler
let didChangeObject: DidChangeObjectHandler
let didChangeContent: DidChangeContentHandler
init(willChangeContent: WillChangeContentHandler,
didChangeSection: DidChangeSectionHandler,
didChangeObject: DidChangeObjectHandler,
didChangeContent: DidChangeContentHandler) {
self.willChangeContent = willChangeContent
self.didChangeSection = didChangeSection
self.didChangeObject = didChangeObject
self.didChangeContent = didChangeContent
}
@objc func controllerWillChangeContent(controller: NSFetchedResultsController) {
willChangeContent(controller)
}
@objc func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
didChangeSection(controller, sectionInfo, sectionIndex, type)
}
@objc func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
didChangeObject(controller, anObject, indexPath, type, newIndexPath)
}
@objc func controllerDidChangeContent(controller: NSFetchedResultsController) {
didChangeContent(controller)
}
}
|
mit
|
b3b64991f60d0289184097a5999a6f74
| 40.703833 | 142 | 0.658117 | 5.737776 | false | false | false | false |
uasys/swift
|
test/refactoring/ExtractFunction/name_correction.swift
|
5
|
486
|
public class C {
/// Insert before this.
public func foo() -> Int{
var aaa = 1 + 2
aaa = aaa + 3
if aaa == 3 { aaa = 4 }
return aaa
}
public func new_name() {}
public func new_name1() {}
public func new_name2() {}
public func new_name3() {}
}
// RUN: rm -rf %t.result && mkdir -p %t.result
// RUN: %refactor -extract-function -source-filename %s -pos=5:1 -end-pos=6:26 >> %t.result/L5-6.swift
// RUN: diff -u %S/Outputs/name_correction/L5-6.swift.expected %t.result/L5-6.swift
|
apache-2.0
|
9942bd59be0dcc086538464f35eb86f1
| 27.588235 | 102 | 0.631687 | 2.685083 | false | false | false | false |
nakkoservices/nkjson
|
Sources/NKJSON/NKJSON.swift
|
1
|
17592
|
//
// NKJSON.swift
// NKJSON
//
// Created by Mihai Fratu on 27/02/15.
// Copyright (c) 2015 Nakko. All rights reserved.
//
import Foundation
#if os(OSX)
import AppKit
#else
import UIKit
#endif
private let dotReplacement = "_|_DOT_|_"
// Extract a Foundation object
infix operator <> : NKJSONDefaultPrecedence
// Transform a type to another type using a callback
infix operator <<>> : NKJSONTransformPrecedence
public func <<>><T>(left: AnyObject?, callback: (AnyObject?) -> T?) -> T? {
return callback(left)
}
precedencegroup NKJSONDefaultPrecedence {
higherThan: BitwiseShiftPrecedence
}
precedencegroup NKJSONTransformPrecedence {
associativity: left
higherThan: NKJSONDefaultPrecedence
}
public func <><T> (left: inout T, right: Any?) {
if let value = right as? T {
left = value
}
}
public func <><T> (left: inout T?, right: Any?) {
if let value = right as? T {
left = value
}
}
public func <><T> (left: inout T, right: AnyObject?) {
if let value = right as? T {
left = value
}
}
public func <><T> (left: inout T?, right: AnyObject?) {
if let value = right as? T? {
left = value
}
}
public func <><T:NKJSONParsable> (left: inout T, right: AnyObject?) {
if let dictionary = right as? [String: AnyObject] {
if let object = (T.self as T.Type).init(JSON: NKJSON(dictionary: dictionary)) {
left = object
}
}
}
public func <><T:NKJSONParsable> (left: inout T?, right: AnyObject?) {
if let dictionary = right as? [String: AnyObject] {
left = (T.self as T.Type).init(JSON: NKJSON(dictionary: dictionary))
}
}
public func <><T:NKJSONParsable>(left: inout [T], right: AnyObject?) {
if let array = right as? [AnyObject] {
var allObjects = Array<T>()
for dictionary in array {
var object: T!
object <> dictionary
if object != nil {
allObjects.append(object)
}
}
left = allObjects
}
}
public func <><T:NKJSONParsable>(left: inout [T]?, right: AnyObject?) {
if let array = right as? [AnyObject] {
var allObjects = Array<T>()
for dictionary in array {
var object: T!
object <> dictionary
if object != nil {
allObjects.append(object)
}
}
left = allObjects
}
}
public func <><T:NKJSONParsable>(left: inout [String: T], right: AnyObject?) {
if let mainDictionary = right as? [String: AnyObject] {
var allObjects: [String: T] = [:]
for (key, dictionary): (String, AnyObject) in mainDictionary {
var object: T!
object <> dictionary
if object != nil {
allObjects[key] = object
}
}
left = allObjects
}
}
public func <><T:NKJSONParsable>(left: inout [String: T]?, right: AnyObject?) {
if let mainDictionary = right as? [String: AnyObject] {
var allObjects: [String: T] = [:]
for (key, dictionary): (String, AnyObject) in mainDictionary {
var object: T!
object <> dictionary
if object != nil {
allObjects[key] = object
}
}
left = allObjects
}
}
public class NKJSON {
// MARK: - Public class vars
public class var rootKey: String {
return "__root"
}
public static var dateFormat: String = "YYYY-MM-dd'T'HH:mm:ssZZZZZ"
// MARK: - Private instance vars
private var resultDictionary: [String: AnyObject]! = nil
// MARK: - Public class methods
public class func parse(_ JSONString: String) -> NKJSON? {
return parse(JSONString.data(using: .utf8, allowLossyConversion: true) as Data?)
}
public class func parse<T:NKJSONParsable>(_ JSONString: String, key: String? = nil) -> T? {
return parse(JSONString.data(using: .utf8, allowLossyConversion: true) as Data?, key: key)
}
public class func parse<T:NKJSONParsable>(_ JSONString: String, key: String? = nil) -> [T]? {
return parse(JSONString.data(using: .utf8, allowLossyConversion: true) as Data?, key: key)
}
public class func parse(_ JSONData: Data?) -> NKJSON? {
if let data = JSONData {
do {
if let result: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] {
return NKJSON(dictionary: result)
}
}
catch {
return nil
}
}
return nil
}
public class func parse<T:NKJSONParsable>(_ JSONData: Data?, key: String? = nil) -> T? {
if let data = JSONData {
do {
if let result: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] {
guard let key = key else {
return (T.self as T.Type).init(JSON: NKJSON(dictionary: result))
}
let JSON: NKJSON = NKJSON(dictionary: result)
if let object = JSON[key] as? T {
return object
}
else if let objectInfo = JSON[key] as? [String: AnyObject] {
return (T.self as T.Type).init(JSON: NKJSON(dictionary: objectInfo))
}
}
}
catch {
return nil
}
}
return nil
}
public class func parse<T:NKJSONParsable>(_ JSONData: Data?, key: String? = nil) -> [T]? {
if let data = JSONData {
do {
guard let key = key else {
if let result: [[String: AnyObject]] = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: AnyObject]] {
var allObjects: [T] = []
for objectInfo in result {
if let object = (T.self as T.Type).init(JSON: NKJSON(dictionary: objectInfo)) {
allObjects.append(object)
}
}
return allObjects
}
return nil
}
if let result: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] {
let JSON: NKJSON = NKJSON(dictionary: result)
if let objectInfos = JSON[key] as? [[String: AnyObject]] {
var allObjects: [T] = []
for objectInfo in objectInfos {
if let object = (T.self as T.Type).init(JSON: NKJSON(dictionary: objectInfo))
{
allObjects.append(object)
}
}
return allObjects
}
}
}
catch {
return nil
}
}
return nil
}
public class func parseFile<T:NKJSONParsable>(_ filePath: String, key: String? = nil) -> T? {
do {
return parse(try String(contentsOfFile: filePath), key: key)
}
catch {
return nil
}
}
public class func parseFile<T:NKJSONParsable>(_ filePath: String, key: String? = nil) -> [T]? {
do {
return parse(try String(contentsOfFile: filePath), key: key)
}
catch {
return nil
}
}
public init(dictionary: [String: AnyObject]) {
resultDictionary = dictionary
}
// MARK: - Private instance methods
private func getValue(keys: [String], array: [AnyObject]) -> AnyObject? {
if keys.isEmpty {
return nil
}
if let intKey = Int(keys.first!) {
if array.count <= intKey || intKey < 0 {
return nil
}
if keys.count > 1 {
if let newDictionary = array[intKey] as? [String: AnyObject] {
return getValue(keys: Array(keys[1..<keys.count]), dictionary: newDictionary)
}
else {
if let newArray = array[intKey] as? [AnyObject] {
return getValue(keys: Array(keys[1..<keys.count]), array: newArray)
}
}
}
else {
return array[intKey]
}
}
return nil
}
private func getValue(keys: [String], array: [AnyObject], keyName: String, keyValue: String, valueKey: String) -> AnyObject? {
if keys.isEmpty {
return nil
}
return nil
}
private func getValue(keys: [String], dictionary: [String: AnyObject]) -> AnyObject? {
if keys.isEmpty {
return nil
}
var currentKey = (keys.first! as String).replacingOccurrences(of: dotReplacement, with: ".")
do {
let regEx = try NSRegularExpression(pattern: "(.*?)(?:\\[(.*?)\\=(.*?)\\|(.*?)\\]|$)")
let result = regEx.firstMatch(in: currentKey, options: [], range: NSMakeRange(0, currentKey.count))!
if result.range(at: 2).location == NSNotFound {
if keys.count > 1 {
if let newDictionary = dictionary[currentKey] as? [String: AnyObject] {
return getValue(keys: Array(keys[1..<keys.count]), dictionary: newDictionary)
}
else {
if let newArray = dictionary[currentKey] as? [AnyObject] {
if keys[1] == "[*]" {
var values: [AnyObject] = []
for value in newArray {
guard let dictionary = getValue(keys: Array(keys[2..<keys.count]), dictionary: value as! [String : AnyObject]) else {
continue
}
values.append(dictionary)
}
return values as NSArray
}
return getValue(keys: Array(keys[1..<keys.count]), array: newArray)
}
}
}
else {
return dictionary[currentKey]
}
}
else {
let keyName = (currentKey as NSString).substring(with: result.range(at: 2))
let keyValue = (currentKey as NSString).substring(with: result.range(at: 3))
let valueKey = (currentKey as NSString).substring(with: result.range(at: 4))
currentKey = (currentKey as NSString).substring(with: result.range(at: 1))
guard let arrayOfPairs = dictionary[currentKey] as? [[String: AnyObject]] else {
return nil
}
for pair in arrayOfPairs {
guard let testKeyValue = pair[keyName] as? String, testKeyValue == keyValue else {
continue
}
if let newDictionary = pair[valueKey] as? [String: AnyObject] {
return getValue(keys: Array(keys[1..<keys.count]), dictionary: newDictionary)
}
else {
if let newArray = pair[valueKey] as? [AnyObject] {
if keys[1] == "[*]" {
var values: [AnyObject] = []
for value in newArray {
guard let dictionary = getValue(keys: Array(keys[2..<keys.count]), dictionary: value as! [String : AnyObject]) else {
continue
}
values.append(dictionary)
}
return values as NSArray
}
return getValue(keys: Array(keys[1..<keys.count]), array: newArray)
}
else {
return pair[valueKey]
}
}
}
}
}
catch _ {
fatalError("This should never happen!")
}
return nil
}
public subscript(key: String) -> AnyObject? {
if key == NKJSON.rootKey {
return resultDictionary as NSDictionary
}
let finalKey = (key as String).replacingOccurrences(of: "\\.", with: dotReplacement)
return getValue(keys: finalKey.components(separatedBy: "."), dictionary: resultDictionary)
}
public subscript(keys: [String]) -> AnyObject? {
for key in keys {
guard let value = self[key] else {
continue
}
return value
}
return nil
}
// MARK: - Helper methods
public class func toInt(object: AnyObject?) -> Int? {
guard let int = object as? Int else {
guard let intString = object as? NSString else {
return nil
}
return intString.integerValue
}
return int
}
public class func toFloat(object: AnyObject?) -> Float? {
guard let float = object as? Float else {
guard let floatString = object as? NSString else {
return nil
}
return floatString.floatValue
}
return float
}
public class func toBool(object: AnyObject?) -> Bool? {
guard let bool = object as? Bool else {
guard let boolString = object as? NSString else {
return nil
}
return boolString.boolValue
}
return bool
}
public class func toCGFloat(object: AnyObject?) -> CGFloat? {
guard let float = toFloat(object: object) else {
return nil
}
return CGFloat(float)
}
public class func toCGSize(object: AnyObject?) -> CGSize? {
guard let dictionary = object as? [String: CGFloat] else {
guard let dictionary = object as? [String: NSString] else {
return nil
}
guard let width = dictionary["width"] else {
return nil
}
guard let height = dictionary["height"] else {
return nil
}
return CGSize(width: CGFloat(width.floatValue), height: CGFloat(height.floatValue))
}
guard let width = dictionary["width"] else {
return nil
}
guard let height = dictionary["height"] else {
return nil
}
return CGSize(width: width, height: height)
}
public class func toCGPoint(object: AnyObject?) -> CGPoint? {
guard let dictionary = object as? [String: CGFloat] else {
guard let dictionary = object as? [String: NSString] else {
return nil
}
guard let x = dictionary["x"] else {
return nil
}
guard let y = dictionary["y"] else {
return nil
}
return CGPoint(x: CGFloat(x.floatValue), y: CGFloat(y.floatValue))
}
guard let x = dictionary["x"] else {
return nil
}
guard let y = dictionary["y"] else {
return nil
}
return CGPoint(x: x, y: y)
}
public class func toDate(object: AnyObject?) -> Date? {
guard let dateString = object as? String else {
return nil
}
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "CET")!
dateFormatter.dateFormat = dateFormat
guard let date = dateFormatter.date(from: dateString) else {
return dateString.detectDates()?.first
}
return date
}
public class func toNilIfEmpty(object: AnyObject?) -> String? {
guard let string = (object as? String)?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) else {
return nil
}
return string.isEmpty ? nil : string
}
}
public protocol NKJSONParsable {
init?(JSON: NKJSON)
}
extension String {
func detectDates() -> [Date]? {
do {
return try NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
.matches(in: self, options: [], range: NSRange(0..<count))
.filter {$0.resultType == .date}
.compactMap {$0.date}
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
}
|
mit
|
235c63359e4aed258cbc836a0e243f1e
| 31.577778 | 153 | 0.485391 | 4.997727 | false | false | false | false |
stephencelis/SQLite.swift
|
Sources/SQLite/Typed/Coding.swift
|
1
|
24178
|
//
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension QueryType {
/// Creates an `INSERT` statement by encoding the given object
/// This method converts any custom nested types to JSON data and does not handle any sort
/// of object relationships. If you want to support relationships between objects you will
/// have to provide your own Encodable implementations that encode the correct ids.
///
/// - Parameters:
///
/// - encodable: An encodable object to insert
///
/// - userInfo: User info to be passed to encoder
///
/// - otherSetters: Any other setters to include in the insert
///
/// - Returns: An `INSERT` statement for the encodable object
public func insert(_ encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:], otherSetters: [Setter] = []) throws -> Insert {
let encoder = SQLiteEncoder(userInfo: userInfo)
try encodable.encode(to: encoder)
return self.insert(encoder.setters + otherSetters)
}
/// Creates an `INSERT` statement by encoding the given object
/// This method converts any custom nested types to JSON data and does not handle any sort
/// of object relationships. If you want to support relationships between objects you will
/// have to provide your own Encodable implementations that encode the correct ids.
/// The onConflict will be passed to the actual insert function to define what should happen
/// when an error occurs during the insert operation.
///
/// - Parameters:
///
/// - onConlict: Define what happens when an insert operation fails
///
/// - encodable: An encodable object to insert
///
/// - userInfo: User info to be passed to encoder
///
/// - otherSetters: Any other setters to include in the insert
///
/// - Returns: An `INSERT` statement fort the encodable object
public func insert(or onConflict: OnConflict, encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:],
otherSetters: [Setter] = []) throws -> Insert {
let encoder = SQLiteEncoder(userInfo: userInfo)
try encodable.encode(to: encoder)
return self.insert(or: onConflict, encoder.setters + otherSetters)
}
/// Creates a batch `INSERT` statement by encoding the array of given objects
/// This method converts any custom nested types to JSON data and does not handle any sort
/// of object relationships. If you want to support relationships between objects you will
/// have to provide your own Encodable implementations that encode the correct ids.
///
/// - Parameters:
///
/// - encodables: Encodable objects to insert
///
/// - userInfo: User info to be passed to encoder
///
/// - otherSetters: Any other setters to include in the inserts, per row/object.
///
/// - Returns: An `INSERT` statement for the encodable objects
public func insertMany(_ encodables: [Encodable], userInfo: [CodingUserInfoKey: Any] = [:],
otherSetters: [Setter] = []) throws -> Insert {
let combinedSettersWithoutNils = try encodables.map { encodable -> [Setter] in
let encoder = SQLiteEncoder(userInfo: userInfo, forcingNilValueSetters: false)
try encodable.encode(to: encoder)
return encoder.setters + otherSetters
}
// requires the same number of setters per encodable
guard Set(combinedSettersWithoutNils.map(\.count)).count == 1 else {
// asymmetric sets of value insertions (some nil, some not), requires NULL value to satisfy INSERT query
let combinedSymmetricSetters = try encodables.map { encodable -> [Setter] in
let encoder = SQLiteEncoder(userInfo: userInfo, forcingNilValueSetters: true)
try encodable.encode(to: encoder)
return encoder.setters + otherSetters
}
return self.insertMany(combinedSymmetricSetters)
}
return self.insertMany(combinedSettersWithoutNils)
}
/// Creates an `INSERT ON CONFLICT DO UPDATE` statement, aka upsert, by encoding the given object
/// This method converts any custom nested types to JSON data and does not handle any sort
/// of object relationships. If you want to support relationships between objects you will
/// have to provide your own Encodable implementations that encode the correct ids.
///
/// - Parameters:
///
/// - encodable: An encodable object to insert
///
/// - userInfo: User info to be passed to encoder
///
/// - otherSetters: Any other setters to include in the insert
///
/// - onConflictOf: The column that if conflicts should trigger an update instead of insert.
///
/// - Returns: An `INSERT` statement fort the encodable object
public func upsert(_ encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:],
otherSetters: [Setter] = [], onConflictOf conflicting: Expressible) throws -> Insert {
let encoder = SQLiteEncoder(userInfo: userInfo)
try encodable.encode(to: encoder)
return self.upsert(encoder.setters + otherSetters, onConflictOf: conflicting)
}
/// Creates an `UPDATE` statement by encoding the given object
/// This method converts any custom nested types to JSON data and does not handle any sort
/// of object relationships. If you want to support relationships between objects you will
/// have to provide your own Encodable implementations that encode the correct ids.
///
/// - Parameters:
///
/// - encodable: An encodable object to insert
///
/// - userInfo: User info to be passed to encoder
///
/// - otherSetters: Any other setters to include in the insert
///
/// - Returns: An `UPDATE` statement fort the encodable object
public func update(_ encodable: Encodable, userInfo: [CodingUserInfoKey: Any] = [:],
otherSetters: [Setter] = []) throws -> Update {
let encoder = SQLiteEncoder(userInfo: userInfo)
try encodable.encode(to: encoder)
return self.update(encoder.setters + otherSetters)
}
}
extension Row {
/// Decode an object from this row
/// This method expects any custom nested types to be in the form of JSON data and does not handle
/// any sort of object relationships. If you want to support relationships between objects you will
/// have to provide your own Decodable implementations that decodes the correct columns.
///
/// - Parameter: userInfo
///
/// - Returns: a decoded object from this row
public func decode<V: Decodable>(userInfo: [CodingUserInfoKey: Any] = [:]) throws -> V {
try V(from: decoder(userInfo: userInfo))
}
public func decoder(userInfo: [CodingUserInfoKey: Any] = [:]) -> Decoder {
SQLiteDecoder(row: self, userInfo: userInfo)
}
}
/// Generates a list of settings for an Encodable object
private class SQLiteEncoder: Encoder {
class SQLiteKeyedEncodingContainer<MyKey: CodingKey>: KeyedEncodingContainerProtocol {
// swiftlint:disable nesting
typealias Key = MyKey
let encoder: SQLiteEncoder
let codingPath: [CodingKey] = []
let forcingNilValueSetters: Bool
init(encoder: SQLiteEncoder, forcingNilValueSetters: Bool = false) {
self.encoder = encoder
self.forcingNilValueSetters = forcingNilValueSetters
}
func superEncoder() -> Swift.Encoder {
fatalError("SQLiteEncoding does not support super encoders")
}
func superEncoder(forKey key: Key) -> Swift.Encoder {
fatalError("SQLiteEncoding does not support super encoders")
}
func encodeNil(forKey key: SQLiteEncoder.SQLiteKeyedEncodingContainer<Key>.Key) throws {
encoder.setters.append(Expression<String?>(key.stringValue) <- nil)
}
func encode(_ value: Int, forKey key: SQLiteEncoder.SQLiteKeyedEncodingContainer<Key>.Key) throws {
encoder.setters.append(Expression(key.stringValue) <- value)
}
func encode(_ value: Bool, forKey key: Key) throws {
encoder.setters.append(Expression(key.stringValue) <- value)
}
func encode(_ value: Float, forKey key: Key) throws {
encoder.setters.append(Expression(key.stringValue) <- Double(value))
}
func encode(_ value: Double, forKey key: Key) throws {
encoder.setters.append(Expression(key.stringValue) <- value)
}
func encode(_ value: String, forKey key: Key) throws {
encoder.setters.append(Expression(key.stringValue) <- value)
}
func encodeIfPresent(_ value: Int?, forKey key: SQLiteEncoder.SQLiteKeyedEncodingContainer<Key>.Key) throws {
if let value = value {
try encode(value, forKey: key)
} else if forcingNilValueSetters {
encoder.setters.append(Expression<Int?>(key.stringValue) <- nil)
}
}
func encodeIfPresent(_ value: Bool?, forKey key: Key) throws {
if let value = value {
try encode(value, forKey: key)
} else if forcingNilValueSetters {
encoder.setters.append(Expression<Bool?>(key.stringValue) <- nil)
}
}
func encodeIfPresent(_ value: Float?, forKey key: Key) throws {
if let value = value {
try encode(value, forKey: key)
} else if forcingNilValueSetters {
encoder.setters.append(Expression<Double?>(key.stringValue) <- nil)
}
}
func encodeIfPresent(_ value: Double?, forKey key: Key) throws {
if let value = value {
try encode(value, forKey: key)
} else if forcingNilValueSetters {
encoder.setters.append(Expression<Double?>(key.stringValue) <- nil)
}
}
func encodeIfPresent(_ value: String?, forKey key: MyKey) throws {
if let value = value {
try encode(value, forKey: key)
} else if forcingNilValueSetters {
encoder.setters.append(Expression<String?>(key.stringValue) <- nil)
}
}
func encode<T>(_ value: T, forKey key: Key) throws where T: Swift.Encodable {
switch value {
case let data as Data:
encoder.setters.append(Expression(key.stringValue) <- data)
case let date as Date:
encoder.setters.append(Expression(key.stringValue) <- date.datatypeValue)
case let uuid as UUID:
encoder.setters.append(Expression(key.stringValue) <- uuid.datatypeValue)
default:
let encoded = try JSONEncoder().encode(value)
let string = String(data: encoded, encoding: .utf8)
encoder.setters.append(Expression(key.stringValue) <- string)
}
}
func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T: Swift.Encodable {
guard let value = value else {
guard forcingNilValueSetters else {
return
}
encoder.setters.append(Expression<String?>(key.stringValue) <- nil)
return
}
try encode(value, forKey: key)
}
func encode(_ value: Int8, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an Int8 is not supported"))
}
func encode(_ value: Int16, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an Int16 is not supported"))
}
func encode(_ value: Int32, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an Int32 is not supported"))
}
func encode(_ value: Int64, forKey key: Key) throws {
encoder.setters.append(Expression(key.stringValue) <- value)
}
func encode(_ value: UInt, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an UInt is not supported"))
}
func encode(_ value: UInt8, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an UInt8 is not supported"))
}
func encode(_ value: UInt16, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an UInt16 is not supported"))
}
func encode(_ value: UInt32, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an UInt32 is not supported"))
}
func encode(_ value: UInt64, forKey key: Key) throws {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath,
debugDescription: "encoding an UInt64 is not supported"))
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key)
-> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
fatalError("encoding a nested container is not supported")
}
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
fatalError("encoding nested values is not supported")
}
}
fileprivate var setters: [Setter] = []
let codingPath: [CodingKey] = []
let userInfo: [CodingUserInfoKey: Any]
let forcingNilValueSetters: Bool
init(userInfo: [CodingUserInfoKey: Any], forcingNilValueSetters: Bool = false) {
self.userInfo = userInfo
self.forcingNilValueSetters = forcingNilValueSetters
}
func singleValueContainer() -> SingleValueEncodingContainer {
fatalError("not supported")
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError("not supported")
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
KeyedEncodingContainer(SQLiteKeyedEncodingContainer(encoder: self, forcingNilValueSetters: forcingNilValueSetters))
}
}
private class SQLiteDecoder: Decoder {
class SQLiteKeyedDecodingContainer<MyKey: CodingKey>: KeyedDecodingContainerProtocol {
typealias Key = MyKey
let codingPath: [CodingKey] = []
let row: Row
init(row: Row) {
self.row = row
}
var allKeys: [Key] {
row.columnNames.keys.compactMap({ Key(stringValue: $0) })
}
func contains(_ key: Key) -> Bool {
row.hasValue(for: key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
!contains(key)
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
try row.get(Expression(key.stringValue))
}
func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
try row.get(Expression(key.stringValue))
}
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an Int8 is not supported"))
}
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an Int16 is not supported"))
}
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an Int32 is not supported"))
}
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
try row.get(Expression(key.stringValue))
}
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an UInt is not supported"))
}
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an UInt8 is not supported"))
}
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an UInt16 is not supported"))
}
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an UInt32 is not supported"))
}
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an UInt64 is not supported"))
}
func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
Float(try row.get(Expression<Double>(key.stringValue)))
}
func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
try row.get(Expression(key.stringValue))
}
func decode(_ type: String.Type, forKey key: Key) throws -> String {
try row.get(Expression(key.stringValue))
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Swift.Decodable {
// swiftlint:disable force_cast
switch type {
case is Data.Type:
let data = try row.get(Expression<Data>(key.stringValue))
return data as! T
case is Date.Type:
let date = try row.get(Expression<Date>(key.stringValue))
return date as! T
case is UUID.Type:
let uuid = try row.get(Expression<UUID>(key.stringValue))
return uuid as! T
default:
// swiftlint:enable force_cast
guard let JSONString = try row.get(Expression<String?>(key.stringValue)) else {
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
debugDescription: "an unsupported type was found"))
}
guard let data = JSONString.data(using: .utf8) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "invalid utf8 data found"))
}
return try JSONDecoder().decode(type, from: data)
}
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws
-> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding nested containers is not supported"))
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding unkeyed containers is not supported"))
}
func superDecoder() throws -> Swift.Decoder {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding super encoders containers is not supported"))
}
func superDecoder(forKey key: Key) throws -> Swift.Decoder {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding super decoders is not supported"))
}
}
let row: Row
let codingPath: [CodingKey] = []
let userInfo: [CodingUserInfoKey: Any]
init(row: Row, userInfo: [CodingUserInfoKey: Any]) {
self.row = row
self.userInfo = userInfo
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
KeyedDecodingContainer(SQLiteKeyedDecodingContainer(row: row))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding an unkeyed container is not supported"))
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
debugDescription: "decoding a single value container is not supported"))
}
}
|
mit
|
4f93226e7e34b4c5838321a3acccb9f8
| 45.673745 | 141 | 0.603673 | 5.317132 | false | false | false | false |
EnderTan/ETNavBarTransparent
|
ETNavBarTransparent/ETNavBarTransparent.swift
|
1
|
10971
|
//
// ETNavBarTransparent.swift
// ETNavBarTransparentDemo
//
// Created by Bing on 2017/3/1.
// Copyright © 2017年 tanyunbing. All rights reserved.
//
import UIKit
extension UIColor {
// System default bar tint color
open class var defaultNavBarTintColor: UIColor {
return UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1.0)
}
}
extension DispatchQueue {
private static var onceTracker = [String]()
public class func once(token: String, block: () -> Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
if onceTracker.contains(token) {
return
}
onceTracker.append(token)
block()
}
}
extension UINavigationController {
override open var preferredStatusBarStyle: UIStatusBarStyle {
return topViewController?.preferredStatusBarStyle ?? .default
}
open override func viewDidLoad() {
UINavigationController.swizzle()
super.viewDidLoad()
}
private static let onceToken = UUID().uuidString
class func swizzle() {
guard self == UINavigationController.self else { return }
DispatchQueue.once(token: onceToken) {
let needSwizzleSelectorArr = [
NSSelectorFromString("_updateInteractiveTransition:"),
#selector(popViewController(animated:)),
#selector(popToViewController(_:animated:)),
#selector(popToRootViewController(animated:))
]
for selector in needSwizzleSelectorArr {
let str = ("et_" + selector.description).replacingOccurrences(of: "__", with: "_")
// popToRootViewControllerAnimated: et_popToRootViewControllerAnimated:
let originalMethod = class_getInstanceMethod(self, selector)
let swizzledMethod = class_getInstanceMethod(self, Selector(str))
if originalMethod != nil && swizzledMethod != nil {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
}
}
@objc func et_updateInteractiveTransition(_ percentComplete: CGFloat) {
guard let topViewController = topViewController, let coordinator = topViewController.transitionCoordinator else {
et_updateInteractiveTransition(percentComplete)
return
}
if #available(iOS 10.0, *) {
coordinator.notifyWhenInteractionChanges({ (context) in
self.dealInteractionChanges(context)
})
} else {
coordinator.notifyWhenInteractionEnds({ (context) in
self.dealInteractionChanges(context)
})
}
let fromViewController = coordinator.viewController(forKey: .from)
let toViewController = coordinator.viewController(forKey: .to)
// Bg Alpha
let fromAlpha = fromViewController?.navBarBgAlpha ?? 0
let toAlpha = toViewController?.navBarBgAlpha ?? 0
let newAlpha = fromAlpha + (toAlpha - fromAlpha) * percentComplete
setNeedsNavigationBackground(alpha: newAlpha)
// Tint Color
let fromColor = fromViewController?.navBarTintColor ?? .blue
let toColor = toViewController?.navBarTintColor ?? .blue
let newColor = averageColor(fromColor: fromColor, toColor: toColor, percent: percentComplete)
navigationBar.tintColor = newColor
et_updateInteractiveTransition(percentComplete)
}
// Calculate the middle Color with translation percent
private func averageColor(fromColor: UIColor, toColor: UIColor, percent: CGFloat) -> UIColor {
var fromRed: CGFloat = 0
var fromGreen: CGFloat = 0
var fromBlue: CGFloat = 0
var fromAlpha: CGFloat = 0
fromColor.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha)
var toRed: CGFloat = 0
var toGreen: CGFloat = 0
var toBlue: CGFloat = 0
var toAlpha: CGFloat = 0
toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha)
let nowRed = fromRed + (toRed - fromRed) * percent
let nowGreen = fromGreen + (toGreen - fromGreen) * percent
let nowBlue = fromBlue + (toBlue - fromBlue) * percent
let nowAlpha = fromAlpha + (toAlpha - fromAlpha) * percent
return UIColor(red: nowRed, green: nowGreen, blue: nowBlue, alpha: nowAlpha)
}
@objc func et_popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
setNeedsNavigationBackground(alpha: viewController.navBarBgAlpha)
navigationBar.tintColor = viewController.navBarTintColor
return et_popToViewController(viewController, animated: animated)
}
@objc func et_popViewControllerAnimated(_ animated: Bool) -> UIViewController? {
if #available(iOS 13.0, *) {
if (viewControllers.count > 1 && interactivePopGestureRecognizer?.state != .began){
let popToVC = viewControllers[viewControllers.count - 2]
setNeedsNavigationBackground(alpha: popToVC.navBarBgAlpha)
navigationBar.tintColor = popToVC.navBarTintColor
}
}
return et_popViewControllerAnimated(animated)
}
@objc func et_popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]? {
setNeedsNavigationBackground(alpha: viewControllers.first?.navBarBgAlpha ?? 0)
navigationBar.tintColor = viewControllers.first?.navBarTintColor
return et_popToRootViewControllerAnimated(animated)
}
fileprivate func setNeedsNavigationBackground(alpha: CGFloat) {
if let barBackgroundView = navigationBar.subviews.first {
let valueForKey = barBackgroundView.getIvar(forKey:)
if let shadowView = valueForKey("_shadowView") as? UIView {
shadowView.alpha = alpha
shadowView.isHidden = alpha == 0
}
if navigationBar.isTranslucent {
if #available(iOS 10.0, *) {
if let backgroundEffectView = valueForKey("_backgroundEffectView") as? UIView, navigationBar.backgroundImage(for: .default) == nil {
backgroundEffectView.alpha = alpha
return
}
} else {
if let adaptiveBackdrop = valueForKey("_adaptiveBackdrop") as? UIView , let backdropEffectView = adaptiveBackdrop.value(forKey: "_backdropEffectView") as? UIView {
backdropEffectView.alpha = alpha
return
}
}
}
barBackgroundView.alpha = alpha
}
}
}
extension NSObject {
func getIvar(forKey key: String) -> Any? {
guard let _var = class_getInstanceVariable(type(of: self), key) else {
return nil
}
return object_getIvar(self, _var)
}
}
extension UINavigationController: UINavigationBarDelegate {
public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
if let topVC = topViewController, let coor = topVC.transitionCoordinator, coor.initiallyInteractive {
if #available(iOS 10.0, *) {
coor.notifyWhenInteractionChanges({ (context) in
self.dealInteractionChanges(context)
})
} else {
coor.notifyWhenInteractionEnds({ (context) in
self.dealInteractionChanges(context)
})
}
return true
}
let itemCount = navigationBar.items?.count ?? 0
let n = viewControllers.count >= itemCount ? 2 : 1
let popToVC = viewControllers[viewControllers.count - n]
if #available(iOS 13.0, *) {
setNeedsNavigationBackground(alpha: popToVC.navBarBgAlpha)
navigationBar.tintColor = popToVC.navBarTintColor
} else {
popToViewController(popToVC, animated: true)
}
return true
}
public func navigationBar(_ navigationBar: UINavigationBar, shouldPush item: UINavigationItem) -> Bool {
setNeedsNavigationBackground(alpha: topViewController?.navBarBgAlpha ?? 0)
navigationBar.tintColor = topViewController?.navBarTintColor
return true
}
private func dealInteractionChanges(_ context: UIViewControllerTransitionCoordinatorContext) {
let animations: (UITransitionContextViewControllerKey) -> () = {
let nowAlpha = context.viewController(forKey: $0)?.navBarBgAlpha ?? 0
self.setNeedsNavigationBackground(alpha: nowAlpha)
self.navigationBar.tintColor = context.viewController(forKey: $0)?.navBarTintColor
}
if context.isCancelled {
let cancelDuration: TimeInterval = context.transitionDuration * Double(context.percentComplete)
UIView.animate(withDuration: cancelDuration) {
animations(.from)
}
} else {
let finishDuration: TimeInterval = context.transitionDuration * Double(1 - context.percentComplete)
UIView.animate(withDuration: finishDuration) {
animations(.to)
}
}
}
}
extension UIViewController {
fileprivate struct AssociatedKeys {
static var navBarBgAlpha: CGFloat = 1.0
static var navBarTintColor: UIColor = UIColor.defaultNavBarTintColor
}
open var navBarBgAlpha: CGFloat {
get {
guard let alpha = objc_getAssociatedObject(self, &AssociatedKeys.navBarBgAlpha) as? CGFloat else {
return 1.0
}
return alpha
}
set {
let alpha = max(min(newValue, 1), 0) // 必须在 0~1的范围
objc_setAssociatedObject(self, &AssociatedKeys.navBarBgAlpha, alpha, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// Update UI
navigationController?.setNeedsNavigationBackground(alpha: alpha)
}
}
open var navBarTintColor: UIColor {
get {
guard let tintColor = objc_getAssociatedObject(self, &AssociatedKeys.navBarTintColor) as? UIColor else {
return UIColor.defaultNavBarTintColor
}
return tintColor
}
set {
navigationController?.navigationBar.tintColor = newValue
objc_setAssociatedObject(self, &AssociatedKeys.navBarTintColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
|
mit
|
845765e548d9faa0abba287ba0551a5a
| 37.307692 | 183 | 0.609164 | 5.491729 | false | false | false | false |
IngmarStein/swift
|
test/SILGen/types.swift
|
1
|
3359
|
// RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | %FileCheck %s
class C {
var member: Int = 0
// Methods have method calling convention.
// CHECK-LABEL: sil hidden @_TFC5types1C3foo{{.*}} : $@convention(method) (Int, @guaranteed C) -> () {
func foo(x x: Int) {
// CHECK: bb0([[X:%[0-9]+]] : $Int, [[THIS:%[0-9]+]] : $C):
member = x
// CHECK-NOT: strong_retain
// CHECK: [[FN:%[0-9]+]] = class_method %1 : $C, #C.member!setter.1
// CHECK: apply [[FN]](%0, %1) : $@convention(method) (Int, @guaranteed C) -> ()
// CHECK-NOT: strong_release
}
}
struct S {
var member: Int
// CHECK-LABEL: sil hidden @{{.*}}1S3foo{{.*}} : $@convention(method) (Int, @inout S) -> ()
mutating
func foo(x x: Int) {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : $Int, [[THIS:%[0-9]+]] : $*S):
member = x
// CHECK: [[THIS_LOCAL_ADDR:%[0-9]+]] = alloc_box $S
// CHECK: [[THIS_LOCAL:%[0-9]+]] = project_box [[THIS_LOCAL_ADDR]]
// CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: [[MEMBER:%[0-9]+]] = struct_element_addr [[THIS_LOCAL]] : $*S, #S.member
// CHECK: copy_addr [[X]] to [[MEMBER]]
}
class SC {
// CHECK-LABEL: sil hidden @_TFCV5types1S2SC3bar{{.*}}
func bar() {}
}
}
func f() {
class FC {
// CHECK-LABEL: sil shared @_TFCF5types1fFT_T_L_2FC3zim{{.*}}
func zim() {}
}
}
func g(b b : Bool) {
if (b) {
class FC {
// CHECK-LABEL: sil shared @_TFCF5types1gFT1bSb_T_L_2FC3zim{{.*}}
func zim() {}
}
} else {
class FC {
// CHECK-LABEL: sil shared @_TFCF5types1gFT1bSb_T_L0_2FC3zim{{.*}}
func zim() {}
}
}
}
struct ReferencedFromFunctionStruct {
let f: (ReferencedFromFunctionStruct) -> () = {x in ()}
let g: (ReferencedFromFunctionEnum) -> () = {x in ()}
}
enum ReferencedFromFunctionEnum {
case f((ReferencedFromFunctionEnum) -> ())
case g((ReferencedFromFunctionStruct) -> ())
}
// CHECK-LABEL: sil hidden @_TF5types34referencedFromFunctionStructFieldsFVS_28ReferencedFromFunctionStructTFS0_T_FOS_26ReferencedFromFunctionEnumT__
// CHECK: [[F:%.*]] = struct_extract [[X:%.*]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.f
// CHECK: [[F]] : $@callee_owned (@owned ReferencedFromFunctionStruct) -> ()
// CHECK: [[G:%.*]] = struct_extract [[X]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.g
// CHECK: [[G]] : $@callee_owned (@owned ReferencedFromFunctionEnum) -> ()
func referencedFromFunctionStructFields(_ x: ReferencedFromFunctionStruct)
-> ((ReferencedFromFunctionStruct) -> (), (ReferencedFromFunctionEnum) -> ()) {
return (x.f, x.g)
}
// CHECK-LABEL: sil hidden @_TF5types32referencedFromFunctionEnumFieldsFOS_26ReferencedFromFunctionEnumTGSqFS0_T__GSqFVS_28ReferencedFromFunctionStructT___
// CHECK: bb{{[0-9]+}}([[F:%.*]] : $@callee_owned (@owned ReferencedFromFunctionEnum) -> ()):
// CHECK: bb{{[0-9]+}}([[G:%.*]] : $@callee_owned (@owned ReferencedFromFunctionStruct) -> ()):
func referencedFromFunctionEnumFields(_ x: ReferencedFromFunctionEnum)
-> (
((ReferencedFromFunctionEnum) -> ())?,
((ReferencedFromFunctionStruct) -> ())?
) {
switch x {
case .f(let f):
return (f, nil)
case .g(let g):
return (nil, g)
}
}
|
apache-2.0
|
40532bf568718a3d8c98750b43ee198a
| 32.929293 | 155 | 0.598095 | 3.192966 | false | false | false | false |
soapyigu/LeetCode_Swift
|
Math/RomanToInteger.swift
|
1
|
1036
|
/**
* Question Link: https://leetcode.com/problems/roman-to-integer/
* Primary idea: Iterate through end to start, add or minus according to different situations
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class RomanToInteger {
func romanToInt(s: String) -> Int {
let dict = initDict()
let chars = [Character](s.characters.reverse())
var res = 0
for i in 0..<chars.count {
guard let current = dict[String(chars[i])] else {
return res
}
if i > 0 && current < dict[String(chars[i - 1])] {
res -= current
} else {
res += current
}
}
return res
}
private func initDict() -> [String: Int] {
var dict = [String: Int]()
dict["I"] = 1
dict["V"] = 5
dict["X"] = 10
dict["L"] = 50
dict["C"] = 100
dict["D"] = 500
dict["M"] = 1000
return dict
}
}
|
mit
|
fc00b912d91bda073bc6127fe2aaf188
| 24.292683 | 93 | 0.468147 | 4.144 | false | false | false | false |
ryan-blunden/ga-mobile
|
Resources/Lesson 08 - Control Flow.playground/Contents.swift
|
2
|
4513
|
//: Playground - noun: a place where people can play
import UIKit
////////////////////////
/// CONTROL FLOW ///
////////////////////////
// Two main structures for reacting to the state of your code
// - if/else if/else
// - switch
//--- If, else if, else ---//
// Testing an optional before we use it
var optionalName:String? = "The Dude"
// Version 1 - if let syntax
if let nameValue = optionalName {
println("Use the unwrapped value from optionalName: '\(nameValue)'")
}
else {
println("No value for `nameValue`")
}
// Vesion (Try to avoid)
if optionalName != nil {
println(optionalName!) // Unbox optionalName's value now that we know it's safe to do so
}
// Version 1 is the preferred way to do this as it's safer and `nameValue` scope is limited to the if statement
// Examplple of multiple in a statement conditions
// && means AND = all statements must evaluate to true
var mealOfChampions = ["meat pie", "tomato sauce"]
if contains(mealOfChampions, "meat pie") {
println("Ripper")
}
// Even though this is also true, Swift will stop looking for options as soon as it finds an option that returns true
else if contains(mealOfChampions, "meat pie") && contains(mealOfChampions, "tomato sauce") {
println("You bloody ripper")
}
else {
println("Rabbitfood...again.")
}
// || neans OR = if any of the statements are true
var menu = ["pizza", "chicken parma"]
if contains(menu, "sushi") || contains(menu, "chicken parma") {
println("Let's eat here")
}
// You can combine && and ||
var restaurant = (food:"cheap", drinks:"fully licensed", style:"chinese", location:"close")
if (restaurant.food == "cheap" && restaurant.drinks == "BYO") || restaurant.location == "close" {
println("Let's go here")
}
// Sometimes if/else else gets out of hand
enum Direction {
case North
case South
case East
case West
}
let walkingDirection = Direction.East
// This works but it's a bit hard to read
if walkingDirection == .North {
println("Walking North")
}
else if walkingDirection == .South {
println("Walking South")
}
else if walkingDirection == .East {
println("Walking East")
}
else {
println("Walking West")
}
// Switch statements to the rescue!
//------------------------------------------
//--- Switch ---//
switch walkingDirection {
case .North:
println("Walking North")
case .South, .East, .West:
println("Not walking North")
}
// Switch statements must be exaustive (covers all options)
switch walkingDirection {
case .North:
println("Walking North")
// Without this, Swift would complain
default:
println("Not walking North")
}
// Switch statements can do more than straight up matching
var planeSeatNumber = (row:19, seat:"A")
// The `_` means you don't care about that value
switch planeSeatNumber {
case (_, "C"):
println("Scored a window seat")
case (19, "A"):
println("Isle seat near the back")
default:
println("Enjoy your flight")
}
//------------------------------------------
//////////////////////
/// ITERATING ///
/////////////////////
// for, for in, for (x, y) in, while
// Arrays
let temperatures = [23, 20, 18, 15, 14, 10, 0]
for temperature in temperatures {
if temperature <= 10 {
println("Freezing")
}
else {
println("Not too bad")
}
}
let leadingGoalKickers = [
"Joshua Kennedy": 22,
"Josh Bruce": 17,
"Jay Schulz": 16
]
for (name, goals) in leadingGoalKickers {
println("Player \(name) has kicked \(goals) so far this season.")
}
println("GO THE HAWKS!!!!") // This just here because
// Iterating over a list of user defined things
struct User {
let email:String
let password:String
}
var users = [User]()
users.append(
User(email: "dude@gmail.com", password: "dude")
)
users.append(
User(email: "henry@hotmailcom", password: "cottensox")
)
// Doing simple user authentication
var enteredEmail = "dude@gmail.com"
var enteredPassword = "dudes"
// Presume we won't find a match
var userAuthenticated = false
for user in users {
if enteredEmail == user.email && enteredPassword == user.password {
userAuthenticated = true
break // This means stop the for loop as we don't need to continue
}
}
if userAuthenticated {
println("Access granted")
}
else {
println("Access denied")
}
// Jumping a bit ahead, but doing the same thing via array filtering
if let user = (users.filter { $0.email == enteredEmail && $0.password == enteredPassword }).first {
println("Access granted to \(user.email)")
}
else {
println("Access denied")
}
|
gpl-3.0
|
9e7c0992322a9b4f84a88f7a9018e910
| 20.593301 | 119 | 0.653446 | 3.58744 | false | false | false | false |
brentsimmons/Evergreen
|
Account/Sources/Account/FeedFinder/FeedSpecifier.swift
|
1
|
2506
|
//
// FeedSpecifier.swift
// NetNewsWire
//
// Created by Brent Simmons on 8/7/16.
// Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//
import Foundation
struct FeedSpecifier: Hashable {
enum Source: Int {
case UserEntered = 0, HTMLHead, HTMLLink
func equalToOrBetterThan(_ otherSource: Source) -> Bool {
return self.rawValue <= otherSource.rawValue
}
}
public let title: String?
public let urlString: String
public let source: Source
public let orderFound: Int
public var score: Int {
return calculatedScore()
}
func feedSpecifierByMerging(_ feedSpecifier: FeedSpecifier) -> FeedSpecifier {
// Take the best data (non-nil title, better source) to create a new feed specifier;
let mergedTitle = title ?? feedSpecifier.title
let mergedSource = source.equalToOrBetterThan(feedSpecifier.source) ? source : feedSpecifier.source
let mergedOrderFound = orderFound < feedSpecifier.orderFound ? orderFound : feedSpecifier.orderFound
return FeedSpecifier(title: mergedTitle, urlString: urlString, source: mergedSource, orderFound: mergedOrderFound)
}
public static func bestFeed(in feedSpecifiers: Set<FeedSpecifier>) -> FeedSpecifier? {
if feedSpecifiers.isEmpty {
return nil
}
if feedSpecifiers.count == 1 {
return feedSpecifiers.anyObject()
}
var currentHighScore = Int.min
var currentBestFeed: FeedSpecifier? = nil
for oneFeedSpecifier in feedSpecifiers {
let oneScore = oneFeedSpecifier.score
if oneScore > currentHighScore {
currentHighScore = oneScore
currentBestFeed = oneFeedSpecifier
}
}
return currentBestFeed
}
}
private extension FeedSpecifier {
func calculatedScore() -> Int {
var score = 0
if source == .UserEntered {
return 1000
}
else if source == .HTMLHead {
score = score + 50
}
score = score - ((orderFound - 1) * 5)
if urlString.caseInsensitiveContains("comments") {
score = score - 10
}
if urlString.caseInsensitiveContains("podcast") {
score = score - 10
}
if urlString.caseInsensitiveContains("rss") {
score = score + 5
}
if urlString.hasSuffix("/feed/") {
score = score + 5
}
if urlString.hasSuffix("/feed") {
score = score + 4
}
if urlString.caseInsensitiveContains("json") {
score = score + 6
}
if let title = title {
if title.caseInsensitiveContains("comments") {
score = score - 10
}
if title.caseInsensitiveContains("json") {
score = score + 1
}
}
return score
}
}
|
mit
|
5dc59220e95ecf86edc81c71e35efd3c
| 22.632075 | 116 | 0.697804 | 3.651603 | false | false | false | false |
J3D1-WARR10R/WikiRaces
|
WikiRaces/Shared/Race View Controllers/HistoryViewController/HistoryTableViewStatsCell.swift
|
2
|
3357
|
//
// HistoryTableViewStatsCell.swift
// WikiRaces
//
// Created by Andrew Finke on 2/28/19.
// Copyright © 2019 Andrew Finke. All rights reserved.
//
import UIKit
final internal class HistoryTableViewStatsCell: UITableViewCell {
// MARK: - Properties -
static let reuseIdentifier = "statsReuseIdentifier"
var stat: (key: String, value: String)? {
didSet {
statLabel.text = stat?.key
detailLabel.text = stat?.value
}
}
let statLabel = UILabel()
let detailLabel = UILabel()
// MARK: - Initialization -
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
statLabel.textAlignment = .left
statLabel.font = UIFont.systemFont(ofSize: 17, weight: .regular)
statLabel.numberOfLines = 0
statLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(statLabel)
detailLabel.font = UIFont.systemFont(ofSize: 17, weight: .medium)
detailLabel.textAlignment = .right
detailLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
detailLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(detailLabel)
setupConstraints()
isUserInteractionEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Life Cycle -
public override func layoutSubviews() {
super.layoutSubviews()
let textColor = UIColor.wkrTextColor(for: traitCollection)
tintColor = textColor
statLabel.textColor = textColor
detailLabel.textColor = textColor
}
// MARK: - Constraints -
private func setupConstraints() {
let leftMarginConstraint = NSLayoutConstraint(item: statLabel,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .leftMargin,
multiplier: 1.0,
constant: 0.0)
let rightMarginConstraint = NSLayoutConstraint(item: detailLabel,
attribute: .right,
relatedBy: .equal,
toItem: self,
attribute: .rightMargin,
multiplier: 1.0,
constant: 0.0)
let constraints = [
leftMarginConstraint,
statLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10),
statLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 15),
statLabel.rightAnchor.constraint(lessThanOrEqualTo: detailLabel.leftAnchor, constant: -15),
rightMarginConstraint,
detailLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
]
NSLayoutConstraint.activate(constraints)
}
}
|
mit
|
851ed0b40d3a8f5047e82fb7b291c7e0
| 35.086022 | 103 | 0.548272 | 6.203327 | false | false | false | false |
yinyifu/cse442_watch
|
applewatch_mapping/SocialController.swift
|
1
|
3078
|
//
// ViewController.swift
// applewatch_mapping
//
// Created by yifu on 9/6/17.
// Copyright © 2017 CSE442_UB. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import GoogleMaps
import GooglePlaces
//@interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>
class SocialController: UIViewController {
let _sc : SessionController = SessionController();
private var mapController : MapController?;
let range = 10
@IBAction func autocompleteClicked(_ sender: UIButton) {
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
present(autocompleteController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad();
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? MapController,
segue.identifier == "socialSegue" {
self.mapController = vc
}else{
NSLog("Motherfucker didnt prepare");
}
}
func alerting(title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle : UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
//trying to make uiimage
@objc func getLoc(sender: UIButton, event: UIEvent){
//_sc.send_image()
}
}
extension SocialController : GMSAutocompleteViewControllerDelegate {
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
// runner.setCenter(place.coordinate)
//let sboar : UIStoryboard = UIStoryboard(name:"Main", bundle:nil);
if let map = self.mapController{
map.setCenter(place.coordinate)
}else{
NSLog("Motherfucker didnt coord");
}
NSLog("coor is \(place.coordinate.latitude) + \(place.coordinate.longitude)");
NSLog("runner is nil");
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
|
mit
|
4f4164ee5ffc4494f3d5c65ee3975dc1
| 32.813187 | 117 | 0.683133 | 5.102819 | false | false | false | false |
OpsLabJPL/MarsImagesIOS
|
MarsImagesIOS/InternetReachabilityStatus.swift
|
1
|
814
|
//
// InternetReachabilityStatus.swift
// MarsImagesIOS
//
// Created by Powell, Mark W (397F) on 8/4/17.
// Copyright © 2017 Mark Powell. All rights reserved.
//
import SwiftMessages
class InternetReachabilityStatus {
static func createStatus(_ layout: MessageView.Layout = .statusLine) -> MessageView {
let status = MessageView.viewFromNib(layout: layout)
status.button?.isHidden = true
status.iconLabel?.text = "❌"
status.iconImageView?.isHidden = true
status.titleLabel?.isHidden = true
status.backgroundView.backgroundColor = UIColor.red
status.bodyLabel?.textColor = UIColor.white
status.configureContent(body: NSLocalizedString("Please, check your internet connection", comment: "internet failure"))
return status
}
}
|
apache-2.0
|
f13a9d2ad20fa8808b321548381ebb64
| 34.26087 | 127 | 0.697904 | 4.634286 | false | false | false | false |
rzrasel/iOS-Swift-2016-01
|
SwiftDropdownSelectBoxOne/SwiftDropdownSelectBoxOne/DropDownSelectBox/DropDownSelectBox.swift
|
2
|
23773
|
//
// DropDownSelectBox.swift
// SwiftDropdownSelectBoxOne
//
// Created by NextDot on 2/2/16.
// Copyright © 2016 RzRasel. All rights reserved.
//
import Foundation
import UIKit
public typealias Index = Int
public typealias Closure = () -> Void
public typealias SelectionClosure = (Index, String) -> Void
public typealias ConfigurationClosure = (Index, String) -> String
private typealias ComputeLayoutTuple = (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat)
/// A Material Design drop down in replacement for `UIPickerView`.
public final class DropDownSelectBox: UIView {
//TODO: handle iOS 7 landscape mode
/// The dismiss mode for a drop down.
public enum DismissMode {
/// A tap outside the drop down is required to dismiss.
case OnTap
/// No tap is required to dismiss, it will dimiss when interacting with anything else.
case Automatic
/// Not dismissable by the user.
case Manual
}
/// The direction where the drop down will show from the `anchorView`.
public enum Direction {
/// The drop down will show below the anchor view when possible, otherwise above if there is more place than below.
case Any
/// The drop down will show above the anchor view or will not be showed if not enough space.
case Top
/// The drop down will show below or will not be showed if not enough space.
case Bottom
}
//MARK: - Properties
/// The current visible drop down. There can be only one visible drop down at a time.
public static weak var VisibleDropDown: DropDownSelectBox?
//MARK: UI
private let dismissableView = UIView()
private let tableViewContainer = UIView()
private let tableView = UITableView()
/// The view to which the drop down will displayed onto.
public weak var anchorView: UIView? {
didSet { setNeedsUpdateConstraints() }
}
/**
The possible directions where the drop down will be showed.
See `Direction` enum for more info.
*/
public var direction = Direction.Any
/**
The offset point relative to `anchorView` when the drop down is shown above the anchor view.
By default, the drop down is showed onto the `anchorView` with the top
left corner for its origin, so an offset equal to (0, 0).
You can change here the default drop down origin.
*/
public var topOffset: CGPoint = CGPointZero {
didSet { setNeedsUpdateConstraints() }
}
/**
The offset point relative to `anchorView` when the drop down is shown below the anchor view.
By default, the drop down is showed onto the `anchorView` with the top
left corner for its origin, so an offset equal to (0, 0).
You can change here the default drop down origin.
*/
public var bottomOffset: CGPoint = CGPointZero {
didSet { setNeedsUpdateConstraints() }
}
/**
The width of the drop down.
Defaults to `anchorView.bounds.width - offset.x`.
*/
public var width: CGFloat? {
didSet { setNeedsUpdateConstraints() }
}
//MARK: Constraints
private var heightConstraint: NSLayoutConstraint!
private var widthConstraint: NSLayoutConstraint!
private var xConstraint: NSLayoutConstraint!
private var yConstraint: NSLayoutConstraint!
//MARK: Appearance
public override var backgroundColor: UIColor? {
get { return tableView.backgroundColor }
set { tableView.backgroundColor = newValue }
}
/**
The background color of the selected cell in the drop down.
Changing the background color automatically reloads the drop down.
*/
public dynamic var selectionBackgroundColor = DPDSBConstant.UI.SelectionBackgroundColor {
didSet { reloadAllComponents() }
}
/**
The color of the text for each cells of the drop down.
Changing the text color automatically reloads the drop down.
*/
public dynamic var textColor = UIColor.blackColor() {
didSet { reloadAllComponents() }
}
/**
The font of the text for each cells of the drop down.
Changing the text font automatically reloads the drop down.
*/
public dynamic var textFont = UIFont.systemFontOfSize(15) {
didSet { reloadAllComponents() }
}
//MARK: Content
/**
The data source for the drop down.
Changing the data source automatically reloads the drop down.
*/
public var dataSource = [String]() {
didSet { reloadAllComponents() }
}
private var selectedRowIndex: Index?
/**
The format for the cells' text.
By default, the cell's text takes the plain `dataSource` value.
Changing `cellConfiguration` automatically reloads the drop down.
*/
public var cellConfiguration: ConfigurationClosure? {
didSet { reloadAllComponents() }
}
/// The action to execute when the user selects a cell.
public var selectionAction: SelectionClosure?
/// The action to execute when the user cancels/hides the drop down.
public var cancelAction: Closure?
/// The dismiss mode of the drop down. Default is `OnTap`.
public var dismissMode = DismissMode.OnTap {
willSet {
if newValue == .OnTap {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissableViewTapped")
dismissableView.addGestureRecognizer(gestureRecognizer)
} else if let gestureRecognizer = dismissableView.gestureRecognizers?.first {
dismissableView.removeGestureRecognizer(gestureRecognizer)
}
}
}
private var minHeight: CGFloat {
return tableView.rowHeight
}
private var didSetupConstraints = false
//MARK: - Init's
deinit {
stopListeningToNotifications()
}
/**
Creates a new instance of a drop down.
Don't forget to setup the `dataSource`,
the `anchorView` and the `selectionAction`
at least before calling `show()`.
*/
public convenience init() {
self.init(frame: CGRectZero)
}
/**
Creates a new instance of a drop down.
- parameter anchorView: The view to which the drop down will displayed onto.
- parameter selectionAction: The action to execute when the user selects a cell.
- parameter dataSource: The data source for the drop down.
- parameter topOffset: The offset point relative to `anchorView` used when drop down is displayed on above the anchor view.
- parameter bottomOffset: The offset point relative to `anchorView` used when drop down is displayed on below the anchor view.
- parameter cellConfiguration: The format for the cells' text.
- parameter cancelAction: The action to execute when the user cancels/hides the drop down.
- returns: A new instance of a drop down customized with the above parameters.
*/
public convenience init(anchorView: UIView, selectionAction: SelectionClosure? = nil, dataSource: [String] = [], topOffset: CGPoint? = nil, bottomOffset: CGPoint? = nil, cellConfiguration: ConfigurationClosure? = nil, cancelAction: Closure? = nil) {
self.init(frame: CGRectZero)
self.anchorView = anchorView
self.selectionAction = selectionAction
self.dataSource = dataSource
self.topOffset = topOffset ?? CGPointZero
self.bottomOffset = bottomOffset ?? CGPointZero
self.cellConfiguration = cellConfiguration
self.cancelAction = cancelAction
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
//MARK: - Setup
private extension DropDownSelectBox {
func setup() {
updateConstraintsIfNeeded()
setupUI()
dismissMode = .OnTap
tableView.delegate = self
tableView.dataSource = self
tableView.registerNib(DropDownSelectBoxCell.Nib, forCellReuseIdentifier: DPDSBConstant.ReusableIdentifier.DropDownSelectBoxCell)
startListeningToKeyboard()
}
func setupUI() {
super.backgroundColor = UIColor.clearColor()
tableViewContainer.layer.masksToBounds = false
tableViewContainer.layer.cornerRadius = DPDSBConstant.UI.CornerRadius
tableViewContainer.layer.shadowColor = DPDSBConstant.UI.Shadow.Color
tableViewContainer.layer.shadowOffset = DPDSBConstant.UI.Shadow.Offset
tableViewContainer.layer.shadowOpacity = DPDSBConstant.UI.Shadow.Opacity
tableViewContainer.layer.shadowRadius = DPDSBConstant.UI.Shadow.Radius
setupTableViewUI()
setHiddentState()
hidden = true
}
func setupTableViewUI() {
backgroundColor = DPDSBConstant.UI.BackgroundColor
tableView.rowHeight = DPDSBConstant.UI.RowHeight
tableView.separatorColor = DPDSBConstant.UI.SeparatorColor
tableView.separatorStyle = DPDSBConstant.UI.SeparatorStyle
tableView.separatorInset = DPDSBConstant.UI.SeparatorInsets
tableView.layer.cornerRadius = DPDSBConstant.UI.CornerRadius
tableView.layer.masksToBounds = true
}
}
//MARK: - UI
extension DropDownSelectBox {
public override func updateConstraints() {
if !didSetupConstraints {
setupConstraints()
}
didSetupConstraints = true
let layout = computeLayout()
if !layout.canBeDisplayed {
super.updateConstraints()
hide()
return
}
xConstraint.constant = layout.x
yConstraint.constant = layout.y
widthConstraint.constant = layout.width
heightConstraint.constant = layout.visibleHeight
tableView.scrollEnabled = layout.offscreenHeight > 0
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.tableView.flashScrollIndicators()
}
super.updateConstraints()
}
private func setupConstraints() {
translatesAutoresizingMaskIntoConstraints = false
// Dismissable view
addSubview(dismissableView)
dismissableView.translatesAutoresizingMaskIntoConstraints = false
addUniversalConstraints(format: "|[dismissableView]|", views: ["dismissableView": dismissableView])
// Table view container
addSubview(tableViewContainer)
tableViewContainer.translatesAutoresizingMaskIntoConstraints = false
xConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .Leading,
relatedBy: .Equal,
toItem: self,
attribute: .Leading,
multiplier: 1,
constant: 0)
addConstraint(xConstraint)
yConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .Top,
relatedBy: .Equal,
toItem: self,
attribute: .Top,
multiplier: 1,
constant: 0)
addConstraint(yConstraint)
widthConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 0)
tableViewContainer.addConstraint(widthConstraint)
heightConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 0)
tableViewContainer.addConstraint(heightConstraint)
// Table view
tableViewContainer.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableViewContainer.addUniversalConstraints(format: "|[tableView]|", views: ["tableView": tableView])
}
public override func layoutSubviews() {
super.layoutSubviews()
// When orientation changes, layoutSubviews is called
// We update the constraint to update the position
setNeedsUpdateConstraints()
let shadowPath = UIBezierPath(rect: tableViewContainer.bounds)
tableViewContainer.layer.shadowPath = shadowPath.CGPath
}
private func computeLayout() -> (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat, visibleHeight: CGFloat, canBeDisplayed: Bool, Direction: Direction) {
var layout: ComputeLayoutTuple = (0, 0, 0, 0)
var direction = self.direction
if let window = UIWindow.visibleWindow() {
switch direction {
case .Any:
layout = computeLayoutBottomDisplay(window: window)
direction = .Bottom
if layout.offscreenHeight > 0 {
let topLayout = computeLayoutForTopDisplay(window: window)
if topLayout.offscreenHeight < layout.offscreenHeight {
layout = topLayout
direction = .Top
}
}
case .Bottom:
layout = computeLayoutBottomDisplay(window: window)
direction = .Bottom
case .Top:
layout = computeLayoutForTopDisplay(window: window)
direction = .Top
}
}
let visibleHeight = tableHeight - layout.offscreenHeight
let canBeDisplayed = visibleHeight >= minHeight
return (layout.x, layout.y, layout.width, layout.offscreenHeight, visibleHeight, canBeDisplayed, direction)
}
private func computeLayoutBottomDisplay(window window: UIWindow) -> ComputeLayoutTuple {
var offscreenHeight: CGFloat = 0
let anchorViewX = (anchorView?.windowFrame?.minX ?? 0)
let anchorViewY = (anchorView?.windowFrame?.minY ?? 0)
let x = anchorViewX + bottomOffset.x
let y = anchorViewY + bottomOffset.y
let maxY = y + tableHeight
let windowMaxY = window.bounds.maxY - DPDSBConstant.UI.HeightPadding
let keyboardListener = DPDSBKeyboardListener.sharedInstance
let keyboardMinY = keyboardListener.keyboardFrame.minY - DPDSBConstant.UI.HeightPadding
if keyboardListener.isVisible && maxY > keyboardMinY {
offscreenHeight = abs(maxY - keyboardMinY)
} else if maxY > windowMaxY {
offscreenHeight = abs(maxY - windowMaxY)
}
let width = self.width ?? (anchorView?.bounds.width ?? 0) - bottomOffset.x
return (x, y, width, offscreenHeight)
}
private func computeLayoutForTopDisplay(window window: UIWindow) -> ComputeLayoutTuple {
var offscreenHeight: CGFloat = 0
let anchorViewX = (anchorView?.windowFrame?.minX ?? 0)
let anchorViewMaxY = (anchorView?.windowFrame?.maxY ?? 0)
let x = anchorViewX + topOffset.x
var y = (anchorViewMaxY + topOffset.y) - tableHeight
let windowY = window.bounds.minY + DPDSBConstant.UI.HeightPadding
if y < windowY {
offscreenHeight = abs(y - windowY)
y = windowY
}
let width = self.width ?? (anchorView?.bounds.width ?? 0) - topOffset.x
return (x, y, width, offscreenHeight)
}
}
//MARK: - Actions
extension DropDownSelectBox {
/**
Shows the drop down if enough height.
- returns: Wether it succeed and how much height is needed to display all cells at once.
*/
public func show() -> (canBeDisplayed: Bool, offscreenHeight: CGFloat?) {
if self == DropDownSelectBox.VisibleDropDown {
return (true, 0)
}
if let visibleDropDown = DropDownSelectBox.VisibleDropDown {
visibleDropDown.cancel()
}
DropDownSelectBox.VisibleDropDown = self
setNeedsUpdateConstraints()
let visibleWindow = UIWindow.visibleWindow()
visibleWindow?.addSubview(self)
visibleWindow?.bringSubviewToFront(self)
self.translatesAutoresizingMaskIntoConstraints = false
visibleWindow?.addUniversalConstraints(format: "|[dropDown]|", views: ["dropDown": self])
let layout = computeLayout()
if !layout.canBeDisplayed {
hide()
return (layout.canBeDisplayed, layout.offscreenHeight)
}
hidden = false
tableViewContainer.transform = DPDSBConstant.Animation.DownScaleTransform
UIView.animateWithDuration(
DPDSBConstant.Animation.Duration,
delay: 0,
options: DPDSBConstant.Animation.EntranceOptions,
animations: { [unowned self] in
self.setShowedState()
},
completion: nil)
selectRowAtIndex(selectedRowIndex)
return (layout.canBeDisplayed, layout.offscreenHeight)
}
/// Hides the drop down.
public func hide() {
if self == DropDownSelectBox.VisibleDropDown {
/*
If one drop down is showed and another one is not
but we call `hide()` on the hidden one:
we don't want it to set the `VisibleDropDown` to nil.
*/
DropDownSelectBox.VisibleDropDown = nil
}
if hidden {
return
}
UIView.animateWithDuration(
DPDSBConstant.Animation.Duration,
delay: 0,
options: DPDSBConstant.Animation.ExitOptions,
animations: { [unowned self] in
self.setHiddentState()
},
completion: { [unowned self] finished in
self.hidden = true
self.removeFromSuperview()
})
}
private func cancel() {
hide()
cancelAction?()
}
private func setHiddentState() {
alpha = 0
}
private func setShowedState() {
alpha = 1
tableViewContainer.transform = CGAffineTransformIdentity
}
}
//MARK: - UITableView
extension DropDownSelectBox {
/**
Reloads all the cells.
It should not be necessary in most cases because each change to
`dataSource`, `textColor`, `textFont`, `selectionBackgroundColor`
and `cellConfiguration` implicitly calls `reloadAllComponents()`.
*/
public func reloadAllComponents() {
if #available(iOS 9, *) {
setupTableViewUI()
}
tableView.reloadData()
setNeedsUpdateConstraints()
}
/// (Pre)selects a row at a certain index.
public func selectRowAtIndex(index: Index?) {
if let index = index {
tableView.selectRowAtIndexPath(
NSIndexPath(forRow: index, inSection: 0),
animated: false,
scrollPosition: .Middle)
} else {
deselectRowAtIndexPath(selectedRowIndex)
}
selectedRowIndex = index
}
public func deselectRowAtIndexPath(index: Index?) {
selectedRowIndex = nil
guard let index = index
where index > 0
else { return }
tableView.deselectRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0), animated: true)
}
/// Returns the index of the selected row.
public var indexForSelectedRow: Index? {
return tableView.indexPathForSelectedRow?.row
}
/// Returns the selected item.
public var selectedItem: String? {
guard let row = tableView.indexPathForSelectedRow?.row else { return nil }
return dataSource[row]
}
/// Returns the height needed to display all cells.
private var tableHeight: CGFloat {
return tableView.rowHeight * CGFloat(dataSource.count)
}
}
//MARK: - UITableViewDataSource - UITableViewDelegate
extension DropDownSelectBox: UITableViewDataSource, UITableViewDelegate {
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(DPDSBConstant.ReusableIdentifier.DropDownSelectBoxCell, forIndexPath: indexPath) as! DropDownSelectBoxCell
cell.optionLabel.textColor = textColor
cell.optionLabel.font = textFont
cell.selectedBackgroundColor = selectionBackgroundColor
if let cellConfiguration = cellConfiguration {
let index = indexPath.row
cell.optionLabel.text = cellConfiguration(index, dataSource[index])
} else {
cell.optionLabel.text = dataSource[indexPath.row]
}
return cell
}
public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.selected = indexPath.row == selectedRowIndex
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedRowIndex = indexPath.row
selectionAction?(selectedRowIndex!, dataSource[selectedRowIndex!])
hide()
}
}
//MARK: - Auto dismiss
extension DropDownSelectBox {
public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let view = super.hitTest(point, withEvent: event)
if dismissMode == .Automatic && view === dismissableView {
cancel()
return nil
} else {
return view
}
}
@objc
private func dismissableViewTapped() {
cancel()
}
}
//MARK: - Keyboard events
extension DropDownSelectBox {
/**
Starts listening to keyboard events.
Allows the drop down to display correctly when keyboard is showed.
*/
public static func startListeningToKeyboard() {
DPDSBKeyboardListener.sharedInstance.startListeningToKeyboard()
}
private func startListeningToKeyboard() {
DPDSBKeyboardListener.sharedInstance.startListeningToKeyboard()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardUpdate",
name: UIKeyboardDidShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "keyboardUpdate",
name: UIKeyboardDidHideNotification,
object: nil)
}
private func stopListeningToNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@objc
private func keyboardUpdate() {
self.setNeedsUpdateConstraints()
}
}
|
apache-2.0
|
e86fb8f539e23a448849135653ec5df4
| 31.476776 | 253 | 0.620604 | 5.606604 | false | false | false | false |
Tornquist/cocoaconfappextensionsclass
|
CocoaConf App Extensions Class/CocoaConfExtensions_06_Action+JavaScript_End/CocoaConf Today/TodayViewController.swift
|
1
|
2953
|
//
// TodayViewController.swift
// CocoaConf Today
//
// Created by Chris Adamson on 3/25/15.
// Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved.
//
import UIKit
import NotificationCenter
import CocoaConfFramework
class TodayViewController: UIViewController, NCWidgetProviding {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
let confs = cocoaConf2015Events
var previousLabel : UILabel? = nil
for (index, conf) in confs.enumerate() {
let label = UILabel ()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "\(conf.cityName): \(conf.relativeTime().rawValue)"
label.textColor = UIColor.whiteColor()
self.view?.addSubview(label)
let xConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|-5-[label]-5-|",
options: [] as NSLayoutFormatOptions,
metrics: nil,
views: ["label" : label])
self.view.addConstraints(xConstraints)
var yConstraints : [NSLayoutConstraint]? = nil
if index == 0 {
// first row
yConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[label]",
options: [] as NSLayoutFormatOptions,
metrics: nil,
views: ["label" : label])
} else if index == confs.count - 1 {
// last row
yConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[previousLabel]-[label]",
options: [] as NSLayoutFormatOptions,
metrics: nil,
views: ["previousLabel" : previousLabel!, "label" : label])
yConstraints?.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:[label]-0-|",
options: [] as NSLayoutFormatOptions,
metrics: nil,
views: ["label" : label]))
} else {
// middle row
yConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[previousLabel]-[label]",
options: [] as NSLayoutFormatOptions,
metrics: nil,
views: ["previousLabel" : previousLabel!, "label" : label])
}
self.view.addConstraints(yConstraints!)
previousLabel = label
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NewData)
}
}
|
cc0-1.0
|
b12fff2ef4c604d856f4465838d2db87
| 36.858974 | 110 | 0.623095 | 5.189807 | false | false | false | false |
carabina/Lantern
|
LanternModel/ModelManager.swift
|
1
|
4255
|
//
// ModelManager.swift
// Hoverlytics
//
// Created by Patrick Smith on 31/03/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Foundation
import BurntFoundation
import BurntList
enum RecordType: String {
case Site = "Site"
var identifier: String {
return self.rawValue
}
}
public enum ModelManagerNotification: String {
case AllSitesDidChange = "LanternModel.ModelManager.AllSitesDidChangeNotification"
public var notificationName: String {
return self.rawValue
}
}
public class ErrorReceiver {
public var errorCallback: ((error: NSError) -> Void)?
func receiveError(error: NSError) {
errorCallback?(error: error)
}
}
public class ModelManager {
var isAvailable = false
public let errorReceiver = ErrorReceiver()
private var storeDirectory: SystemDirectory
private var sitesList: ArrayList<SiteValues>?
private var sitesListStore: ListJSONFileStore<ArrayList<SiteValues>>?
private var sitesListObserver: ListObserverOf<SiteValues>!
public var allSites: [SiteValues]? {
return sitesList?.allItems
}
init() {
sitesList = ArrayList(items: [SiteValues]())
let listJSONTransformer = DictionaryKeyJSONTransformer(dictionaryKey: "items", objectCoercer: { (value: [AnyObject]) in
value as NSArray
})
let storeOptions = ListJSONFileStoreOptions(listJSONTransformer: listJSONTransformer)
storeDirectory = SystemDirectory(pathComponents: ["v1"], inUserDirectory: .ApplicationSupportDirectory, errorReceiver: errorReceiver.receiveError, useBundleIdentifier: true)
storeDirectory.useOnQueue(dispatch_get_main_queue()) { directoryURL in
let JSONURL = directoryURL.URLByAppendingPathComponent("sites.json")
let store = ListJSONFileStore(creatingList: { items in
return ArrayList<SiteValues>(items: items)
}, loadedFromURL: JSONURL, options: storeOptions)
store.ensureLoaded{ (list, error) in
if let list = list {
list.addObserver(self.sitesListObserver)
self.sitesList = list
self.notifyAllSitesDidChange()
}
}
self.sitesListStore = store
}
sitesListObserver = ListObserverOf<SiteValues> { [unowned self] changes in
self.notifyAllSitesDidChange()
}
}
deinit {
let nc = NSNotificationCenter.defaultCenter()
}
public class var sharedManager: ModelManager {
struct Helper {
static let sharedManager = ModelManager()
}
return Helper.sharedManager
}
func onSystemDirectoryError(error: NSError) {
}
func updateMainProperties() {
}
private func mainQueue_notify(identifier: ModelManagerNotification, userInfo: [String:AnyObject]? = nil) {
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(identifier.notificationName, object: self, userInfo: userInfo)
}
func notifyAllSitesDidChange() {
self.mainQueue_notify(.AllSitesDidChange)
}
public func createSiteWithValues(siteValues: SiteValues) {
sitesList?.appendItems([siteValues])
}
private var sitesListUUIDIndexFinder: PrimaryIndexIterativeFinder<Int, SiteValues, NSUUID>? {
if let sitesList = sitesList {
let UUIDExtractor = ItemValueExtractorOf { (item: SiteValues) in
return item.UUID
}
return PrimaryIndexIterativeFinder(collectionAccessor: { sitesList }, valueExtractor: UUIDExtractor)
}
else {
return nil
}
}
private var sitesListEditableAssistant: EditableListFinderAssistant<ArrayList<SiteValues>, PrimaryIndexIterativeFinder<Int, SiteValues, NSUUID>>? {
if let sitesList = sitesList {
let UUIDExtractor = ItemValueExtractorOf { (item: SiteValues) in
return item.UUID
}
let sitesListUUIDIndexFinder = PrimaryIndexIterativeFinder(collectionAccessor: { sitesList }, valueExtractor: UUIDExtractor)
return EditableListFinderAssistant(list: sitesList, primaryIndexFinder: sitesListUUIDIndexFinder)
}
else {
return nil
}
}
public func updateSiteWithUUID(UUID: NSUUID, withValues siteValues: SiteValues) {
//sitesListEditableAssistant?.replaceItemWhoseValueIs(UUID, with: siteValues)
if let index = sitesListUUIDIndexFinder?[UUID] {
sitesList?.replaceItemAtIndex(index, with: siteValues)
}
}
public func removeSiteWithUUID(UUID: NSUUID) {
sitesListEditableAssistant?.removeItemsWithValues(Set([UUID]))
}
}
|
apache-2.0
|
c582bc0c828e9631824e23cbdb63818b
| 26.451613 | 175 | 0.755817 | 3.875228 | false | false | false | false |
DiabetesCompass/Diabetes_Compass
|
BGCompass/TrendsAlgorithmModelExtension.swift
|
1
|
7972
|
//
// TrendsAlgorithmModelExtension.swift
// BGCompass
//
// Created by Steve Baker on 12/11/16.
// Copyright © 2016 Clif Alferness. All rights reserved.
//
import Foundation
/** Swift extension can extend a Swift class or an Objective C class
http://ctarda.com/2016/05/swift-extensions-can-be-applied-to-objective-c-types/
If this was a class would add @objc, but apparently
for an extension this annotation is not needed or allowed
*/
extension TrendsAlgorithmModel {
// 100 days in seconds = days * hours/day * minutes/hour * seconds/minute
public static let hemoglobinLifespanSeconds: TimeInterval = 100 * 24 * 60 * 60;
// MARK: get readings
/**
Creates [BGReadingLight] from [BGReading]
- returns: array of BGReadingLight.
returns empty array [] if bgReadings is empty.
*/
class func bgReadingLights(bgReadings: [BGReading]) -> [BGReadingLight] {
var bgLights: [BGReadingLight] = []
for bgReading in bgReadings {
let bgReadingLight = BGReadingLight(bgReading: bgReading)
bgLights.append(bgReadingLight)
}
return bgLights
}
/**
- returns: first reading in blood glucose array, else nil
based on index, not date
*/
func bgArrayReadingFirst() -> BGReading? {
return self.getFromBGArray(0)
}
/**
- returns: last element in blood glucose array, else nil
based on index, not date
*/
func bgArrayReadingLast() -> BGReading? {
if self.bgArrayCount() == 0 {
return nil
} else {
let index = UInt(self.bgArrayCount()) - 1
return self.getFromBGArray(index)
}
}
/**
- returns: first reading in HA1c array, else nil
based on index, not date
*/
func ha1cArrayReadingFirst() -> Ha1cReading? {
return self.getFromHa1cArray(0)
}
/**
- returns: last reading in HA1c array, else nil
based on index, not date
*/
func ha1cArrayReadingLast() -> Ha1cReading? {
if self.ha1cArrayCount() == 0 {
return nil
} else {
let index = UInt(self.ha1cArrayCount()) - 1
return self.getFromHa1cArray(index)
}
}
/**
- returns: readings between startDate (inclusive) and endDate (inclusive)
*/
// func bloodGlucoseReadings(_ readings: [BGReading],
// startDate: Date,
// endDate: Date) -> [BGReading] {
//
// // Swift 3 Date is a struct, implements comparable, can be compared using < >
// // NSDate is an object.
// // Need to use something like comparisonResult .orderedAscending
// // Using < on NSDate would compare memory addresses.
// // http://stackoverflow.com/questions/26198526/nsdate-comparison-using-swift#28109990
// let readingsBetweenDates = readings
// .filter( { ($0.timeStamp != nil)
// && ($0.timeStamp >= startDate)
// && ($0.timeStamp <= endDate) } )
// return readingsBetweenDates
// }
// MARK: -
/**
- parameter bgReadings: blood glucose readings to average. quantity units mmol/L
readings may appear in any chronological order, the method reads their timeStamp
- parameter date: date for ha1cValue. Blood glucose readings after date are ignored.
- parameter decayLifeSeconds: time for blood glucose from a reading to decay to 0.0.
Typically hemoglobin lifespan seconds.
- returns: ha1c value based on average of decayed BG reading.quantity
*/
class func ha1cValueForBgReadings(_ bgReadings: [BGReading],
date: Date,
decayLifeSeconds: TimeInterval) -> Float {
// create [BGReadingLight] from [BGReading]
let bgReadingLights = TrendsAlgorithmModel.bgReadingLights(bgReadings: bgReadings)
let averageDecayedBG = TrendsAlgorithmModel.averageDecayedBGReadingQuantity(bgReadingLights,
date: date,
decayLifeSeconds: decayLifeSeconds)
let ha1cValue = hA1c(bloodGlucoseMmolPerL: averageDecayedBG)
return ha1cValue
}
/**
This method uses BGReadingLight, and may be tested without a CoreData context.
- parameter bgReadingLights: BGReadingLight readings to average.
readings may appear in any chronological order, the method reads their timeStamp
- parameter date: date for quantity. Blood glucose readings after date are ignored.
- parameter decayLifeSeconds: time for blood glucose from a reading to decay to 0.0.
Typically hemoglobin lifespan seconds.
- returns: average of decayed BG reading.quantity
*/
class func averageDecayedBGReadingQuantity(_ bgReadingLights: [BGReadingLight],
date: Date,
decayLifeSeconds: TimeInterval) -> Float {
if bgReadingLights.count == 0 {
return 0.0
}
var sumOfWeightedBgReadings: Float = 0.0
var sumOfWeights: Float = 0.0
for bgReadingLight in bgReadingLights {
if bgReadingLight.timeStamp > date {
// skip this reading, continue loop
continue
}
let weight = TrendsAlgorithmModel.weightLinearDecayFirstDate(bgReadingLight.timeStamp,
secondDate: date,
decayLifeSeconds: decayLifeSeconds)
sumOfWeightedBgReadings += weight * bgReadingLight.quantity
sumOfWeights += weight
}
// avoid potential divide by 0
if sumOfWeights == 0 {
return 0.0
}
let average = sumOfWeightedBgReadings / sumOfWeights
print("averageDecayedBGReadingQuantity \(average)")
return average
}
/**
weight that decreases linearly from 1 to 0 as firstDate decreases from secondDate to (secondDate - decayLifeSeconds).
- parameter firstDate: date at which weight is calculated
- parameter secondDate: Occurs after firstDate. At this date or later weight is 1.0
- parameter decayLifeSeconds: time for weight to decay to 0.0. Typically hemoglobin lifespan seconds.
- returns: weight from 0.0 to 1.0 inclusive.
returns 0.0 if firstDate is decayLifeSeconds or more before secondDate
returns 1.0 if firstDate is on or after secondDate
*/
class func weightLinearDecayFirstDate(_ firstDate: Date, secondDate: Date, decayLifeSeconds: TimeInterval) -> Float {
let timeIntervalSecondDateSinceFirst = secondDate.timeIntervalSince(firstDate)
var weight: Float = 0.0;
if timeIntervalSecondDateSinceFirst >= decayLifeSeconds {
// firstDate is decayLifeSeconds or more before secondDate
weight = 0.0;
} else if timeIntervalSecondDateSinceFirst <= 0 {
// firstDate is on or after secondDate
weight = 1.0
} else {
weight = Float(1.0 - (timeIntervalSecondDateSinceFirst/decayLifeSeconds))
}
return weight
}
/**
Ha1c units are percent of hemoglobin that is glycated.
Generally physiologic HA1c is >= 5.
5 represents 5%, or 0.05
https://en.wikipedia.org/wiki/Glycated_hemoglobin
- parameter bloodGlucoseMmolPerL: blood glucose quantity, units mmol/L
- returns: HA1c in DCCT percentage
*/
class func hA1c(bloodGlucoseMmolPerL: Float) -> Float {
let bloodGlucoseMgPerDl = bloodGlucoseMmolPerL * MG_PER_DL_PER_MMOL_PER_L
let hA1cFromBg = (bloodGlucoseMgPerDl + 46.7) / 28.7
return hA1cFromBg
}
}
|
mit
|
d80adfd49440427eb708cba4ed208849
| 37.322115 | 122 | 0.614979 | 4.483127 | false | false | false | false |
rvald/Wynfood.iOS
|
Wynfood/RestaurantService.swift
|
1
|
3760
|
//
// RestaurantService.swift
// Wynfood
//
// Created by craftman on 4/18/17.
// Copyright © 2017 craftman. All rights reserved.
//
import Foundation
import MapKit
class RestaurantService {
// MARK: - Properties
private var restaurants = [Restaurant]()
private var restaurantCache = [Restaurant]()
// MARK: - Methods
func restaurant(by id: Int) -> Restaurant {
return restaurants.first(where: { $0.id == id })!
}
func parseData() {
let bundle = Bundle.main
let path = bundle.path(forResource: "restaurants", ofType: "json")
if let path = path {
let url = URL(fileURLWithPath: path)
let data = NSData(contentsOf: url)
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data as Data, options: []) as! Dictionary<String, AnyObject>
let restaurantObjects = json["restaurants"] as! [Dictionary<String, AnyObject>]
for object in restaurantObjects {
guard let id = object["id"],
let name = object["name"],
let address = object["address"],
let phone = object["phone"],
let cuisine = object["cuisine"],
let website = object["website"],
let latitude = object["lat"],
let longitude = object["long"],
let description = object["description"]
else {
return
}
let aRestaurant = Restaurant(id: id as! Int,
name: name as! String,
address: address as! String,
phone: phone as! String,
cuisine: cuisine as! String,
website: website as! String,
latitude: latitude as! Double,
longitude: longitude as! Double,
distance: "",
description: description as! String)
add(restaurant: aRestaurant)
}
} catch {
return
}
}
} else {
return
}
}
func allRestaurants() -> [Restaurant] {
return restaurants
}
func add(restaurant: Restaurant) {
restaurants.append(restaurant)
}
func cacheDistance(restaurant: Restaurant) {
restaurantCache.append(restaurant)
}
func distanceForRestaurant(name: String) -> Restaurant? {
return cachedRestaurants().first(where: { $0.name == name })
}
func cachedRestaurants() -> [Restaurant] {
return restaurantCache
}
func deleteCache() {
restaurantCache = [Restaurant]()
}
}
|
apache-2.0
|
43f65a3181812fbdc041a0101d0f5637
| 30.066116 | 130 | 0.386007 | 6.772973 | false | false | false | false |
exponent/exponent
|
ios/versioned/sdk44/ExpoModulesCore/Swift/EventListener.swift
|
2
|
1674
|
/**
Represents a listener for the specific event.
*/
internal struct EventListener: AnyDefinition {
let name: EventName
let call: (Any?, Any?) throws -> Void
/**
Listener initializer for events without sender and payload.
*/
init(_ name: EventName, _ listener: @escaping () -> Void) {
self.name = name
self.call = { (sender, payload) in listener() }
}
/**
Listener initializer for events with no payload.
*/
init<Sender>(_ name: EventName, _ listener: @escaping (Sender) -> Void) {
self.name = name
self.call = { (sender, payload) in
guard let sender = sender as? Sender else {
throw InvalidSenderTypeError(eventName: name, senderType: Sender.self)
}
listener(sender)
}
}
/**
Listener initializer for events that specify the payload.
*/
init<Sender, PayloadType>(_ name: EventName, _ listener: @escaping (Sender, PayloadType?) -> Void) {
self.name = name
self.call = { (sender, payload) in
guard let sender = sender as? Sender else {
throw InvalidSenderTypeError(eventName: name, senderType: Sender.self)
}
listener(sender, payload as? PayloadType)
}
}
}
struct InvalidSenderTypeError: CodedError {
var eventName: EventName
var senderType: Any.Type
var description: String {
"Sender for event `\(eventName)` must be of type `\(senderType)`."
}
}
public enum EventName: Equatable {
case custom(_ name: String)
// MARK: Module lifecycle
case moduleCreate
case moduleDestroy
case appContextDestroys
// MARK: App (UIApplication) lifecycle
case appEntersForeground
case appBecomesActive
case appEntersBackground
}
|
bsd-3-clause
|
d542754072e240fc67588aa9468795db
| 24.753846 | 102 | 0.669654 | 4.072993 | false | false | false | false |
Holmusk/HMRequestFramework-iOS
|
HMRequestFramework-FullDemo/AppDelegate.swift
|
1
|
2761
|
//
// AppDelegate.swift
// HMRequestFramework-FullDemo
//
// Created by Hai Pham on 17/1/18.
// Copyright © 2018 Holmusk. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let provider = Singleton.instance
let topVC = (window?.rootViewController as? NavigationVC)!
let navigator = NavigationService(topVC)
let vm = NavigationViewModel(provider, navigator)
topVC.viewModel = vm
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive
// state. This can occur for certain types of temporary interruptions
// (such as an incoming phone call or SMS message) or when the user
// quits the application and it begins the transition to the background
// state.
// Use this method to pause ongoing tasks, disable timers, and invalidate
// graphics rendering callbacks. Games should use this method to pause
// the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate
// timers, and store enough application state information to restore
// your application to its current state in case it is terminated later.
//
// If your application supports background execution, this method is
// called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active
// state; here you can undo many of the changes made on entering the
// background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the
// application was inactive. If the application was previously in the
// background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if
// appropriate. See also applicationDidEnterBackground:.
//
// Saves changes in the application's managed object context before the
// application terminates.
}
}
|
apache-2.0
|
977cfea0f0e7b8a550c614a92d5afd8e
| 40.19403 | 114 | 0.689493 | 5.667351 | false | false | false | false |
rlopezdiez/RLDTableViewSwift
|
Sample app/TableViewPrototype/View controllers/RLDMasterViewController.swift
|
1
|
1350
|
import UIKit
class RLDMasterViewController: RLDTableViewController {
let modelProvider = RLDTableViewModelProvider()
override func viewDidLoad() {
super.viewDidLoad()
registerNibs()
registerEventHandlers()
setTableViewModel()
attachEditButton()
}
private func registerNibs() {
for (reuseIdentifier, nibName) in modelProvider.headerFooterReuseIdentifiersToNibNames {
let nib = UINib(nibName:reuseIdentifier, bundle:nil)
tableView?.registerNib(nib, forHeaderFooterViewReuseIdentifier:nibName)
}
}
private func registerEventHandlers() {
RLDGenericTableViewCellEventHandler.register()
RLDTableViewHeaderViewEventHandler.register()
}
private func setTableViewModel() {
tableViewModel = modelProvider.tableViewModel
}
private func attachEditButton() {
navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func setEditing(editing:Bool, animated:Bool) {
super.setEditing(editing, animated:animated)
navigationController?.hidesBarsOnSwipe = !editing
navigationController?.hidesBarsWhenVerticallyCompact = !editing
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
apache-2.0
|
3ba57c6d45f5eb514bb94aa6b002255d
| 28.369565 | 96 | 0.672593 | 5.869565 | false | false | false | false |
Torsten2217/PathDynamicModal
|
PathDynamicModal-Demo/ViewController.swift
|
1
|
3854
|
//
// ViewController.swift
// PathDynamicModal-Demo
//
// Created by Ryo Aoyama on 2/9/15.
// Copyright (c) 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var titleAndImages: [(String, UIImage)]! = []
override func viewDidLoad() {
super.viewDidLoad()
self.configure()
}
private func configure() {
self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(20.0), NSForegroundColorAttributeName: UIColor.whiteColor()]
self.tableView.registerNib(UINib(nibName: "ImageCell", bundle: nil), forCellReuseIdentifier: "imageCell")
self.tableView.delegate = self
self.tableView.dataSource = self
self.fillNavigationBar(color: UIColor(red: 252.0/255.0, green: 0, blue: 0, alpha: 1.0))
for i in 1...16 {
let imageName = "SampleImage\(i)"
let image = UIImage(named: "\(imageName).jpg")!
self.titleAndImages.append((imageName, image))
}
}
private func fillNavigationBar(#color: UIColor) {
if let nav = self.navigationController {
nav.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
nav.navigationBar.shadowImage = UIImage()
for view in nav.navigationBar.subviews {
if view.isKindOfClass(NSClassFromString("_UINavigationBarBackground")) {
if view.isKindOfClass(UIView) {
(view as UIView).backgroundColor = color
}
}
}
}
}
@IBAction func helloButton(sender: UIButton) {
let view = ModalView.instantiateFromNib()
let window = UIApplication.sharedApplication().delegate?.window??
let modal = PathDynamicModal()
modal.showMagnitude = 200.0
modal.closeMagnitude = 130.0
view.closeButtonHandler = {[weak modal] in
modal?.closeWithLeansRandom()
return
}
view.bottomButtonHandler = {[weak modal] in
modal?.closeWithLeansRandom()
return
}
modal.show(modalView: view, inView: window!)
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
let view = ImageModalView.instantiateFromNib()
view.image = self.titleAndImages[indexPath.item].1
let window = UIApplication.sharedApplication().delegate?.window??
let modal = PathDynamicModal.show(modalView: view, inView: window!)
view.closeButtonHandler = {[weak modal] in
modal?.closeWithLeansRandom()
return
}
view.bottomButtonHandler = {[weak modal] in
modal?.closeWithLeansRandom()
return
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80.0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.titleAndImages.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("imageCell", forIndexPath: indexPath) as ImageCell
let titleAndImage = self.titleAndImages[indexPath.item]
cell.title = titleAndImage.0
cell.sideImage = titleAndImage.1
return cell
}
}
|
mit
|
27e7dbc198c268e76a68a38d55e0c031
| 35.714286 | 181 | 0.638817 | 5.118194 | false | false | false | false |
carabina/AlecrimAsyncKit
|
Source/AlecrimAsyncKit/Convenience/Conditions/DelayTaskCondition.swift
|
1
|
1159
|
//
// DelayTaskCondition.swift
// AlecrimAsyncKit
//
// Created by Vanderlei Martinelli on 2015-08-04.
// Copyright (c) 2015 Alecrim. All rights reserved.
//
import Foundation
public final class DelayTaskCondition: TaskCondition {
public init(timeInterval: NSTimeInterval, tolerance: NSTimeInterval = 0) {
super.init(subconditions: nil, dependencyTask: nil) { result in
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
let intervalInNanoseconds = Int64(timeInterval * NSTimeInterval(NSEC_PER_SEC))
let toleranceInNanoseconds = Int64(tolerance * NSTimeInterval(NSEC_PER_SEC))
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, intervalInNanoseconds), UInt64(intervalInNanoseconds), UInt64(toleranceInNanoseconds))
dispatch_source_set_event_handler(timer) {
dispatch_source_cancel(timer)
result(.Satisfied)
}
dispatch_resume(timer)
}
}
}
|
mit
|
7d196ef45bbe3805c905a0914b861506
| 35.25 | 164 | 0.642796 | 4.440613 | false | false | false | false |
naithar/Kitura
|
Sources/Kitura/Router.swift
|
1
|
16293
|
/*
* Copyright IBM Corporation 2015
*
* 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 KituraNet
import LoggerAPI
import Foundation
import KituraTemplateEngine
// MARK Router
/// The `Router` class provides the external interface for the routing of requests to
/// the appropriate code for handling. This includes:
///
/// - Routing requests to closures with the signature of `RouterHandler`
/// - Routing requests to the handle function of classes that implement the
/// `RouterMiddleware` protocol.
/// - Routing the request to a template engine to generate the appropriate output.
/// - Serving the landing page when someone makes an HTTP request with a path of slash (/).
public class Router {
/// Contains the list of routing elements
var elements: [RouterElement] = []
/// Map from file extensions to Template Engines
private var templateEngines = [String: TemplateEngine]()
/// Default template engine extension
private var defaultEngineFileExtension: String?
/// The root directory for templates that will be automatically handed over to an
/// appropriate templating engine for content generation.
public var viewsPath = "./Views/"
/// Prefix for special page resources
fileprivate let kituraResourcePrefix = "/@@Kitura-router@@/"
/// Helper for serving file resources
fileprivate let fileResourceServer = FileResourceServer()
/// Flag to enable/disable access to parent router's params
private let mergeParameters: Bool
/// Collection of `RouterParameterHandler` for specified parameter name
/// that will be passed to `RouterElementWalker` when server receives client request
/// and used to handle request's url parameters.
fileprivate var parameterHandlers = [String : [RouterParameterHandler]]()
/// Initialize a `Router` instance
///
/// - Parameter mergeParameters: Specify if this router should have access to path parameters
/// matched in its parent router. Defaults to `false`.
public init(mergeParameters: Bool = false) {
self.mergeParameters = mergeParameters
Log.verbose("Router initialized")
}
func routingHelper(_ method: RouterMethod, pattern: String?, handler: [RouterHandler]) -> Router {
elements.append(RouterElement(method: method,
pattern: pattern,
handler: handler,
mergeParameters: mergeParameters))
return self
}
func routingHelper(_ method: RouterMethod, pattern: String?, allowPartialMatch: Bool = true, middleware: [RouterMiddleware]) -> Router {
elements.append(RouterElement(method: method,
pattern: pattern,
middleware: middleware,
allowPartialMatch: allowPartialMatch,
mergeParameters: mergeParameters))
return self
}
// MARK: Template Engine
/// Sets the default templating engine to be used when the extension of a file in the
/// `viewsPath` doesn't match the extension of one of the registered templating engines.
///
/// - Parameter templateEngine: The new default templating engine
public func setDefault(templateEngine: TemplateEngine?) {
if let templateEngine = templateEngine {
defaultEngineFileExtension = templateEngine.fileExtension
add(templateEngine: templateEngine)
return
}
defaultEngineFileExtension = nil
}
/// Register a templating engine. The templating engine will handle files in the `viewsPath`
/// that match the extension it supports.
///
/// - Parameter templateEngine: The templating engine to register.
/// - Parameter forFileExtensions: The extensions of the files to apply the template engine on.
/// - Parameter useDefaultFileExtension: flag to specify if the default file extension of the
/// template engine should be used
public func add(templateEngine: TemplateEngine, forFileExtensions fileExtensions: [String] = [],
useDefaultFileExtension: Bool = true) {
if useDefaultFileExtension {
templateEngines[templateEngine.fileExtension] = templateEngine
}
for fileExtension in fileExtensions {
templateEngines[fileExtension] = templateEngine
}
}
/// Render a template using a context
///
/// - Parameter template: The path to the template file to be rendered.
/// - Parameter context: A Dictionary of variables to be used by the
/// template engine while rendering the template.
/// - Parameter options: rendering options, specific per template engine
///
/// - Returns: The content generated by rendering the template.
/// - Throws: Any error thrown by the Templating Engine when it fails to
/// render the template.
internal func render(template: String, context: [String: Any], options: RenderingOptions = NullRenderingOptions()) throws -> String {
guard let resourceExtension = URL(string: template)?.pathExtension else {
throw TemplatingError.noTemplateEngineForExtension(extension: "")
}
let fileExtension: String
let resourceWithExtension: String
if resourceExtension.isEmpty {
fileExtension = defaultEngineFileExtension ?? ""
// swiftlint:disable todo
//TODO: Use stringByAppendingPathExtension once issue https://bugs.swift.org/browse/SR-999 is resolved
// swiftlint:enable todo
resourceWithExtension = template + "." + fileExtension
} else {
fileExtension = resourceExtension
resourceWithExtension = template
}
if fileExtension.isEmpty {
throw TemplatingError.noDefaultTemplateEngineAndNoExtensionSpecified
}
guard let templateEngine = templateEngines[fileExtension] else {
throw TemplatingError.noTemplateEngineForExtension(extension: fileExtension)
}
let filePath: String
if let decodedResourceExtension = resourceWithExtension.removingPercentEncoding {
filePath = viewsPath + decodedResourceExtension
} else {
Log.warning("Unable to decode url \(resourceWithExtension)")
filePath = viewsPath + resourceWithExtension
}
let absoluteFilePath = StaticFileServer.ResourcePathHandler.getAbsolutePath(for: filePath)
return try templateEngine.render(filePath: absoluteFilePath, context: context)
}
// MARK: Sub router
/// Setup a "sub router" to handle requests. This can make it easier to
/// build a server that serves a large set of paths, by breaking it up
/// in to "sub router" where each sub router is mapped to it's own root
/// path and handles all of the mappings of paths below that.
///
/// - Parameter route: The path to bind the sub router to.
/// - Parameter mergeParameters: Specify if this router should have access to path parameters
/// matched in its parent router. Defaults to `false`.
/// - Parameter allowPartialMatch: A Bool that indicates whether or not a partial match of
/// the path by the pattern is sufficient.
/// - Returns: The created sub router.
public func route(_ route: String, mergeParameters: Bool = false, allowPartialMatch: Bool = true) -> Router {
let subrouter = Router(mergeParameters: mergeParameters)
subrouter.parameterHandlers = self.parameterHandlers
self.all(route, allowPartialMatch: allowPartialMatch, middleware: subrouter)
return subrouter
}
// MARK: Parameter handling
/// Setup a handler for specific name of request parameters.
/// This can make it easier to handle values of provided parameter name.
///
/// - Parameter name: A single parameter name to be handled
/// - Parameter handler: A comma delimited set of `RouterParameterHandler`s that will be
/// invoked when request parses a parameter with specified name.
/// - Returns: Current router instance
@discardableResult
public func parameter(_ name: String, handler: @escaping RouterParameterHandler...) -> Router {
return self.parameter([name], handlers: handler)
}
/// Setup a handler for specific name of request parameters.
/// This can make it easier to handle values of provided parameter name.
///
/// - Parameter names: The array of parameter names that will be used to invoke handlers
/// - Parameter handler: A comma delimited set of `RouterParameterHandler`s that will be
/// invoked when request parses a parameter with specified name.
/// - Returns: Current router instance
@discardableResult
public func parameter(_ names: [String], handler: @escaping RouterParameterHandler...) -> Router {
return self.parameter(names, handlers: handler)
}
/// Setup a handler for specific name of request parameters.
/// This can make it easier to handle values of provided parameter name.
///
/// - Parameter names: The array of parameter names that will be used to invoke handlers
/// - Parameter handlers: The array of `RouterParameterHandler`s that will be
/// invoked when request parses a parameter with specified name.
/// - Returns: Current router instance
@discardableResult
public func parameter(_ names: [String], handlers: [RouterParameterHandler]) -> Router {
for name in names {
if self.parameterHandlers[name] == nil {
self.parameterHandlers[name] = handlers
} else {
self.parameterHandlers[name]?.append(contentsOf: handlers)
}
}
return self
}
}
// MARK: RouterMiddleware extensions
extension Router : RouterMiddleware {
/// Handle an HTTP request as a middleware. Used for sub routing.
///
/// - Parameter request: The `RouterRequest` object that is used to work with
/// the incoming request.
/// - Parameter response: The `RouterResponse` object used to send responses
/// to the HTTP request.
/// - Parameter next: The closure to invoke to cause the router to inspect the
/// path in the list of paths.
public func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
guard let urlPath = request.parsedURLPath.path else {
Log.error("request.parsedURLPath.path is nil. Failed to handle request")
return
}
if request.allowPartialMatch {
let mountpath = request.matchedPath
/// Note: Since regex always start with ^, the beginning of line character,
/// matched ranges always start at location 0, so it's OK to check via `hasPrefix`.
/// Note: `hasPrefix("")` is `true` on macOS but `false` on Linux
guard mountpath == "" || urlPath.hasPrefix(mountpath) else {
Log.error("Failed to find matches in url")
return
}
let index = urlPath.index(urlPath.startIndex, offsetBy: mountpath.characters.count)
request.parsedURLPath.path = urlPath.substring(from: index)
}
process(request: request, response: response) {
request.parsedURLPath.path = urlPath
next()
}
}
}
// MARK: HTTPServerDelegate extensions
extension Router : ServerDelegate {
/// Handle the HTTP request
///
/// - Parameter request: The `ServerRequest` object used to work with the incoming
/// HTTP request at the Kitura-net API level.
/// - Parameter response: The `ServerResponse` object used to send responses to the
/// HTTP request at the Kitura-net API level.
public func handle(request: ServerRequest, response: ServerResponse) {
let routeReq = RouterRequest(request: request)
let routeResp = RouterResponse(response: response, router: self, request: routeReq)
process(request: routeReq, response: routeResp) { [weak self, weak routeReq, weak routeResp] () in
guard let strongSelf = self else {
Log.error("Found nil self at \(#file) \(#line)")
return
}
guard let routeReq = routeReq else {
Log.error("Found nil routeReq at \(#file) \(#line)")
return
}
guard let routeResp = routeResp else {
Log.error("Found nil routeResp at \(#file) \(#line)")
return
}
do {
if !routeResp.state.invokedEnd {
if routeResp.statusCode == .unknown && !routeResp.state.invokedSend {
strongSelf.sendDefaultResponse(request: routeReq, response: routeResp)
}
if !routeResp.state.invokedEnd {
try routeResp.end()
}
}
} catch {
// Not much to do here
Log.error("Failed to send response to the client")
}
}
}
/// Processes the request
///
/// - Parameter request: The `RouterRequest` object that is used to work with
/// the incoming request.
/// - Parameter response: The `RouterResponse` object used to send responses
/// to the HTTP request.
/// - Parameter callback: The closure to invoke to cause the router to inspect the
/// path in the list of paths.
fileprivate func process(request: RouterRequest, response: RouterResponse, callback: @escaping () -> Void) {
guard let urlPath = request.parsedURLPath.path else {
Log.error("request.parsedURLPath.path is nil. Failed to process request")
return
}
if urlPath.hasPrefix(kituraResourcePrefix) {
let resource = urlPath.substring(from: kituraResourcePrefix.endIndex)
fileResourceServer.sendIfFound(resource: resource, usingResponse: response)
} else {
let looper = RouterElementWalker(elements: self.elements,
parameterHandlers: self.parameterHandlers,
request: request,
response: response,
callback: callback)
looper.next()
}
}
/// Send default index.html file and its resources if appropriate, otherwise send
/// default 404 message.
///
/// - Parameter request: The `RouterRequest` object that is used to work with
/// the incoming request.
/// - Parameter response: The `RouterResponse` object used to send responses
/// to the HTTP request.
private func sendDefaultResponse(request: RouterRequest, response: RouterResponse) {
if request.parsedURLPath.path == "/" {
fileResourceServer.sendIfFound(resource: "index.html", usingResponse: response)
} else {
do {
let errorMessage = "Cannot \(request.method) \(request.parsedURLPath.path ?? "")."
try response.status(.notFound).send(errorMessage).end()
} catch {
Log.error("Error sending default not found message: \(error)")
}
}
}
}
|
apache-2.0
|
24440ad8c288e50941df10e912e68c73
| 43.760989 | 140 | 0.634015 | 5.207095 | false | false | false | false |
dydyistc/DYWeibo
|
DYWeibo/Classes/Home(首页)/StatusViewModel.swift
|
1
|
2692
|
//
// StatusViewModel.swift
// DYWeibo
//
// Created by Yi Deng on 25/04/2017.
// Copyright © 2017 TD. All rights reserved.
//
import UIKit
class StatusViewModel: NSObject {
// MARK:- 定义属性
var status : Status?
var cellHeight : CGFloat = 0
// MARK:- 对数据处理的属性
var sourceText : String? // 处理来源
var createAtText : String? // 处理创建时间
var verifiedImage : UIImage? // 处理用户认证图标
var vipImage : UIImage? // 处理用户会员等级
var profileURL : URL? // 处理用户头像的地址
var picURLs : [URL] = [URL]() // 处理微博配图的数据
// MARK:- 自定义构造函数
init(status : Status) {
self.status = status
// 1.对来源处理
if let source = status.source, source != "" {
// 1.1.获取起始位置和截取的长度
let startIndex = (source as NSString).range(of: ">").location + 1
let length = (source as NSString).range(of: "</").location - startIndex
// 1.2.截取字符串
sourceText = (source as NSString).substring(with: NSRange(location: startIndex, length: length))
}
// 2.处理时间
if let createAt = status.created_at {
createAtText = Date.createDateString(createAt)
}
// 3.处理认证
let verifiedType = status.user?.verified_type ?? -1
switch verifiedType {
case 0:
verifiedImage = UIImage(named: "avatar_vip")
case 2, 3, 5:
verifiedImage = UIImage(named: "avatar_enterprise_vip")
case 220:
verifiedImage = UIImage(named: "avatar_grassroot")
default:
verifiedImage = nil
}
// 4.处理会员图标
let mbrank = status.user?.mbrank ?? 0
if mbrank > 0 && mbrank <= 6 {
vipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
}
// 5.用户头像的处理
let profileURLString = status.user?.profile_image_url ?? ""
profileURL = URL(string: profileURLString)
// 6.处理配图数据
let picURLDicts = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
if let picURLDicts = picURLDicts {
for picURLDict in picURLDicts {
guard let picURLString = picURLDict["thumbnail_pic"] else {
continue
}
picURLs.append(URL(string: picURLString)!)
}
}
}
}
|
apache-2.0
|
cef4b505b85464b8c312abd976df07fc
| 29.8375 | 108 | 0.530604 | 4.297909 | false | false | false | false |
babyboy18/swift_code
|
Swifter/SwifterSearch.swift
|
1
|
3083
|
//
// SwifterSearch.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
// GET search/tweets
public func getSearchTweetsWithQuery(q: String, geocode: String?, lang: String?, locale: String?, resultType: String?, count: Int?, until: String?, sinceID: String?, maxID: String?, includeEntities: Bool?, callback: String?, success: ((statuses: [JSONValue]?, searchMetadata: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) {
let path = "search/tweets.json"
var parameters = Dictionary<String, AnyObject>()
parameters["q"] = q
if geocode != nil {
parameters["geocode"] = geocode!
}
if lang != nil {
parameters["lang"] = lang!
}
if locale != nil {
parameters["locale"] = locale!
}
if resultType != nil {
parameters["result_type"] = resultType!
}
if count != nil {
parameters["count"] = count!
}
if until != nil {
parameters["until"] = until!
}
if sinceID != nil {
parameters["since_id"] = sinceID!
}
if maxID != nil {
parameters["max_id"] = maxID!
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if callback != nil {
parameters["callback"] = callback!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
switch (json["statuses"].array, json["search_metadata"].object) {
case (let statuses, let searchMetadata):
success?(statuses: statuses, searchMetadata: searchMetadata)
default:
success?(statuses: nil, searchMetadata: nil)
}
}, failure: failure)
}
}
|
mit
|
d02cab9845234d462726095b4f781bc4
| 37.061728 | 349 | 0.625365 | 4.601493 | false | false | false | false |
devroo/onTodo
|
Swift/StringsAndCharacters.playground/section-1.swift
|
1
|
4729
|
import UIKit
/*
* 문자열과 문자 (Strings and Characters)
*/
// 리터럴
let someString = "Some string literal value"
/*
이스케이프 특별 문자 \0 (null 문자), \\ (백슬래시), \t (수평 탭), \n (줄 바꿈), \r (캐리지 리턴), \" (큰따옴표), \' (작은따옴표)
1바이트 유니코드 스칼라는 \xnn 이며 nn은 두개의 16진수 숫자입니다.
2바이트 유니코드 스칼라는 \unnnn 이며 nnnn은 4개의 16진수 숫자입니다.
4바이트 유니코드 스칼라는 \Unnnnnnnn 이며 nnnnnnnn은 8개의 16진수 숫자입니다.
*/
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}" // $, Unicode scalar U+0024
let blackHeart = "\u{2665}" // ♥, Unicode scalar U+2665
let sparklingHeart = "\u{0001F496}" // 💖, Unicode scalar U+1F496
// 초기화
var emptyString = "" // 빈 문자열 리터럴
var anotherEmptyString = String() // 초기화 문법
// 두 문자열 모두 비어있으며 서로 똑같다.
if emptyString.isEmpty {
println("여기엔 아무것도 보이지 않습니다.")
}
// prints 여긴 아무것도 보이지 않습니다."
// 가변성
var variableString = "Horse"
variableString += " and carriage"
// variableString 은 "Horse and carriage" 입니다.
let constantString = "Highlander"
// constantString += " and another Highlander"
// 컴파일 에러 - 상수 문자열은 변경될 수 없습니다.
// 캐릭터 작업
for character in "Dog!🐶"{
println(character)
}
// D
// o
// g
// !
// 🐶
let yenSign: Character = "¥"
// 문자 세기
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
// countElements 는 NSString의 utf16count 의 값을 의미
// 문자열 및 문자 합치기
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
let stringPlusCharacter = string1 + character1 // equals "hello!"
let stringPlusString = string1 + string2 // equals "hello there"
let characterPlusString = character1 + string1 // equals "!hello"
let characterPlusCharacter = character1 + character2 // equals "!?"
var instruction = "look over"
instruction += string2
// instriction 은 "look over there" 와 같습니다.
var welcome = "good mornig"
welcome += character1
// welcome 은 "good morning!" 과 같습니다.
// 형변환 값입력
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
// 문자열 비교
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
// hasPrefix 전위 문자열 찾기
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
println("There are \(act1SceneCount) scenes in Act 1")
// prints "There are 5 scenes in Act 1"
// hasSuffix 후위 문자열 찾기
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
++mansionCount
} else if scene.hasSuffix("Friar Lawrence's cell") {
++cellCount
}
}
println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// prints "6 mansion scenes; 2 cell scenes"
// 대문자와 소문자 ( uppercase / lowercase 가 사라졌나? )
let normal = "Could you help me, please?"
//let shouty = normal.uppercaseString
// shouty is equal to "COULD YOU HELP ME, PLEASE?"
//let whispered = normal.lowercaseString
// whispered is equal to "could you help me, please?"
// 유니코드
let dogString = "Dog!🐶" //( dog face : U+1F436 )
for codeUnit in dogString.utf8 {
print("\(codeUnit) ")
}
// 68 111 103 33 240 159 144 182
for codeUnit in dogString.utf16 {
print("\(codeUnit) ")
}
// 68 111 103 33 55357 56374
|
gpl-2.0
|
c6168240e631bad2642b88adab4f6bdb
| 27.047297 | 93 | 0.668193 | 2.616646 | false | false | false | false |
orchely/ColorThiefSwift
|
ColorThiefSwift/Classes/ColorThief.swift
|
2
|
6459
|
//
// ColorThief.swift
// ColorThiefSwift
//
// Created by Kazuki Ohara on 2017/02/11.
// Copyright © 2019 Kazuki Ohara. All rights reserved.
//
// License
// -------
// MIT License
// https://github.com/yamoridon/ColorThiefSwift/blob/master/LICENSE
//
// Thanks
// ------
// Lokesh Dhakar - for the original Color Thief JavaScript version
// http://lokeshdhakar.com/projects/color-thief/
// Sven Woltmann - for the fast Java Implementation
// https://github.com/SvenWoltmann/color-thief-java
import UIKit
public class ColorThief {
public static let defaultQuality = 10
public static let defaultIgnoreWhite = true
/// Use the median cut algorithm to cluster similar colors and return the
/// base color from the largest cluster.
///
/// - Parameters:
/// - image: the source image
/// - quality: 1 is the highest quality settings. 10 is the default. There is
/// a trade-off between quality and speed. The bigger the number,
/// the faster a color will be returned but the greater the
/// likelihood that it will not be the visually most dominant
/// color.
/// - ignoreWhite: if true, white pixels are ignored
/// - Returns: the dominant color
public static func getColor(from image: UIImage, quality: Int = defaultQuality, ignoreWhite: Bool = defaultIgnoreWhite) -> MMCQ.Color? {
guard let palette = getPalette(from: image, colorCount: 5, quality: quality, ignoreWhite: ignoreWhite) else {
return nil
}
let dominantColor = palette[0]
return dominantColor
}
/// Use the median cut algorithm to cluster similar colors.
///
/// - Parameters:
/// - image: the source image
/// - colorCount: the size of the palette; the number of colors returned.
/// *the actual size of array becomes smaller than this.
/// this is intended to align with the original Java version.*
/// - quality: 1 is the highest quality settings. 10 is the default. There is
/// a trade-off between quality and speed. The bigger the number,
/// the faster the palette generation but the greater the
/// likelihood that colors will be missed.
/// - ignoreWhite: if true, white pixels are ignored
/// - Returns: the palette
public static func getPalette(from image: UIImage, colorCount: Int, quality: Int = defaultQuality, ignoreWhite: Bool = defaultIgnoreWhite) -> [MMCQ.Color]? {
guard let colorMap = getColorMap(from: image, colorCount: colorCount, quality: quality, ignoreWhite: ignoreWhite) else {
return nil
}
return colorMap.makePalette()
}
/// Use the median cut algorithm to cluster similar colors.
///
/// - Parameters:
/// - image: the source image
/// - colorCount: the size of the palette; the number of colors returned.
/// *the actual size of array becomes smaller than this.
/// this is intended to align with the original Java version.*
/// - quality: 1 is the highest quality settings. 10 is the default. There is
/// a trade-off between quality and speed. The bigger the number,
/// the faster the palette generation but the greater the
/// likelihood that colors will be missed.
/// - ignoreWhite: if true, white pixels are ignored
/// - Returns: the color map
public static func getColorMap(from image: UIImage, colorCount: Int, quality: Int = defaultQuality, ignoreWhite: Bool = defaultIgnoreWhite) -> MMCQ.ColorMap? {
guard let pixels = makeBytes(from: image) else {
return nil
}
let colorMap = MMCQ.quantize(pixels, quality: quality, ignoreWhite: ignoreWhite, maxColors: colorCount)
return colorMap
}
static func makeBytes(from image: UIImage) -> [UInt8]? {
guard let cgImage = image.cgImage else {
return nil
}
if isCompatibleImage(cgImage) {
return makeBytesFromCompatibleImage(cgImage)
} else {
return makeBytesFromIncompatibleImage(cgImage)
}
}
static func isCompatibleImage(_ cgImage: CGImage) -> Bool {
guard let colorSpace = cgImage.colorSpace else {
return false
}
if colorSpace.model != .rgb {
return false
}
let bitmapInfo = cgImage.bitmapInfo
let alpha = bitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
let alphaRequirement = (alpha == CGImageAlphaInfo.noneSkipLast.rawValue || alpha == CGImageAlphaInfo.last.rawValue)
let byteOrder = bitmapInfo.rawValue & CGBitmapInfo.byteOrderMask.rawValue
let byteOrderRequirement = (byteOrder == CGBitmapInfo.byteOrder32Little.rawValue)
if !(alphaRequirement && byteOrderRequirement) {
return false
}
if cgImage.bitsPerComponent != 8 {
return false
}
if cgImage.bitsPerPixel != 32 {
return false
}
if cgImage.bytesPerRow != cgImage.width * 4 {
return false
}
return true
}
static func makeBytesFromCompatibleImage(_ image: CGImage) -> [UInt8]? {
guard let dataProvider = image.dataProvider else {
return nil
}
guard let data = dataProvider.data else {
return nil
}
let length = CFDataGetLength(data)
var rawData = [UInt8](repeating: 0, count: length)
CFDataGetBytes(data, CFRange(location: 0, length: length), &rawData)
return rawData
}
static func makeBytesFromIncompatibleImage(_ image: CGImage) -> [UInt8]? {
let width = image.width
let height = image.height
var rawData = [UInt8](repeating: 0, count: width * height * 4)
guard let context = CGContext(
data: &rawData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: 4 * width,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) else {
return nil
}
context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
return rawData
}
}
|
mit
|
daddb3dd48e0a988221b0c1c2a32b2d0
| 40.133758 | 163 | 0.620316 | 4.580142 | false | false | false | false |
GetZero/-Swift-LeetCode
|
LeetCode/FizzBuzz.swift
|
1
|
1283
|
//
// FizzBuzz.swift
// LeetCode
//
// Created by 韦曲凌 on 2016/11/7.
// Copyright © 2016年 Wake GetZero. All rights reserved.
//
import Foundation
class FizzBuzz: NSObject {
// Write a program that outputs the string representation of numbers from 1 to n.
//
// But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
//
// Example:
//
// n = 15,
//
// Return:
// [
// "1",
// "2",
// "Fizz",
// "4",
// "Buzz",
// "Fizz",
// "7",
// "8",
// "Fizz",
// "Buzz",
// "11",
// "Fizz",
// "13",
// "14",
// "FizzBuzz"
// ]
func fizzBuzz(_ n: Int) -> [String] {
var fzBz: [String] = []
for i in 1 ... n {
if i % 3 != 0 && i % 5 != 0 {
fzBz.append("\(i)")
continue
}
if i % 3 == 0 && i % 5 == 0 {
fzBz.append("FizzBuzz")
} else if i % 5 == 0 {
fzBz.append("Buzz")
} else {
fzBz.append("Fizz")
}
}
return fzBz
}
}
|
apache-2.0
|
11e56d259c2cc0607a7f19695ff17ad2
| 19.688525 | 197 | 0.429477 | 3.312336 | false | false | false | false |
davidear/swiftsome
|
JokeClient-Swift/JokeClient-Swift/AppDelegate.swift
|
1
|
2606
|
//
// AppDelegate.swift
// JokeClient-Swift
//
// Created by YANGReal on 14-6-5.
// Copyright (c) 2014年 YANGReal. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]? ) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
var mainViewController = YRMainViewController(nibName:nil, bundle: nil)
var navigationViewController = UINavigationController(rootViewController: mainViewController)
self.window!.rootViewController = navigationViewController
//self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
172043819f5084ef1c78bc60e8d47c55
| 49.076923 | 285 | 0.741551 | 5.62419 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.