repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apple/swift-nio-http2 | FuzzTesting/Sources/FuzzHTTP2/main.swift | 1 | 1877 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// Sources/protoc-gen-swift/main.swift - Protoc plugin main
//
// Copyright (c) 2020 - 2021 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
import Foundation
import NIOCore
import NIOEmbedded
import NIOHTTP1
import NIOHTTP2
fileprivate func fuzzInput(_ bytes: UnsafeRawBufferPointer) throws {
let channel = EmbeddedChannel()
defer {
_ = try? channel.finish()
}
_ = try channel.configureHTTP2Pipeline(
mode: .server,
initialLocalSettings: [HTTP2Setting(parameter: .maxConcurrentStreams, value: 1<<23)],
inboundStreamInitializer: nil
).wait()
try channel.connect(to: SocketAddress(unixDomainSocketPath: "/foo")).wait()
let buffer = channel.allocator.buffer(bytes: bytes)
try channel.writeInbound(buffer)
channel.embeddedEventLoop.run()
channel.pipeline.fireChannelInactive()
channel.embeddedEventLoop.run()
}
@_cdecl("LLVMFuzzerTestOneInput")
public func FuzzServer(_ start: UnsafeRawPointer, _ count: Int) -> CInt {
let bytes = UnsafeRawBufferPointer(start: start, count: count)
do {
let _ = try fuzzInput(bytes)
} catch {
// Errors parsing are to be expected since not all inputs will be well formed.
}
return 0
}
| apache-2.0 | a70d29afb5e571f4ffbf26572f34e26e | 30.813559 | 93 | 0.658498 | 4.469048 | false | false | false | false |
badoo/Chatto | ChattoAdditions/sources/Input/Photos/Camera/LiveCameraCaptureSession.swift | 1 | 4946 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import Photos
protocol LiveCameraCaptureSessionProtocol {
var captureLayer: AVCaptureVideoPreviewLayer? { get }
var isInitialized: Bool { get }
var isCapturing: Bool { get }
func startCapturing(_ completion: @escaping () -> Void)
func stopCapturing(_ completion: @escaping () -> Void)
}
class LiveCameraCaptureSession: LiveCameraCaptureSessionProtocol {
let settings: LiveCameraSettings
var isInitialized: Bool = false
init(settings: LiveCameraSettings) {
self.settings = settings
}
var isCapturing: Bool {
return self.isInitialized && self.captureSession?.isRunning ?? false
}
deinit {
var layer = self.captureLayer
layer?.removeFromSuperlayer()
var session: AVCaptureSession? = self.isInitialized ? self.captureSession : nil
DispatchQueue.global(qos: .default).async {
// Analogously to AVCaptureSession creation, dealloc can take very long, so let's do it out of the main thread
if layer != nil { layer = nil }
if session != nil { session = nil }
}
}
func startCapturing(_ completion: @escaping () -> Void) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak operation, weak self] in
guard let sSelf = self, let strongOperation = operation, !strongOperation.isCancelled else { return }
sSelf.addInputDevicesIfNeeded()
sSelf.captureSession?.startRunning()
DispatchQueue.main.async(execute: completion)
}
self.queue.cancelAllOperations()
self.queue.addOperation(operation)
}
func stopCapturing(_ completion: @escaping () -> Void) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak operation, weak self] in
guard let sSelf = self, let strongOperation = operation, !strongOperation.isCancelled else { return }
sSelf.captureSession?.stopRunning()
sSelf.removeInputDevices()
DispatchQueue.main.async(execute: completion)
}
self.queue.cancelAllOperations()
self.queue.addOperation(operation)
}
private (set) var captureLayer: AVCaptureVideoPreviewLayer?
private lazy var queue: OperationQueue = {
let queue = OperationQueue()
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 1
return queue
}()
private lazy var captureSession: AVCaptureSession? = {
assert(!Thread.isMainThread, "This can be very slow, make sure it happens in a background thread")
self.isInitialized = true
#if !(arch(i386) || arch(x86_64))
let session = AVCaptureSession()
self.captureLayer = AVCaptureVideoPreviewLayer(session: session)
self.captureLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
return session
#else
return nil
#endif
}()
private func addInputDevicesIfNeeded() {
assert(!Thread.isMainThread, "This can be very slow, make sure it happens in a background thread")
guard self.captureSession?.inputs.count == 0 else { return }
guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: self.settings.cameraPosition) else {
return
}
do {
let input = try AVCaptureDeviceInput(device: device)
self.captureSession?.addInput(input)
} catch {
}
}
private func removeInputDevices() {
assert(!Thread.isMainThread, "This can be very slow, make sure it happens in a background thread")
self.captureSession?.inputs.forEach { (input) in
self.captureSession?.removeInput(input)
}
}
}
| mit | be361b348c2f965c2d4197f652d9d233 | 37.640625 | 135 | 0.682572 | 5.141372 | false | false | false | false |
rexmas/Crust | RealmCrustTests/Tests.swift | 1 | 4451 | import XCTest
import Crust
import JSONValueRX
import Realm
public class User: RLMObject {
@objc public dynamic var identifier: String = ""
@objc public dynamic var name: String? = nil
@objc public dynamic var surname: String? = nil
@objc public dynamic var height: Int = 170
@objc public dynamic var weight: Int = 70
@objc public dynamic var birthDate: NSDate? = nil
@objc public dynamic var sex: Int = 2
@objc public dynamic var photoPath: String? = nil
// override public static func primaryKey() -> String? {
// return "identifier"
// }
}
public class UserMapping: RealmMapping {
public var adapter: RealmAdapter
public var primaryKeys: [Mapping.PrimaryKeyDescriptor]? {
return [("identifier", "id_hash", nil)]
}
public required init(adapter: RealmAdapter) {
self.adapter = adapter
}
public func mapping(toMap: inout User, payload: MappingPayload<String>) {
let birthdateMapping = DateMapping(dateFormatter: DateFormatter.isoFormatter)
let primaryKeyMapping = PrimaryKeyMapping()
toMap.birthDate <- (.mapping("birthdate", birthdateMapping), payload)
toMap.identifier <- (.mapping("id_hash", primaryKeyMapping), payload)
toMap.name <- ("user_name", payload)
toMap.surname <- ("user_surname", payload)
toMap.height <- ("height", payload)
toMap.weight <- ("weight", payload)
toMap.sex <- ("sex", payload)
toMap.photoPath <- ("photo_path", payload)
}
}
extension NSDate: AnyMappable { }
public class DateMapping: Transform {
public typealias MappedObject = NSDate
let dateFormatter: DateFormatter
init(dateFormatter: DateFormatter){
self.dateFormatter = dateFormatter
}
public func fromJSON(_ json: JSONValue) throws -> MappedObject {
switch json {
case .string(let date):
return (self.dateFormatter.date(from: date) as NSDate?) ?? NSDate()
default:
throw NSError(domain: "", code: 0, userInfo: nil)
}
}
public func toJSON(_ obj: MappedObject) -> JSONValue {
return .string(self.dateFormatter.string(from: obj as Date))
}
}
extension String: AnyMappable { }
public class PrimaryKeyMapping: Transform {
public typealias MappedObject = String
public func fromJSON(_ json: JSONValue) throws -> MappedObject {
switch json{
case .string(let string):
return string
default:
throw NSError(domain: "", code: -1, userInfo: nil)
}
}
public func toJSON(_ obj: MappedObject) -> JSONValue {
return JSONValue.number(.int(Int64(obj)!))
}
}
class Tests: RealmMappingTest {
func testShouldDecodeJSONUserObjects() {
// NOTE: Also testing coercing strings to numbers.
// TODO: We don't coerce numbers to strings, possibly something to look into.
let json: [String : Any] = ["data": ["id_hash": "170", "user_name": "Jorge", "user_surname": "Revuelta", "birthdate": "1991-03-31", "height": 175, "weight": "60", "sex": 2, "photo_path": "http://somwhere-over-the-internet.com/"]]
let mapping = Mapper()
let jsonValue = try! JSONValue(object: json)
_ = try! mapping.map(from: jsonValue["data"]!, using: UserMapping(adapter: adapter!), keyedBy: AllKeys())
XCTAssertEqual(User.allObjects(in: realm!).count, 1)
}
func testShouldEncodeJSONUserObjects() {
let jsonObj: [String : Any] = ["data": ["id_hash": "170", "user_name": "Jorge", "user_surname": "Revuelta", "birthdate": "1991-03-31", "height": 175, "weight": "60", "sex": 2, "photo_path": "http://somwhere-over-the-internet.com/"]]
let mapping = Mapper()
let jsonValue = try! JSONValue(object: jsonObj)
_ = try! mapping.map(from: jsonValue["data"]!, using: UserMapping(adapter: adapter!), keyedBy: AllKeys())
let user = User.allObjects(in: realm!).firstObject()!
let json = try! mapping.mapFromObjectToJSON(user as! User, mapping: UserMapping(adapter: adapter!), keyedBy: AllKeys())
//let id_hash = json["id_hash"]?.values() as! Int
XCTAssertNotNil(json)
//XCTAssertEqual(id_hash, 170)
}
}
| mit | 66091ac01424b162fcc95fdd5e053621 | 33.503876 | 240 | 0.608627 | 4.300483 | false | false | false | false |
arnaudjbernard/ReactiveSwift | Future.swift | 1 | 10779 | ////////////////////////////////////////////////////////////////////////////////////////////////////
// Created by ArnaudJBernard.
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Dirty trick to keep the compiler happy
public class Cell<A> {
private let val: A
init(_ val: A) {
self.val = val
}
}
prefix operator * {}
public prefix func * <A> (c: Cell<A>) -> A {
return c.val
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Either
public enum Either<L, R> {
case Left(Cell<L>)
case Right(Cell<R>)
public func map<NR>(mapping: (R -> NR)) -> Either<L, NR> {
switch self {
case let .Left(l):
return .Left(l)
case let .Right(r):
return .Right(Cell<NR>(mapping(*r)))
}
}
public func flatMap<NR>(flatMapping: R -> Either<L, NR>) -> Either<L, NR> {
switch self {
case let .Left(l):
return .Left(l)
case let .Right(r):
return flatMapping(*r)
}
}
public func void() -> Either<Void, Void> {
//TODO: void is a verb, a noun and an abjective OTL, and it sounds mutating
switch self {
case .Left:
return .Left(Cell<Void>())
case .Right:
return .Right(Cell<Void>())
}
}
}
extension Either: Printable {
public var description: String {
switch self {
case let .Left(l):
return "Left{\(*l)}"
case let .Right(r):
return "Right{\(*r)}"
}
}
}
///Internal Future Callback
private enum FutureCallback<E, S> {
typealias ResultCallback = Either<E, S> -> ()
case Result(ResultCallback)
typealias SuccessCallback = S -> ()
case Success(SuccessCallback)
typealias ErrorCallback = E -> ()
case Error(ErrorCallback)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Future
public class Future<E, S> {
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Private Lifecycle
private var _result: Either<E, S>?
private var _callbacks = Array<FutureCallback<E, S>>()
private var _canceled = false
private init() {}
private func succeed(s: S) {
complete(Either.Right(Cell<S>(s)))
}
private func fail(e: E) {
complete(Either.Left(Cell<E>(e)))
}
private func complete(res: Either<E, S>) {
if _result != nil {
return
}
_result = res
for callback in _callbacks {
call(callback)
}
_callbacks.removeAll()
}
private func cancel() {
//TODO: this may not be a good idea, it breaks the contract
_canceled = true
_callbacks.removeAll()
}
private func call(callback: FutureCallback<E, S>) {
if _canceled {
return
}
if let res = _result {
switch callback {
case let .Result(f):
f(res)
case let .Success(f):
switch res {
case .Left:
break
case let .Right(s):
f(*s)
}
case let .Error(f):
switch res {
case let .Left(e):
f(*e)
case .Right:
break
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Accessor
public var result: Either<E, S>? {
return _result
}
public var completed: Bool {
return result != nil
}
public var success: S? {
if !completed {
return nil
}
switch result! {
case let Either.Right(s):
return *s
default:
return nil
}
}
public var succeeded: Bool {
return success != nil
}
public var error: E? {
if !completed {
return nil
}
switch result! {
case let Either.Left(e):
return *e
default:
return nil
}
}
public var failed: Bool {
return error != nil
}
public var canceled: Bool {
return _canceled
}
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: In place
public func onResult(resultCallback: Either<E, S> -> ()) -> Future<E, S> {
let futureCallback = FutureCallback.Result(resultCallback)
if completed {
call(futureCallback)
}
else {
_callbacks.append(futureCallback)
}
return self
}
public func onSuccess(successCallback: S -> ()) -> Future<E, S> {
let futureCallback = FutureCallback<E, S>.Success(successCallback)
if completed {
call(futureCallback)
}
else {
_callbacks.append(futureCallback)
}
return self
}
public func onError(errorCallback: E -> ()) -> Future<E, S> {
let futureCallback = FutureCallback<E, S>.Error(errorCallback)
if completed {
call(futureCallback)
}
else {
_callbacks.append(futureCallback)
}
return self
}
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Transform
public func map <NS> (mapping: S -> NS) -> Future<E, NS> {
return mapResult() {
either in
either.map(mapping)
}
}
public func mapResult <NE, NS> (mapping: Either<E, S> -> Either<NE, NS>) -> Future<NE, NS> {
var p = Promise<NE, NS>()
onResult() {
either in
p.complete(mapping(either))
}
return p.future
}
public func chain <NS> (mapping: S -> Future<E, NS>) -> Future<E, NS> {
func chaining(either: Either<E, S>) -> Future<E, NS> {
switch either {
case let .Right(s):
return mapping(*s)
case let .Left(e):
return Future<E, NS>.Failed(*e)
}
}
return chainResult(chaining)
}
public func chainResult <NS> (mapping: Either<E, S> -> Future<E, NS>) -> Future<E, NS> {
var p = Promise<E, NS>()
onResult() {
either in
mapping(either).onResult() {
futResult in
p.complete(futResult)
}
return
}
return p.future
}
public func void() -> Future<Void, Void> {
return mapResult() {
either in
either.void()
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Util - Constructors
public class func Completed<E, S>(either : Either<E, S>) -> Future<E, S> {
var f = Future<E, S>()
f.complete(either)
return f
}
public class func Succeeded<E, S>(s : S) -> Future<E, S> {
var f = Future<E, S>()
f.succeed(s)
return f
}
public class func Failed<E, S>(e : E) -> Future<E, S> {
var f = Future<E, S>()
f.fail(e)
return f
}
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Util - Aggregations
//TODO: decide if it belongs in Future or Promise
public class func AllResult(futures: Array<Future<E, S>>) -> Future<Void, Array<Either<E, S>>> {
assert(futures.count > 0)
var p = Promise<Void, Array<Either<E, S>>>()
var resultCount = 0
for future in futures {
future.onResult() {
_ in
resultCount += 1
if resultCount == futures.count {
p.succeed(futures.map({ $0.result! }))
}
}
}
return p.future
}
public class func AllSuccess(futures: Array<Future<E, S>>) -> Future<E, Array<S>> {
assert(futures.count > 0)
var p = Promise<E, Array<S>>()
var successCount = 0
for future in futures {
future.onSuccess() {
_ in
successCount += 1
if successCount == futures.count {
p.succeed(futures.map({ $0.success! }))
}
}
future.onError() {
e in
p.fail(e)
}
}
return p.future
}
public class func Any(futures: Array<Future<E, S>>) -> Future<E, S> {
assert(futures.count > 0)
var p = Promise<E, S>()
var successCount = 0
for future in futures {
future.onSuccess() {
s in
p.succeed(s)
}
future.onError() {
e in
p.fail(e)
}
}
return p.future
}
}
extension Future: Printable {
public var description: String {
return "Future{\(result)}"
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Promise
public class Promise<E, S> {
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Future Accessor
private var _future = Future<E, S>()
var future: Future<E, S> {
return _future
}
////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Lifecycle: mutating the underlying future
public func complete(res: Either<E, S>) {
_future.complete(res)
}
public func succeed(s: S) {
_future.succeed(s)
}
public func fail(e: E) {
_future.fail(e)
}
public func cancel() {
_future.cancel()
}
public func follow(otherFuture: Future<E, S>) {
//TODO: find a good name
otherFuture.onResult(complete)
}
public func unless<_E, NS>(otherFuture: Future<_E, NS>, errorBuilder: NS -> E) {
otherFuture.onSuccess() {
ns in
self.fail(errorBuilder(ns))
}
}
}
extension Promise: Printable {
public var description: String {
return "Promise{\(_future)}"
}
}
| mit | b8c97c5ac2bd1f7521f5271c49d3ea85 | 21.270661 | 100 | 0.420911 | 4.692643 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Highlight/ChartHighlighter.swift | 7 | 3655 | //
// ChartHighlighter.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/7/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class ChartHighlighter : NSObject
{
/// instance of the data-provider
public weak var chart: BarLineChartViewBase?
public init(chart: BarLineChartViewBase)
{
self.chart = chart
}
/// Returns a Highlight object corresponding to the given x- and y- touch positions in pixels.
/// - parameter x:
/// - parameter y:
/// - returns:
public func getHighlight(x x: Double, y: Double) -> ChartHighlight?
{
let xIndex = getXIndex(x)
if (xIndex == -Int.max)
{
return nil
}
let dataSetIndex = getDataSetIndex(xIndex: xIndex, x: x, y: y)
if (dataSetIndex == -Int.max)
{
return nil
}
return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex)
}
/// Returns the corresponding x-index for a given touch-position in pixels.
/// - parameter x:
/// - returns:
public func getXIndex(x: Double) -> Int
{
// create an array of the touch-point
var pt = CGPoint(x: x, y: 0.0)
// take any transformer to determine the x-axis value
self.chart?.getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
return Int(round(pt.x))
}
/// Returns the corresponding dataset-index for a given xIndex and xy-touch position in pixels.
/// - parameter xIndex:
/// - parameter x:
/// - parameter y:
/// - returns:
public func getDataSetIndex(xIndex xIndex: Int, x: Double, y: Double) -> Int
{
let valsAtIndex = getSelectionDetailsAtIndex(xIndex)
let leftdist = ChartUtils.getMinimumDistance(valsAtIndex, val: y, axis: ChartYAxis.AxisDependency.Left)
let rightdist = ChartUtils.getMinimumDistance(valsAtIndex, val: y, axis: ChartYAxis.AxisDependency.Right)
let axis = leftdist < rightdist ? ChartYAxis.AxisDependency.Left : ChartYAxis.AxisDependency.Right
let dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: y, axis: axis)
return dataSetIndex
}
/// Returns a list of SelectionDetail object corresponding to the given xIndex.
/// - parameter xIndex:
/// - returns:
public func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail]
{
var vals = [ChartSelectionDetail]()
var pt = CGPoint()
for i in 0 ..< (self.chart?.data?.dataSetCount ?? 0)
{
let dataSet = self.chart!.data!.getDataSetByIndex(i)
// dont include datasets that cannot be highlighted
if !dataSet.isHighlightEnabled
{
continue
}
// extract all y-values from all DataSets at the given x-index
let yVal: Double = dataSet.yValForXIndex(xIndex)
if yVal.isNaN
{
continue
}
pt.y = CGFloat(yVal)
self.chart!.getTransformer(dataSet.axisDependency).pointValueToPixel(&pt)
if !pt.y.isNaN
{
vals.append(ChartSelectionDetail(value: Double(pt.y), dataSetIndex: i, dataSet: dataSet))
}
}
return vals
}
}
| apache-2.0 | bff799d5a0412a606d1127ad87dfa53d | 29.714286 | 113 | 0.587415 | 4.866844 | false | false | false | false |
Sephiroth87/Flippable | Flippable.swift | 1 | 2171 | //
// Flippable.swift
//
//
// Created by Fabio Ritrovato on 18/02/2015.
// Copyright (c) 2015 orange in a day. All rights reserved.
//
import UIKit
prefix operator ⦅╯°□°⦆╯{}
postfix operator ⧸⦅°⎽°⧸⦆ {}
protocol Flippable {
func flip() -> Self
}
prefix func ⦅╯°□°⦆╯<T: Flippable>(inout rhs: T) -> T {
rhs = rhs.flip()
return rhs
}
postfix func ⧸⦅°⎽°⧸⦆<T: Flippable>(inout lhs: T) -> T {
let old = lhs
lhs = lhs.flip()
return old
}
extension String: Flippable {
static let flipMap: [Character: Character] = [
"w":"ʍ","?":"¿","{":"}","'":",","∴":"∵","A":"∀","&":"⅋","C":"Ↄ","r":"ɹ","c":"ɔ","R":"ᴚ","G":"⅁","e":"ǝ","E":"Ǝ",";":"؛","V":"ᴧ","j":"ɾ","!":"¡",".":"˙","B":"𐐒","K":"⋊","i":"ı","T":"⊥","3":"Ɛ","<":">","l":"ʃ","P":"Ԁ","(":")","D":"◖","n":"u","J":"ſ","v":"ʌ","M":"W","[":"]","b":"q","N":"ᴎ","6":"9","Y":"⅄","‿":"⁀","7":"Ɫ","y":"ʎ","h":"ɥ","\"":"„","U":"∩","L":"⅂","f":"ɟ","F":"Ⅎ","k":"ʞ","d":"p","t":"ʇ","⁅":"⁆","a":"ɐ","_":"‾","m":"ɯ","4":"ᔭ","g":"ƃ","Q":"Ό","┬":"┻"
]
func flip() -> String {
return String(reverse(map(self) {
String.flipMap[$0] ?? {
let inverted: Character = $0
return filter(String.flipMap, {
$1 == inverted
}).first?.0 ?? inverted
}($0)
}))
}
}
extension UIView: Flippable {
func flip() -> Self {
transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
return self
}
}
extension UIImage: Flippable {
func flip() -> Self {
UIGraphicsBeginImageContextWithOptions(size, true, scale)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, size.width, size.height)
CGContextRotateCTM(context, CGFloat(M_PI))
self.drawAtPoint(CGPoint(x: 0.0, y: 0.0))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return self.dynamicType(CGImage: newImage.CGImage)!
}
} | mit | e6aceca20585f6ed13e6e9b4d218bc04 | 27.788732 | 472 | 0.47675 | 2.8375 | false | false | false | false |
joalbright/Relax | Example/Relax/FoursquareVC.swift | 1 | 2297 | //
// FoursquareVC.swift
// Relax
//
// Created by Jo Albright on 1/15/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import MapKit
class FoursquareVC: UIViewController {
@IBOutlet weak var venuesMapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
FoursquareAPI.session().start()
}
override func viewDidAppear(_ animated: Bool) {
if FoursquareAPI.session().authToken.isEmpty { login() } else { loadVenues() }
}
func login() {
present(LoginViewController(session: FoursquareAPI.session()), animated: true, completion: nil)
}
func loadVenues() {
var explore = FoursquareAPI.Endpoints.venuesExplore.endpoint
explore.parameters = ["near" : "atlanta"]
FoursquareAPI.session().request(explore) {
guard let response = $0.0?["response"] as? [String:Any] else { return }
guard let groups = response["groups"] as? [[String:Any]] else { return }
for group in groups {
guard let items = group["items"] as? [[String:Any]] else { continue }
for item in items {
guard let venue = item["venue"] as? [String:Any] else { continue }
guard let location = venue["location"] as? [String:Any] else { continue }
guard let lat = location["lat"] as? Double else { continue }
guard let lng = location["lng"] as? Double else { continue }
let annotation = MKPointAnnotation()
annotation.title = venue["name"] as? String
annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
self.venuesMapView.addAnnotation(annotation)
}
}
// update map with markers
self.venuesMapView.showAnnotations(self.venuesMapView.annotations, animated: true)
}
}
}
| mit | c0c96e5d6ed6f82ae80a198929dd3525 | 29.210526 | 103 | 0.50784 | 5.466667 | false | false | false | false |
Kawoou/FlexibleImage | Sources/Filter/HueFilter.swift | 1 | 2409 | //
// HueFilter.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 12..
// Copyright © 2017년 test. All rights reserved.
//
#if !os(OSX)
import UIKit
#else
import AppKit
#endif
#if !os(watchOS)
import Metal
#endif
internal class HueFilter: ImageFilter {
// MARK: - Property
internal override var metalName: String {
get {
return "HueFilter"
}
}
internal var color: FIColorType = (1.0, 1.0, 1.0, 1.0)
// MARK: - Internal
#if !os(watchOS)
@available(OSX 10.11, iOS 8, tvOS 9, *)
internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool {
let factors: [Float] = [color.r, color.g, color.b, color.a]
for i in 0..<factors.count {
var factor = factors[i]
let size = max(MemoryLayout<Float>.size, 16)
let options: MTLResourceOptions
if #available(iOS 9.0, *) {
options = [.storageModeShared]
} else {
options = [.cpuCacheModeWriteCombined]
}
let buffer = device.device.makeBuffer(
bytes: &factor,
length: size,
options: options
)
#if swift(>=4.0)
commandEncoder.setBuffer(buffer, offset: 0, index: i)
#else
commandEncoder.setBuffer(buffer, offset: 0, at: i)
#endif
}
return super.processMetal(device, commandBuffer, commandEncoder)
}
#endif
override func processNone(_ device: ImageNoneDevice) -> Bool {
guard let context = device.context else { return false }
let color = FIColor(
red: CGFloat(self.color.r),
green: CGFloat(self.color.g),
blue: CGFloat(self.color.b),
alpha: CGFloat(self.color.a)
)
context.saveGState()
context.setBlendMode(.hue)
context.setFillColor(color.cgColor)
context.fill(device.drawRect!)
context.restoreGState()
return super.processNone(device)
}
}
| mit | 4eb564d866260b4ce4a1aef36dfea79f | 26.655172 | 160 | 0.510806 | 4.653772 | false | false | false | false |
plus44/hcr-2016 | app/PiNAOqio/Server/ServerController.swift | 1 | 5918 | //
// ServerController.swift
// PiNAOqio
//
// Created by Mihnea Rusu on 06/12/16.
// Copyright © 2016 Mihnea Rusu. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import UIKit
class ServerController : NSObject {
var host : String!
var port : Int!
var url : String!
var isLongPolling : Bool = false
var jsonPost = JSON(["doneTakingPicture" : nil, "error" : nil, "picture" : nil, "format" : nil])
weak var longPollRequest : Request?
let queue = DispatchQueue(label: "com.queue.ServerController.Serial")
init(host: String) {
super.init()
self.host = host
self.port = 80
self.url = "\(host):\(port)/phone"
}
/**
Resets the values of the keys in jsonPost.
*/
func resetJsonPost() {
jsonPost["doneTakingPicture"].bool = false
jsonPost["error"].string = "NotInitialized"
jsonPost["picture"].string = nil
jsonPost["format"].string = nil
}
/**
Cancels the on-going long-poll request.
*/
func cancelLongPollRequest() {
longPollRequest?.cancel()
print("Cancelled long-poll request.")
}
/**
Long polls the host:port combination at /phone with a GET request.
- Parameters:
- serverReturn: A callback that gets triggered when the server has responded. Should return true if the long-polling is to continue, or false if the long-polling is to stop (will need to be manually queued afterwards).
- response: The response header from the server.
- body: The raw data in the server response.
*/
func longPollServer(serverReturn: @escaping (_ response: HTTPURLResponse?, _ body: Data?) -> Bool) {
print("Starting long-polling.")
longPollRequest = Alamofire.request(url, method: .get)
.response { response in
if serverReturn(response.response, response.data) {
self.longPollServer(serverReturn: serverReturn)
} else {
self.longPollRequest = nil
}
} // end of response closure
}
/**
Uploads a CIImage to the server at /phone using a POST request, under the "picture" entry in the JSON dictionary.
- Parameters:
- ciContext: A CIContext object that can be used to convert the CIImage to JPEG.
- image: Image to send
*/
func uploadCIImageToServerAsJPEG(ciContext: CIContext, image: CIImage) {
queue.sync {
if let jpegImage = ciContext.jpegRepresentation(of: image, colorSpace: CGColorSpace(name: CGColorSpace.genericRGBLinear)!, options: ["kCGImageDestinationLossyCompressionQuality" : 0.9]) {
jsonPost["doneTakingPicture"].bool = true
jsonPost["error"].string = "None"
jsonPost["picture"].string = jpegImage.base64EncodedString(options: .lineLength64Characters)
jsonPost["format"].string = "jpeg"
} // end of if let jpegImage
} // end of queue.sync
postJSONPostToServer()
} // end of func uploadImageToServerAsJpeg
/**
Uploads a UIImage to the server at /phone using a POST request, under the "picture" entry in the JSON dictionary.
- Parameter image: The image to upload as JPEG.
*/
func uploadUIImageToServerAsJPEG(image: UIImage) {
queue.sync {
if let jpegImage = UIImageJPEGRepresentation(image, 0.5) {
jsonPost["doneTakingPicture"].bool = true
jsonPost["error"].string = "None"
jsonPost["picture"].string = jpegImage.base64EncodedString(options: .lineLength64Characters)
jsonPost["format"].string = "jpeg"
print("Converted image to JPEG!")
} // end of if let jpegImage
} // end of queue.sync
postJSONPostToServer()
}
/**
Uploads a UIImage to the server under the "picture" entry in the JSON dictionary at the /phone address of the server host.
- Parameter image: The image to upload as PNG.
*/
func uploadUIImageToServerAsPNG(image: UIImage) {
queue.sync {
if let pngImage = UIImagePNGRepresentation(image) {
jsonPost["doneTakingPicture"].bool = true
jsonPost["error"].string = "None"
jsonPost["picture"].string = pngImage.base64EncodedString(options: .lineLength64Characters)
jsonPost["format"].string = "png"
} // end of if let pngImage
} // end of queue.sync
postJSONPostToServer()
}
/**
Posts the JSON post instance variable to the server at the /phone address on the host.
*/
private func postJSONPostToServer() {
let headers : HTTPHeaders = [
"Content-type" : "application/json"
]
do {
let jsonString = try jsonPost.rawData(options: .prettyPrinted)
print("jsonString rawData: \(jsonString)")
// Upload to server
Alamofire.upload(jsonString, to: url, method: .post, headers: headers)
.response { response in
self.resetJsonPost()
if response.response?.statusCode == 200 {
print("Successfully POSTed JSON to server.")
} else {
print("Failed POSTing JSON to server.")
print("Status code received: \(response.response?.statusCode)")
}
}
} catch {
print("Failed converting jsonString to rawData")
}
}
}
| apache-2.0 | eeb2fcdcb46426ff06db5a792f4a5a10 | 35.079268 | 230 | 0.572925 | 4.85 | false | false | false | false |
quran/quran-ios | Sources/Timing/Timer.swift | 1 | 2935 | //
// Timer.swift
// Quran
//
// Created by Mohamed Afifi on 5/2/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import Locking
open class Timer {
open var isCancelled: Bool {
cancelled.value
}
private let repeated: Bool
private let timer: DispatchSourceTimer
private var cancelled = Protected(false)
private var eventHandler: (() -> Void)?
public init(interval: TimeInterval,
repeated: Bool = false,
startNow: Bool = false,
queue: DispatchQueue = .main,
handler: @escaping () -> Void)
{
self.repeated = repeated
timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: queue)
let dispatchInterval = UInt64(interval * Double(NSEC_PER_SEC))
let startTime = DispatchTime.now() + Double(startNow ? 0 : Int64(dispatchInterval)) / Double(NSEC_PER_SEC)
timer.schedule(deadline: startTime, repeating: DispatchTimeInterval.seconds(Int(interval)))
eventHandler = handler
timer.setEventHandler { [weak self] in
self?.fired()
}
timer.resume()
}
private func fired() {
if !cancelled.value {
eventHandler?()
}
// cancel next ones if not repeated
if !repeated {
cancel()
}
}
public func cancel() {
cancelled.value = true
timer.cancel()
}
deinit {
timer.setEventHandler {}
timer.cancel()
/*
If the timer is suspended, calling cancel without resuming
triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
*/
resume()
eventHandler = nil
}
// MARK: - Pause/Resume
private enum State {
case paused
case resumed
}
private var state = Protected(State.resumed)
public func pause() {
state.sync { state in
guard state == .resumed else {
return
}
state = .paused
timer.suspend()
}
}
public func resume() {
state.sync { state in
guard state == .paused else {
return
}
state = .resumed
timer.resume()
}
}
}
| apache-2.0 | bd1f362c967654ce2caa73f73928cbaf | 25.205357 | 114 | 0.589779 | 4.65873 | false | false | false | false |
vadymmarkov/Pitchy | Source/Data/Note.swift | 1 | 1829 | public struct Note {
public enum Letter: String {
case C = "C"
case CSharp = "C#"
case D = "D"
case DSharp = "D#"
case E = "E"
case F = "F"
case FSharp = "F#"
case G = "G"
case GSharp = "G#"
case A = "A"
case ASharp = "A#"
case B = "B"
public static var values = [
C,
CSharp,
D,
DSharp,
E,
F,
FSharp,
G,
GSharp,
A,
ASharp,
B
]
}
public let index: Int
public let letter: Letter
public let octave: Int
public let frequency: Double
public let wave: AcousticWave
public var string: String {
return "\(self.letter.rawValue)\(self.octave)"
}
// MARK: - Initialization
public init(index: Int) throws {
self.index = index
letter = try NoteCalculator.letter(forIndex: index)
octave = try NoteCalculator.octave(forIndex: index)
frequency = try NoteCalculator.frequency(forIndex: index)
wave = try AcousticWave(frequency: frequency)
}
public init(frequency: Double) throws {
index = try NoteCalculator.index(forFrequency: frequency)
letter = try NoteCalculator.letter(forIndex: index)
octave = try NoteCalculator.octave(forIndex: index)
self.frequency = try NoteCalculator.frequency(forIndex: index)
wave = try AcousticWave(frequency: frequency)
}
public init(letter: Letter, octave: Int) throws {
self.letter = letter
self.octave = octave
index = try NoteCalculator.index(forLetter: letter, octave: octave)
frequency = try NoteCalculator.frequency(forIndex: index)
wave = try AcousticWave(frequency: frequency)
}
// MARK: - Closest Notes
public func lower() throws -> Note {
return try Note(index: index - 1)
}
public func higher() throws -> Note {
return try Note(index: index + 1)
}
}
| mit | 7beb7fd75293149013954aeaf7e303d3 | 22.753247 | 71 | 0.630399 | 3.771134 | false | false | false | false |
kaneshin/Logging-swift | Source/Logging.swift | 1 | 3674 | // Logging.swift
//
// Copyright (c) 2014 Shintaro Kaneko (http://kaneshinth.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum LogLevel: Int {
case Verbose
case Debug
case Info
case Warn
case Error
var tag: String {
switch self {
case .Verbose:
return "VERBOSE"
case .Debug:
return "DEBUG"
case .Info:
return "INFO"
case .Warn:
return "WARN"
case .Error:
return "ERROR"
default:
return "LOG"
}
}
}
public struct Component {
var location: String = __FUNCTION__
var line: Int = __LINE__
}
// MARK: - Driver
public class Driver {
}
// MARK: - Manager
public class Manager {
public class var sharedInstance: Manager {
struct Singleton {
static let instance = Manager()
}
return Singleton.instance
}
var level: LogLevel = LogLevel.Info
var location: Bool = true
var line: Bool = true
public func println(level: LogLevel, message: String, component: Component) {
if self.level.toRaw() > level.toRaw() {
return
}
var output: String = ""
if location {
output += "[\(component.location)]"
}
if line {
output += "[Line \(component.line)]"
}
output += "[\(level.tag)] \(message)"
Swift.println(output)
}
}
// MARK: - Setup
public func setLogLevel(level: LogLevel) {
Manager.sharedInstance.level = level
}
public func includeLocation(location: Bool) {
Manager.sharedInstance.location = location
}
public func includeLine(line: Bool) {
Manager.sharedInstance.line = line
}
// MARK: - Useful
public func verbose(message: String, component: Component = Component()) {
Manager.sharedInstance.println(LogLevel.Verbose, message: message, component: component)
}
public func debug(message: String, component: Component = Component()) {
Manager.sharedInstance.println(LogLevel.Debug, message: message, component: component)
}
public func info(message: String, component: Component = Component()) {
Manager.sharedInstance.println(LogLevel.Info, message: message, component: component)
}
public func warn(message: String, component: Component = Component()) {
Manager.sharedInstance.println(LogLevel.Warn, message: message, component: component)
}
public func error(message: String, component: Component = Component()) {
Manager.sharedInstance.println(LogLevel.Error, message: message, component: component)
}
| mit | eb0a4a7b27429706688f29ac3a14fd04 | 28.15873 | 92 | 0.664943 | 4.426506 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/OpenPanelAccessoryController.swift | 1 | 2360 | //
// OpenPanelAccessoryController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2018-02-24.
//
// ---------------------------------------------------------------------------
//
// © 2018-2022 1024jp
//
// 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
//
// https://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 Cocoa
final class OpenPanelAccessoryController: NSViewController {
// MARK: Public Properties
weak var openPanel: NSOpenPanel? // keep open panel for hidden file visivility toggle
// MARK: Private Properties
@IBOutlet private weak var encodingMenu: NSPopUpButton?
@objc private dynamic var _selectedEncoding: UInt = 0
// MARK: -
// MARK: ViewController Methods
override func viewDidLoad() {
super.viewDidLoad()
// build encoding menu
let menu = self.encodingMenu!.menu!
let autoDetectItem = NSMenuItem(title: "Automatic".localized, action: nil, keyEquivalent: "")
menu.items = [autoDetectItem, .separator()] + EncodingManager.shared.createEncodingMenuItems()
}
// MARK: Public Methods
/// encoding selected by user
var selectedEncoding: String.Encoding? {
self._selectedEncoding > 0 ? String.Encoding(rawValue: self._selectedEncoding) : nil
}
// MARK: Action Messages
/// toggle visivility of hidden files
@IBAction func toggleShowsHiddenFiles(_ sender: NSButton) {
guard let openPanel = self.openPanel else { return assertionFailure() }
let showsHiddenFiles = (sender.integerValue == 1)
openPanel.showsHiddenFiles = showsHiddenFiles
openPanel.treatsFilePackagesAsDirectories = showsHiddenFiles
openPanel.validateVisibleColumns()
}
}
| apache-2.0 | 20373219f0cc42353df4d45e1db6d29e | 27.421687 | 102 | 0.633319 | 4.863918 | false | false | false | false |
nathawes/swift | stdlib/public/core/UnsafePointer.swift | 9 | 42360 | //===--- UnsafePointer.swift ----------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A pointer for accessing data of a
/// specific type.
///
/// You use instances of the `UnsafePointer` type to access data of a
/// specific type in memory. The type of data that a pointer can access is the
/// pointer's `Pointee` type. `UnsafePointer` provides no automated
/// memory management or alignment guarantees. You are responsible for
/// handling the life cycle of any memory you work with through unsafe
/// pointers to avoid leaks or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafePointer` type to access and
/// manage memory that has been bound to a specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafePointer` instance can be in
/// one of several states. Many pointer operations must only be applied to
/// pointers with memory in a specific state---you must keep track of the
/// state of the memory you are working with and understand the changes to
/// that state that different operations perform. Memory can be untyped and
/// uninitialized, bound to a type and uninitialized, or bound to a type and
/// initialized to a value. Finally, memory that was allocated previously may
/// have been deallocated, leaving existing pointers referencing unallocated
/// memory.
///
/// Uninitialized Memory
/// --------------------
///
/// Memory that has just been allocated through a typed pointer or has been
/// deinitialized is in an *uninitialized* state. Uninitialized memory must be
/// initialized before it can be accessed for reading.
///
/// Initialized Memory
/// ------------------
///
/// *Initialized* memory has a value that can be read using a pointer's
/// `pointee` property or through subscript notation. In the following
/// example, `ptr` is a pointer to memory initialized with a value of `23`:
///
/// let ptr: UnsafePointer<Int> = ...
/// // ptr.pointee == 23
/// // ptr[0] == 23
///
/// Accessing a Pointer's Memory as a Different Type
/// ================================================
///
/// When you access memory through an `UnsafePointer` instance, the
/// `Pointee` type must be consistent with the bound type of the memory. If
/// you do need to access memory that is bound to one type as a different
/// type, Swift's pointer types provide type-safe ways to temporarily or
/// permanently change the bound type of the memory, or to load typed
/// instances directly from raw memory.
///
/// An `UnsafePointer<UInt8>` instance allocated with eight bytes of
/// memory, `uint8Pointer`, will be used for the examples below.
///
/// let uint8Pointer: UnsafePointer<UInt8> = fetchEightBytes()
///
/// When you only need to temporarily access a pointer's memory as a different
/// type, use the `withMemoryRebound(to:capacity:)` method. For example, you
/// can use this method to call an API that expects a pointer to a different
/// type that is layout compatible with your pointer's `Pointee`. The following
/// code temporarily rebinds the memory that `uint8Pointer` references from
/// `UInt8` to `Int8` to call the imported C `strlen` function.
///
/// // Imported from C
/// func strlen(_ __s: UnsafePointer<Int8>!) -> UInt
///
/// let length = uint8Pointer.withMemoryRebound(to: Int8.self, capacity: 8) {
/// return strlen($0)
/// }
/// // length == 7
///
/// When you need to permanently rebind memory to a different type, first
/// obtain a raw pointer to the memory and then call the
/// `bindMemory(to:capacity:)` method on the raw pointer. The following
/// example binds the memory referenced by `uint8Pointer` to one instance of
/// the `UInt64` type:
///
/// let uint64Pointer = UnsafeRawPointer(uint8Pointer)
/// .bindMemory(to: UInt64.self, capacity: 1)
///
/// After rebinding the memory referenced by `uint8Pointer` to `UInt64`,
/// accessing that pointer's referenced memory as a `UInt8` instance is
/// undefined.
///
/// var fullInteger = uint64Pointer.pointee // OK
/// var firstByte = uint8Pointer.pointee // undefined
///
/// Alternatively, you can access the same memory as a different type without
/// rebinding through untyped memory access, so long as the bound type and the
/// destination type are trivial types. Convert your pointer to an
/// `UnsafeRawPointer` instance and then use the raw pointer's
/// `load(fromByteOffset:as:)` method to read values.
///
/// let rawPointer = UnsafeRawPointer(uint64Pointer)
/// let fullInteger = rawPointer.load(as: UInt64.self) // OK
/// let firstByte = rawPointer.load(as: UInt8.self) // OK
///
/// Performing Typed Pointer Arithmetic
/// ===================================
///
/// Pointer arithmetic with a typed pointer is counted in strides of the
/// pointer's `Pointee` type. When you add to or subtract from an `UnsafePointer`
/// instance, the result is a new pointer of the same type, offset by that
/// number of instances of the `Pointee` type.
///
/// // 'intPointer' points to memory initialized with [10, 20, 30, 40]
/// let intPointer: UnsafePointer<Int> = ...
///
/// // Load the first value in memory
/// let x = intPointer.pointee
/// // x == 10
///
/// // Load the third value in memory
/// let offsetPointer = intPointer + 2
/// let y = offsetPointer.pointee
/// // y == 30
///
/// You can also use subscript notation to access the value in memory at a
/// specific offset.
///
/// let z = intPointer[2]
/// // z == 30
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafePointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `printInt(atAddress:)` function in the following code
/// sample expects an `UnsafePointer<Int>` instance as its first parameter:
///
/// func printInt(atAddress p: UnsafePointer<Int>) {
/// print(p.pointee)
/// }
///
/// As is typical in Swift, you can call the `printInt(atAddress:)` function
/// with an `UnsafePointer` instance. This example passes `intPointer`, a pointer to
/// an `Int` value, to `print(address:)`.
///
/// printInt(atAddress: intPointer)
/// // Prints "42"
///
/// Because a mutable typed pointer can be implicitly cast to an immutable
/// pointer with the same `Pointee` type when passed as a parameter, you can
/// also call `printInt(atAddress:)` with an `UnsafeMutablePointer` instance.
///
/// let mutableIntPointer = UnsafeMutablePointer(mutating: intPointer)
/// printInt(atAddress: mutableIntPointer)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. The following example passes a
/// pointer to the `value` variable by using inout syntax:
///
/// var value: Int = 23
/// printInt(atAddress: &value)
/// // Prints "23"
///
/// An immutable pointer to the elements of an array is implicitly created when
/// you pass the array as an argument. This example uses implicit bridging to
/// pass a pointer to the elements of `numbers` when calling
/// `printInt(atAddress:)`.
///
/// let numbers = [5, 10, 15, 20]
/// printInt(atAddress: numbers)
/// // Prints "5"
///
/// You can also use inout syntax to pass a mutable pointer to the elements of
/// an array. Because `printInt(atAddress:)` requires an immutable pointer,
/// although this is syntactically valid, it isn't necessary.
///
/// var mutableNumbers = numbers
/// printInt(atAddress: &mutableNumbers)
///
/// No matter which way you call `printInt(atAddress:)`, Swift's type safety
/// guarantees that you can only pass a pointer to the type required by the
/// function---in this case, a pointer to an `Int`.
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafePointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafePointer<Int>(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen // unsafe-performance
public struct UnsafePointer<Pointee>: _Pointer {
/// A type that represents the distance between two pointers.
public typealias Distance = Int
/// The underlying raw (untyped) pointer.
public let _rawValue: Builtin.RawPointer
/// Creates an `UnsafePointer` from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Deallocates the memory block previously allocated at this pointer.
///
/// This pointer must be a pointer to the start of a previously allocated memory
/// block. The memory must not be initialized or `Pointee` must be a trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Accesses the instance referenced by this pointer.
///
/// When reading from the `pointee` property, the instance referenced by
/// this pointer must already be initialized.
@inlinable // unsafe-performance
public var pointee: Pointee {
@_transparent unsafeAddress {
return self
}
}
/// Executes the given closure while temporarily binding the specified number
/// of instances to the given type.
///
/// Use this method when you have a pointer to memory bound to one type and
/// you need to access that memory as instances of another type. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized.
///
/// The following example temporarily rebinds the memory of a `UInt64`
/// pointer to `Int64`, then accesses a property on the signed integer.
///
/// let uint64Pointer: UnsafePointer<UInt64> = fetchValue()
/// let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self, capacity: 1) { ptr in
/// return ptr.pointee < 0
/// }
///
/// Because this pointer's memory is no longer bound to its `Pointee` type
/// while the `body` closure executes, do not access memory using the
/// original pointer from within `body`. Instead, use the `body` closure's
/// pointer argument to access the values in memory as instances of type
/// `T`.
///
/// After executing `body`, this method rebinds memory back to the original
/// `Pointee` type.
///
/// - Note: Only use this method to rebind the pointer's memory to a type
/// with the same size and stride as the currently bound `Pointee` type.
/// To bind a region of memory to a type that is a different size, convert
/// the pointer to a raw pointer and use the `bindMemory(to:capacity:)`
/// method.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. The type `T` must be the same size and be layout compatible
/// with the pointer's `Pointee` type.
/// - count: The number of instances of `Pointee` to bind to `type`.
/// - body: A closure that takes a typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result {
Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer {
Builtin.bindMemory(_rawValue, count._builtinWordValue, Pointee.self)
}
return try body(UnsafePointer<T>(_rawValue))
}
/// Accesses the pointee at the specified offset from this pointer.
///
///
/// For a pointer `p`, the memory at `p + i` must be initialized.
///
/// - Parameter i: The offset from this pointer at which to access an
/// instance, measured in strides of the pointer's `Pointee` type.
@inlinable
public subscript(i: Int) -> Pointee {
@_transparent
unsafeAddress {
return self + i
}
}
@inlinable // unsafe-performance
internal static var _max: UnsafePointer {
return UnsafePointer(
bitPattern: 0 as Int &- MemoryLayout<Pointee>.stride
)._unsafelyUnwrappedUnchecked
}
}
/// A pointer for accessing and manipulating data of a
/// specific type.
///
/// You use instances of the `UnsafeMutablePointer` type to access data of a
/// specific type in memory. The type of data that a pointer can access is the
/// pointer's `Pointee` type. `UnsafeMutablePointer` provides no automated
/// memory management or alignment guarantees. You are responsible for
/// handling the life cycle of any memory you work with through unsafe
/// pointers to avoid leaks or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeMutablePointer` type to access and
/// manage memory that has been bound to a specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeMutablePointer` instance can be in
/// one of several states. Many pointer operations must only be applied to
/// pointers with memory in a specific state---you must keep track of the
/// state of the memory you are working with and understand the changes to
/// that state that different operations perform. Memory can be untyped and
/// uninitialized, bound to a type and uninitialized, or bound to a type and
/// initialized to a value. Finally, memory that was allocated previously may
/// have been deallocated, leaving existing pointers referencing unallocated
/// memory.
///
/// Uninitialized Memory
/// --------------------
///
/// Memory that has just been allocated through a typed pointer or has been
/// deinitialized is in an *uninitialized* state. Uninitialized memory must be
/// initialized before it can be accessed for reading.
///
/// You can use methods like `initialize(to:count:)`, `initialize(from:count:)`,
/// and `moveInitialize(from:count:)` to initialize the memory referenced by a
/// pointer with a value or series of values.
///
/// Initialized Memory
/// ------------------
///
/// *Initialized* memory has a value that can be read using a pointer's
/// `pointee` property or through subscript notation. In the following
/// example, `ptr` is a pointer to memory initialized with a value of `23`:
///
/// let ptr: UnsafeMutablePointer<Int> = ...
/// // ptr.pointee == 23
/// // ptr[0] == 23
///
/// Accessing a Pointer's Memory as a Different Type
/// ================================================
///
/// When you access memory through an `UnsafeMutablePointer` instance, the
/// `Pointee` type must be consistent with the bound type of the memory. If
/// you do need to access memory that is bound to one type as a different
/// type, Swift's pointer types provide type-safe ways to temporarily or
/// permanently change the bound type of the memory, or to load typed
/// instances directly from raw memory.
///
/// An `UnsafeMutablePointer<UInt8>` instance allocated with eight bytes of
/// memory, `uint8Pointer`, will be used for the examples below.
///
/// var bytes: [UInt8] = [39, 77, 111, 111, 102, 33, 39, 0]
/// let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 8)
/// uint8Pointer.initialize(from: &bytes, count: 8)
///
/// When you only need to temporarily access a pointer's memory as a different
/// type, use the `withMemoryRebound(to:capacity:)` method. For example, you
/// can use this method to call an API that expects a pointer to a different
/// type that is layout compatible with your pointer's `Pointee`. The following
/// code temporarily rebinds the memory that `uint8Pointer` references from
/// `UInt8` to `Int8` to call the imported C `strlen` function.
///
/// // Imported from C
/// func strlen(_ __s: UnsafePointer<Int8>!) -> UInt
///
/// let length = uint8Pointer.withMemoryRebound(to: Int8.self, capacity: 8) {
/// return strlen($0)
/// }
/// // length == 7
///
/// When you need to permanently rebind memory to a different type, first
/// obtain a raw pointer to the memory and then call the
/// `bindMemory(to:capacity:)` method on the raw pointer. The following
/// example binds the memory referenced by `uint8Pointer` to one instance of
/// the `UInt64` type:
///
/// let uint64Pointer = UnsafeMutableRawPointer(uint8Pointer)
/// .bindMemory(to: UInt64.self, capacity: 1)
///
/// After rebinding the memory referenced by `uint8Pointer` to `UInt64`,
/// accessing that pointer's referenced memory as a `UInt8` instance is
/// undefined.
///
/// var fullInteger = uint64Pointer.pointee // OK
/// var firstByte = uint8Pointer.pointee // undefined
///
/// Alternatively, you can access the same memory as a different type without
/// rebinding through untyped memory access, so long as the bound type and the
/// destination type are trivial types. Convert your pointer to an
/// `UnsafeMutableRawPointer` instance and then use the raw pointer's
/// `load(fromByteOffset:as:)` and `storeBytes(of:toByteOffset:as:)` methods
/// to read and write values.
///
/// let rawPointer = UnsafeMutableRawPointer(uint64Pointer)
/// let fullInteger = rawPointer.load(as: UInt64.self) // OK
/// let firstByte = rawPointer.load(as: UInt8.self) // OK
///
/// Performing Typed Pointer Arithmetic
/// ===================================
///
/// Pointer arithmetic with a typed pointer is counted in strides of the
/// pointer's `Pointee` type. When you add to or subtract from an `UnsafeMutablePointer`
/// instance, the result is a new pointer of the same type, offset by that
/// number of instances of the `Pointee` type.
///
/// // 'intPointer' points to memory initialized with [10, 20, 30, 40]
/// let intPointer: UnsafeMutablePointer<Int> = ...
///
/// // Load the first value in memory
/// let x = intPointer.pointee
/// // x == 10
///
/// // Load the third value in memory
/// let offsetPointer = intPointer + 2
/// let y = offsetPointer.pointee
/// // y == 30
///
/// You can also use subscript notation to access the value in memory at a
/// specific offset.
///
/// let z = intPointer[2]
/// // z == 30
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeMutablePointer` parameter, you can pass
/// an instance of that specific pointer type or use Swift's implicit bridging
/// to pass a compatible pointer.
///
/// For example, the `printInt(atAddress:)` function in the following code
/// sample expects an `UnsafeMutablePointer<Int>` instance as its first parameter:
///
/// func printInt(atAddress p: UnsafeMutablePointer<Int>) {
/// print(p.pointee)
/// }
///
/// As is typical in Swift, you can call the `printInt(atAddress:)` function
/// with an `UnsafeMutablePointer` instance. This example passes `intPointer`, a mutable
/// pointer to an `Int` value, to `print(address:)`.
///
/// printInt(atAddress: intPointer)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. The following example passes a
/// pointer to the `value` variable by using inout syntax:
///
/// var value: Int = 23
/// printInt(atAddress: &value)
/// // Prints "23"
///
/// A mutable pointer to the elements of an array is implicitly created when
/// you pass the array using inout syntax. This example uses implicit bridging
/// to pass a pointer to the elements of `numbers` when calling
/// `printInt(atAddress:)`.
///
/// var numbers = [5, 10, 15, 20]
/// printInt(atAddress: &numbers)
/// // Prints "5"
///
/// No matter which way you call `printInt(atAddress:)`, Swift's type safety
/// guarantees that you can only pass a pointer to the type required by the
/// function---in this case, a pointer to an `Int`.
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeMutablePointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeMutablePointer<Int>(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen // unsafe-performance
public struct UnsafeMutablePointer<Pointee>: _Pointer {
/// A type that represents the distance between two pointers.
public typealias Distance = Int
/// The underlying raw (untyped) pointer.
public let _rawValue: Builtin.RawPointer
/// Creates an `UnsafeMutablePointer` from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a mutable typed pointer referencing the same memory as the given
/// immutable pointer.
///
/// - Parameter other: The immutable pointer to convert.
@_transparent
public init(@_nonEphemeral mutating other: UnsafePointer<Pointee>) {
self._rawValue = other._rawValue
}
/// Creates a mutable typed pointer referencing the same memory as the given
/// immutable pointer.
///
/// - Parameter other: The immutable pointer to convert. If `other` is `nil`,
/// the result is `nil`.
@_transparent
public init?(@_nonEphemeral mutating other: UnsafePointer<Pointee>?) {
guard let unwrapped = other else { return nil }
self.init(mutating: unwrapped)
}
/// Creates an immutable typed pointer referencing the same memory as the
/// given mutable pointer.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init(@_nonEphemeral _ other: UnsafeMutablePointer<Pointee>) {
self._rawValue = other._rawValue
}
/// Creates an immutable typed pointer referencing the same memory as the
/// given mutable pointer.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?(@_nonEphemeral _ other: UnsafeMutablePointer<Pointee>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
/// Allocates uninitialized memory for the specified number of instances of
/// type `Pointee`.
///
/// The resulting pointer references a region of memory that is bound to
/// `Pointee` and is `count * MemoryLayout<Pointee>.stride` bytes in size.
///
/// The following example allocates enough new memory to store four `Int`
/// instances and then initializes that memory with the elements of a range.
///
/// let intPointer = UnsafeMutablePointer<Int>.allocate(capacity: 4)
/// for i in 0..<4 {
/// (intPointer + i).initialize(to: i)
/// }
/// print(intPointer.pointee)
/// // Prints "0"
///
/// When you allocate memory, always remember to deallocate once you're
/// finished.
///
/// intPointer.deallocate()
///
/// - Parameter count: The amount of memory to allocate, counted in instances
/// of `Pointee`.
@inlinable
public static func allocate(capacity count: Int)
-> UnsafeMutablePointer<Pointee> {
let size = MemoryLayout<Pointee>.stride * count
// For any alignment <= _minAllocationAlignment, force alignment = 0.
// This forces the runtime's "aligned" allocation path so that
// deallocation does not require the original alignment.
//
// The runtime guarantees:
//
// align == 0 || align > _minAllocationAlignment:
// Runtime uses "aligned allocation".
//
// 0 < align <= _minAllocationAlignment:
// Runtime may use either malloc or "aligned allocation".
var align = Builtin.alignof(Pointee.self)
if Int(align) <= _minAllocationAlignment() {
align = (0)._builtinWordValue
}
let rawPtr = Builtin.allocRaw(size._builtinWordValue, align)
Builtin.bindMemory(rawPtr, count._builtinWordValue, Pointee.self)
return UnsafeMutablePointer(rawPtr)
}
/// Deallocates the memory block previously allocated at this pointer.
///
/// This pointer must be a pointer to the start of a previously allocated memory
/// block. The memory must not be initialized or `Pointee` must be a trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Accesses the instance referenced by this pointer.
///
/// When reading from the `pointee` property, the instance referenced by this
/// pointer must already be initialized. When `pointee` is used as the left
/// side of an assignment, the instance must be initialized or this
/// pointer's `Pointee` type must be a trivial type.
///
/// Do not assign an instance of a nontrivial type through `pointee` to
/// uninitialized memory. Instead, use an initializing method, such as
/// `initialize(to:count:)`.
@inlinable // unsafe-performance
public var pointee: Pointee {
@_transparent unsafeAddress {
return UnsafePointer(self)
}
@_transparent nonmutating unsafeMutableAddress {
return self
}
}
/// Initializes this pointer's memory with the specified number of
/// consecutive copies of the given value.
///
/// The destination memory must be uninitialized or the pointer's `Pointee`
/// must be a trivial type. After a call to `initialize(repeating:count:)`, the
/// memory referenced by this pointer is initialized.
///
/// - Parameters:
/// - repeatedValue: The instance to initialize this pointer's memory with.
/// - count: The number of consecutive copies of `newValue` to initialize.
/// `count` must not be negative.
@inlinable
public func initialize(repeating repeatedValue: Pointee, count: Int) {
// FIXME: add tests (since the `count` has been added)
_debugPrecondition(count >= 0,
"UnsafeMutablePointer.initialize(repeating:count:): negative count")
// Must not use `initializeFrom` with a `Collection` as that will introduce
// a cycle.
for offset in 0..<count {
Builtin.initialize(repeatedValue, (self + offset)._rawValue)
}
}
/// Initializes this pointer's memory with a single instance of the given value.
///
/// The destination memory must be uninitialized or the pointer's `Pointee`
/// must be a trivial type. After a call to `initialize(to:)`, the
/// memory referenced by this pointer is initialized. Calling this method is
/// roughly equivalent to calling `initialize(repeating:count:)` with a
/// `count` of 1.
///
/// - Parameters:
/// - value: The instance to initialize this pointer's pointee to.
@inlinable
public func initialize(to value: Pointee) {
Builtin.initialize(value, self._rawValue)
}
/// Retrieves and returns the referenced instance, returning the pointer's
/// memory to an uninitialized state.
///
/// Calling the `move()` method on a pointer `p` that references memory of
/// type `T` is equivalent to the following code, aside from any cost and
/// incidental side effects of copying and destroying the value:
///
/// let value: T = {
/// defer { p.deinitialize(count: 1) }
/// return p.pointee
/// }()
///
/// The memory referenced by this pointer must be initialized. After calling
/// `move()`, the memory is uninitialized.
///
/// - Returns: The instance referenced by this pointer.
@inlinable
public func move() -> Pointee {
return Builtin.take(_rawValue)
}
/// Replaces this pointer's memory with the specified number of
/// consecutive copies of the given value.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `assign(repeating:count:)`, the region is initialized.
///
/// - Parameters:
/// - repeatedValue: The instance to assign this pointer's memory to.
/// - count: The number of consecutive copies of `newValue` to assign.
/// `count` must not be negative.
@inlinable
public func assign(repeating repeatedValue: Pointee, count: Int) {
_debugPrecondition(count >= 0, "UnsafeMutablePointer.assign(repeating:count:) with negative count")
for i in 0..<count {
self[i] = repeatedValue
}
}
/// Replaces this pointer's initialized memory with the specified number of
/// instances from the given pointer's memory.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `assign(from:count:)`, the region is initialized.
///
/// - Note: Returns without performing work if `self` and `source` are equal.
///
/// - Parameters:
/// - source: A pointer to at least `count` initialized instances of type
/// `Pointee`. The memory regions referenced by `source` and this
/// pointer may overlap.
/// - count: The number of instances to copy from the memory referenced by
/// `source` to this pointer's memory. `count` must not be negative.
@inlinable
public func assign(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.assign with negative count")
if UnsafePointer(self) < source || UnsafePointer(self) >= source + count {
// assign forward from a disjoint or following overlapping range.
Builtin.assignCopyArrayFrontToBack(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// self[i] = source[i]
// }
}
else if UnsafePointer(self) != source {
// assign backward from a non-following overlapping range.
Builtin.assignCopyArrayBackToFront(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var i = count-1
// while i >= 0 {
// self[i] = source[i]
// i -= 1
// }
}
}
/// Moves instances from initialized source memory into the uninitialized
/// memory referenced by this pointer, leaving the source memory
/// uninitialized and the memory referenced by this pointer initialized.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be uninitialized or
/// `Pointee` must be a trivial type. After calling
/// `moveInitialize(from:count:)`, the region is initialized and the memory
/// region `source..<(source + count)` is uninitialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer may overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func moveInitialize(
@_nonEphemeral from source: UnsafeMutablePointer, count: Int
) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.moveInitialize with negative count")
if self < source || self >= source + count {
// initialize forward from a disjoint or following overlapping range.
Builtin.takeArrayFrontToBack(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self + i).initialize(to: (source + i).move())
// }
}
else {
// initialize backward from a non-following overlapping range.
Builtin.takeArrayBackToFront(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var src = source + count
// var dst = self + count
// while dst != self {
// (--dst).initialize(to: (--src).move())
// }
}
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be uninitialized or
/// `Pointee` must be a trivial type. After calling
/// `initialize(from:count:)`, the region is initialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func initialize(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.initialize with negative count")
_debugPrecondition(
UnsafePointer(self) + count <= source ||
source + count <= UnsafePointer(self),
"UnsafeMutablePointer.initialize overlapping range")
Builtin.copyArray(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self + i).initialize(to: source[i])
// }
}
/// Replaces the memory referenced by this pointer with the values
/// starting at the given pointer, leaving the source memory uninitialized.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `moveAssign(from:count:)`, the region is initialized and the memory
/// region `source..<(source + count)` is uninitialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func moveAssign(
@_nonEphemeral from source: UnsafeMutablePointer, count: Int
) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.moveAssign(from:) with negative count")
_debugPrecondition(
self + count <= source || source + count <= self,
"moveAssign overlapping range")
Builtin.assignTakeArray(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// These builtins are equivalent to:
// for i in 0..<count {
// self[i] = (source + i).move()
// }
}
/// Deinitializes the specified number of values starting at this pointer.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized. After
/// calling `deinitialize(count:)`, the memory is uninitialized, but still
/// bound to the `Pointee` type.
///
/// - Parameter count: The number of instances to deinitialize. `count` must
/// not be negative.
/// - Returns: A raw pointer to the same address as this pointer. The memory
/// referenced by the returned raw pointer is still bound to `Pointee`.
@inlinable
@discardableResult
public func deinitialize(count: Int) -> UnsafeMutableRawPointer {
_debugPrecondition(count >= 0, "UnsafeMutablePointer.deinitialize with negative count")
// FIXME: optimization should be implemented, where if the `count` value
// is 1, the `Builtin.destroy(Pointee.self, _rawValue)` gets called.
Builtin.destroyArray(Pointee.self, _rawValue, count._builtinWordValue)
return UnsafeMutableRawPointer(self)
}
/// Executes the given closure while temporarily binding the specified number
/// of instances to the given type.
///
/// Use this method when you have a pointer to memory bound to one type and
/// you need to access that memory as instances of another type. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized.
///
/// The following example temporarily rebinds the memory of a `UInt64`
/// pointer to `Int64`, then accesses a property on the signed integer.
///
/// let uint64Pointer: UnsafeMutablePointer<UInt64> = fetchValue()
/// let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self, capacity: 1) { ptr in
/// return ptr.pointee < 0
/// }
///
/// Because this pointer's memory is no longer bound to its `Pointee` type
/// while the `body` closure executes, do not access memory using the
/// original pointer from within `body`. Instead, use the `body` closure's
/// pointer argument to access the values in memory as instances of type
/// `T`.
///
/// After executing `body`, this method rebinds memory back to the original
/// `Pointee` type.
///
/// - Note: Only use this method to rebind the pointer's memory to a type
/// with the same size and stride as the currently bound `Pointee` type.
/// To bind a region of memory to a type that is a different size, convert
/// the pointer to a raw pointer and use the `bindMemory(to:capacity:)`
/// method.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. The type `T` must be the same size and be layout compatible
/// with the pointer's `Pointee` type.
/// - count: The number of instances of `Pointee` to bind to `type`.
/// - body: A closure that takes a mutable typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result {
Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer {
Builtin.bindMemory(_rawValue, count._builtinWordValue, Pointee.self)
}
return try body(UnsafeMutablePointer<T>(_rawValue))
}
/// Accesses the pointee at the specified offset from this pointer.
///
/// For a pointer `p`, the memory at `p + i` must be initialized when reading
/// the value by using the subscript. When the subscript is used as the left
/// side of an assignment, the memory at `p + i` must be initialized or
/// the pointer's `Pointee` type must be a trivial type.
///
/// Do not assign an instance of a nontrivial type through the subscript to
/// uninitialized memory. Instead, use an initializing method, such as
/// `initialize(to:count:)`.
///
/// - Parameter i: The offset from this pointer at which to access an
/// instance, measured in strides of the pointer's `Pointee` type.
@inlinable
public subscript(i: Int) -> Pointee {
@_transparent
unsafeAddress {
return UnsafePointer(self + i)
}
@_transparent
nonmutating unsafeMutableAddress {
return self + i
}
}
@inlinable // unsafe-performance
internal static var _max: UnsafeMutablePointer {
return UnsafeMutablePointer(
bitPattern: 0 as Int &- MemoryLayout<Pointee>.stride
)._unsafelyUnwrappedUnchecked
}
}
| apache-2.0 | bca773d17b3d116d0335b741417a7d55 | 41.96146 | 103 | 0.674221 | 4.403326 | false | false | false | false |
con-beo-vang/Spendy | Spendy/Views/Account Detail/TransactionCell.swift | 1 | 2042 | //
// TransactionCell.swift
// Spendy
//
// Created by Dave Vo on 9/19/15.
// Copyright (c) 2015 Cheetah. All rights reserved.
//
import UIKit
class TransactionCell: UITableViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var noteLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var balanceLabel: UILabel!
var currentAccount: Account?
var transaction: Transaction! {
didSet {
if let noteText = transaction.note {
if noteText.isEmpty {
noteLabel.text = transaction.categoryName
} else {
noteLabel.text = noteText
}
} else {
noteLabel.text = transaction.categoryName
}
amountLabel.text = transaction.formattedAmount()
amountLabel.textColor = KindColor.forTransaction(transaction, account: currentAccount!)
dateLabel.text = transaction.dateOnly()
// TODO: which balance to display
if let account = currentAccount,
toAccount = transaction.toAccount
where account == toAccount {
balanceLabel.text = transaction.formattedToBalanceSnapshot()
} else {
balanceLabel.text = transaction.formattedBalanceSnapshot()
}
if let icon = transaction.categoryIcon {
iconView.image = Helper.sharedInstance.createIcon(icon)
iconView.setNewTintColor(UIColor.whiteColor())
switch transaction.kind! {
case CategoryType.Expense.rawValue:
iconView.layer.backgroundColor = Color.expenseColor.CGColor
case CategoryType.Income.rawValue:
iconView.layer.backgroundColor = Color.incomeColor.CGColor
case CategoryType.Transfer.rawValue:
iconView.layer.backgroundColor = Color.transferIconColor.CGColor
default:
break
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
Helper.sharedInstance.setIconLayer(iconView)
}
}
| mit | d8dde20557660a87dcb7d930778744a3 | 28.594203 | 93 | 0.664545 | 4.861905 | false | false | false | false |
crazypoo/PTools | Pods/Appz/Appz/Appz/Apps/AirLaunch.swift | 2 | 1027 | //
// AirLaunch.swift
// Pods
//
// Created by Mariam AlJamea on 1/25/16.
// Copyright © 2016 kitz. All rights reserved.
//
public extension Applications {
public struct AirLaunch: ExternalApplication {
public typealias ActionType = Applications.AirLaunch.Action
public let scheme = "airlaunch:"
public let fallbackURL = "http://www.iosappdownload.org/download.php?boaID=846864"
public let appStoreId = "993479740"
public init() {}
}
}
// MARK: - Actions
public extension Applications.AirLaunch {
public enum Action {
case open
}
}
extension Applications.AirLaunch.Action: ExternalApplicationAction {
public var paths: ActionPaths {
switch self {
case .open:
return ActionPaths(
app: Path(
pathComponents: ["app"],
queryParameters: [:]
),
web: Path()
)
}
}
}
| mit | f5c42da88281edc1c8f5edbbc38f5aca | 20.829787 | 90 | 0.551657 | 4.816901 | false | false | false | false |
soapyigu/LeetCode_Swift | String/LongestSubstringMostTwoDistinctCharacters.swift | 1 | 1352 | /**
* Question Link: https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
* Primary idea: Slding window, use dictionary to check substring is valid or not, and
note to handle the end of string edge case
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class LongestSubstringMostTwoDistinctCharacters {
func lengthOfLongestSubstringTwoDistinct(_ s: String) -> Int {
var start = 0, longest = 0, charFreq = [Character: Int]()
let sChars = Array(s)
for (i, char) in sChars.enumerated() {
if let freq = charFreq[char] {
charFreq[char] = freq + 1
} else {
if charFreq.count == 2 {
longest = max(longest, i - start)
while charFreq.count == 2 {
let charStart = sChars[start]
charFreq[charStart]! -= 1
if charFreq[charStart] == 0 {
charFreq[charStart] = nil
}
start += 1
}
}
charFreq[char] = 1
}
}
return max(longest, sChars.count - start)
}
} | mit | 27ade3be793f16abe545a7f3f71964f4 | 32.825 | 103 | 0.460059 | 4.828571 | false | false | false | false |
SwiftAndroid/swift | test/expr/unary/selector/selector.swift | 2 | 4066 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -disable-objc-attr-requires-foundation-module -parse %s -verify
import ObjectiveC
// REQUIRES: objc_interop
@objc class A { }
@objc class B { }
class C1 {
@objc init(a: A, b: B) { }
@objc func method1(_ a: A, b: B) { }
@objc(someMethodWithA:B:) func method2(_ a: A, b: B) { }
@objc class func method3(_ a: A, b: B) { } // expected-note{{found this candidate}}
@objc class func method3(a: A, b: B) { } // expected-note{{found this candidate}}
@objc var a: A = A() // expected-note{{'a' declared here}}
@objc func getC1() -> AnyObject { return self }
@objc func testUnqualifiedSelector(_ a: A, b: B) {
_ = #selector(testUnqualifiedSelector(_:b:))
let testUnqualifiedSelector = 1
_ = #selector(testUnqualifiedSelector(_:b:))
_ = testUnqualifiedSelector // suppress unused warning
}
@objc func testParam(_ testParam: A) { // expected-note{{'testParam' declared here}}
_ = #selector(testParam) // expected-error{{argument of '#selector' cannot refer to a parameter}}
}
@objc func testVariable() {
let testVariable = 1 // expected-note{{'testVariable' declared here}}
_ = #selector(testVariable) // expected-error{{argument of '#selector' cannot refer to a variable}}
}
}
@objc protocol P1 {
func method4(_ a: A, b: B)
static func method5(_ a: B, b: B)
}
extension C1 {
final func method6() { } // expected-note{{add '@objc' to expose this method to Objective-C}}{{3-3=@objc }}
}
func testSelector(_ c1: C1, p1: P1, obj: AnyObject) {
// Instance methods on an instance
let sel1 = #selector(c1.method1)
_ = #selector(c1.method1(_:b:))
_ = #selector(c1.method2)
// Instance methods on a class.
_ = #selector(C1.method1)
_ = #selector(C1.method1(_:b:))
_ = #selector(C1.method2)
// Class methods on a class.
_ = #selector(C1.method3(_:b:))
_ = #selector(C1.method3(a:b:))
// Methods on a protocol.
_ = #selector(P1.method4)
_ = #selector(P1.method4(_:b:))
_ = #selector(P1.method5) // expected-error{{static member 'method5' cannot be used on protocol metatype 'P1.Protocol'}}
_ = #selector(P1.method5(_:b:)) // expected-error{{static member 'method5(_:b:)' cannot be used on protocol metatype 'P1.Protocol'}}
_ = #selector(p1.method4)
_ = #selector(p1.method4(_:b:))
_ = #selector(p1.dynamicType.method5)
_ = #selector(p1.dynamicType.method5(_:b:))
// Interesting expressions that refer to methods.
_ = #selector(Swift.AnyObject.method1)
_ = #selector(AnyObject.method1!)
_ = #selector(obj.getC1?().method1)
// Initializers
_ = #selector(C1.init(a:b:))
// Make sure the result has type "ObjectiveC.Selector"
let sel2: Selector
sel2 = sel1
_ = sel2
}
func testAmbiguity() {
_ = #selector(C1.method3) // expected-error{{ambiguous use of 'method3(_:b:)'}}
}
func testUnusedSelector() {
#selector(C1.getC1) // expected-warning{{result of '#selector' is unused}}
}
func testProperties(_ c1: C1) {
_ = #selector(c1.a) // expected-error{{argument of '#selector' cannot refer to a property}}
_ = #selector(C1.a) // FIXME poor diagnostic: expected-error{{instance member 'a' cannot be used on type 'C1'}}
}
func testNonObjC(_ c1: C1) {
_ = #selector(c1.method6) // expected-error{{argument of '#selector' refers to a method that is not exposed to Objective-C}}
}
func testParseErrors1() {
_ = #selector foo // expected-error{{expected '(' following '#selector'}}
}
func testParseErrors2() {
_ = #selector( // expected-error{{expected expression naming a method within '#selector(...)'}}
}
func testParseErrors3(_ c1: C1) {
_ = #selector( // expected-note{{to match this opening '('}}
c1.method1(_:b:) // expected-error{{expected ')' to complete '#selector' expression}}
}
func testParseErrors4() {
// Subscripts
_ = #selector(C1.subscript) // expected-error{{expected member name following '.'}}
// expected-error@-1{{consecutive statements on a line must be separated by ';'}}
// expected-error@-2{{expected '(' for subscript parameters}}
}
| apache-2.0 | 43be88af2d46dd8a061a19891e1a12a1 | 32.327869 | 134 | 0.653222 | 3.286985 | false | true | false | false |
mbrandonw/naturally-swift | naturally-swift/naturally-swift/Array.swift | 1 | 643 |
/// MARK: Functor
extension Array : Functor {
typealias _A = T
typealias _B = Any
typealias _FA = [_A]
typealias _FB = [_B]
public static func fmap <_A, _B> (f: _A -> _B) -> [_A] -> [_B] {
return {xs in
return xs.map(f)
}
}
}
public func <%> <_A, _B> (f: _A -> _B, xs: [_A]) -> [_B] {
return xs.map(f)
}
/// MARK: Monad
extension Array : Monad {
public static func unit (x: _A) -> [_A] {
return [x]
}
public static func bind <_B> (xs: [_A], f: _A -> [_B]) -> [_B] {
return xs.map(f).reduce([], +)
}
}
public func >>= <_A, _B> (xs: [_A], f: _A -> [_B]) -> [_B] {
return Array.bind(xs, f)
}
| mit | 45524ec8a356ea26235a57560efeeb3c | 17.371429 | 66 | 0.468118 | 2.531496 | false | false | false | false |
kingreza/UIDiagonal | DiagonalCategory/UIDiagonalView.swift | 1 | 6835 | //
// UIDiagonalView.swift
// UIKitCatalog
//
// Created by Reza Shirazian on 2017-04-15.
// Copyright © 2017 Apple. All rights reserved.
//
import UIKit
class UIDiagonalView: UIView {
var delegate: UIDiagonalDelegate?
let DEVICE_WIDTH = 1920.0
var rows = [UIDiagonalViewCell]()
private var cellWidth: Double {
return self.cellChopWidth * (4 / 3)
}
private var cellChopWidth: Double {
if let delegate = self.delegate {
return DEVICE_WIDTH / Double(delegate.numberOfCells(self))
}
return 0
}
private var offset: Double {
return cellWidth - cellChopWidth
}
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.red
}
convenience init() {
self.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.red
}
override func didMoveToSuperview() {
initSubviews()
}
func initSubviews() {
if let delegate = self.delegate {
let count = delegate.numberOfCells(self)
let width = self.cellWidth
for i in 0..<count {
let cell = delegate.diagonalView(self, cellForRowAt: i)
cell.tag = i + 1
cell.layer.zPosition = CGFloat(count - i)
cell.index = i
cell.offset = offset
cell.didSetupCell()
let container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
container.tag = i + 1
rows.append(cell)
container.addSubview(cell)
container.leftAnchor.constraint(equalTo: cell.leftAnchor).isActive = true
container.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
container.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true
container.rightAnchor.constraint(equalTo: cell.rightAnchor).isActive = true
container.layer.zPosition = CGFloat(count - i)
container.accessibilityIdentifier = "container"
self.addSubview(container)
let top = NSLayoutConstraint(item: container,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: 0)
let left = NSLayoutConstraint(item: container,
attribute: .left,
relatedBy: .equal,
toItem: i == 0 ? self : self.subviews.first{$0.tag == i}!,
attribute: i == 0 ? .left : .right,
multiplier: 1.0,
constant: i == 0 ? CGFloat(-self.offset / 2.0) : CGFloat(-self.offset))
let bottom = NSLayoutConstraint(item: container,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1.0,
constant: 0)
let width = NSLayoutConstraint(item: container,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: CGFloat(width))
cell.topConstraint = top
cell.leftConstraint = left
cell.bottomConstraint = bottom
cell.widthConstraint = width
self.addConstraints([top, left, bottom, width])
cell.didSetupConstraints()
}
}
}
override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
for press in presses {
if (press.type == .select) {
if let focusedCell = UIScreen.main.focusedView as? UIDiagonalViewCell {
if let indexPath = self.indexPath(for: focusedCell) {
print("IndexPath is \(indexPath)")
if let delegate = self.delegate {
delegate.diagonalView(self, didSelectRowAt: indexPath)
}
}
}
} else {
super.pressesEnded(presses, with: event)
}
}
}
func rowAtIndex(index: Int) -> UIDiagonalViewCell? {
return rows[index]
}
func indexPath(for cell: UIDiagonalViewCell) -> Int? {
if let row = self.rows.index(where: {$0 === cell}) {
return row
}
return nil
}
override func layoutSubviews() {
super.layoutSubviews()
if let delegate = self.delegate {
let count = delegate.numberOfCells(self)
for i in 0..<count - 1 {
if let container = self.viewWithTag(i + 1) {
let mask = CAShapeLayer()
mask.frame = container.layer.bounds
let width = container.layer.frame.width
let height = container.layer.frame.height
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: width, y: 0))
path.addLine(to: CGPoint(x: CGFloat(self.cellChopWidth), y: height))
path.addLine(to: CGPoint(x: 0, y: height))
path.close()
mask.name = "sliced"
mask.path = path.cgPath
container.layer.mask = mask
}
}
}
}
}
| mit | 926e233186423079e7511457f16792b9 | 37.610169 | 117 | 0.451858 | 5.891379 | false | false | false | false |
valentin7/wwdc2015app | Valentin-Perez/Valentin-Perez/Valentin-Perez/MenuTransitionManager.swift | 1 | 6160 | //
// MenuTransitionManager.swift
// ValentinWWDC2015
//
// Created by Valentin Perez on 4/26/15.
// Copyright (c) 2015 Valentin Perez. All rights reserved.
//
//
// MenuTransitionManager.swift
// Menu
//
// Created by Mathew Sanders on 9/7/14.
// Copyright (c) 2014 Mat. All rights reserved.
//
import UIKit
class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = false
// MARK: UIViewControllerAnimatedTransitioning protocol methods
// animate a change from one viewcontroller to another
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView()
// create a tuple of our screens
let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!)
// assign references to our menu view controller and the 'bottom' view controller from the tuple
// remember that our moreInfoViewController will alternate between the from and to view controller depending if we're presenting or dismissing
let moreInfoViewController = !self.presenting ? screens.from as! MoreInfoViewController : screens.to as! MoreInfoViewController
let bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController
let menuView = moreInfoViewController.view
let bottomView = bottomViewController.view
// prepare menu items to slide in
if (self.presenting){
self.offStageMenuController(moreInfoViewController)
}
// add the both views to our view controller
container.addSubview(bottomView)
container.addSubview(menuView)
let duration = self.transitionDuration(transitionContext)
// perform the animation!
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: nil, animations: {
if (self.presenting){
self.onStageMenuController(moreInfoViewController) // onstage items: slide in
}
else {
self.offStageMenuController(moreInfoViewController) // offstage items: slide out
}
}, completion: { finished in
// tell our transitionContext object that we've finished animating
transitionContext.completeTransition(true)
// bug: we have to manually add our 'to view' back http://openradar.appspot.com/radar?id=5320103646199808
UIApplication.sharedApplication().keyWindow?.addSubview(screens.to.view)
})
}
func offStage(amount: CGFloat) -> CGAffineTransform {
return CGAffineTransformMakeTranslation(amount, 0)
}
func offStageMenuController(moreInfoViewController: MoreInfoViewController){
moreInfoViewController.view.alpha = 0
// setup paramaters for 2D transitions for animations
let topRowOffset :CGFloat = 300
let middleRowOffset :CGFloat = 150
let bottomRowOffset :CGFloat = 50
moreInfoViewController.descriptionTextView.transform = self.offStage(-topRowOffset)
moreInfoViewController.actionButton.transform = self.offStage(topRowOffset)
// moreInfoViewController.quotePostIcon.transform = self.offStage(-middleRowOffset)
// moreInfoViewController.quotePostLabel.transform = self.offStage(-middleRowOffset)
//
// moreInfoViewController.chatPostIcon.transform = self.offStage(-bottomRowOffset)
// moreInfoViewController.chatPostLabel.transform = self.offStage(-bottomRowOffset)
//
// moreInfoViewController.photoPostIcon.transform = self.offStage(topRowOffset)
// moreInfoViewController.photoPostLabel.transform = self.offStage(topRowOffset)
//
// moreInfoViewController.linkPostIcon.transform = self.offStage(middleRowOffset)
// moreInfoViewController.linkPostLabel.transform = self.offStage(middleRowOffset)
//
// moreInfoViewController.audioPostIcon.transform = self.offStage(bottomRowOffset)
// moreInfoViewController.audioPostLabel.transform = self.offStage(bottomRowOffset)
}
func onStageMenuController(moreInfoViewController: MoreInfoViewController){
// prepare menu to fade in
moreInfoViewController.view.alpha = 1
moreInfoViewController.actionButton.transform = CGAffineTransformIdentity
moreInfoViewController.descriptionTextView.transform = CGAffineTransformIdentity
}
// return how many seconds the transiton animation will take
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.5
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animator when presenting a viewcontroller
// rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
// return the animator used when dismissing from a viewcontroller
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
| mit | 1e838094ccf9160cbd1fc2a47bb4711f | 43 | 233 | 0.699188 | 6.009756 | false | false | false | false |
prolificinteractive/IQKeyboardManager | IQKeybordManagerSwift/IQTextView/IQTextView.swift | 1 | 3451 | //
// IQTextView.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-14 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/** @abstract UITextView with placeholder support */
class IQTextView : UITextView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private var placeholderLabel: UILabel?
/** @abstract To set textView's placeholder text. Default is ni. */
var placeholder : String? {
get {
return placeholderLabel?.text
}
set {
if placeholderLabel == nil {
placeholderLabel = UILabel(frame: CGRectInset(self.bounds, 5, 0))
if let unwrappedPlaceholderLabel = placeholderLabel {
unwrappedPlaceholderLabel.autoresizingMask = .FlexibleWidth | .FlexibleHeight
unwrappedPlaceholderLabel.lineBreakMode = .ByWordWrapping
unwrappedPlaceholderLabel.numberOfLines = 0
unwrappedPlaceholderLabel.font = font?
unwrappedPlaceholderLabel.backgroundColor = UIColor.clearColor()
unwrappedPlaceholderLabel.textColor = UIColor(white: 0.7, alpha: 1.0)
unwrappedPlaceholderLabel.alpha = 0
addSubview(unwrappedPlaceholderLabel)
}
}
placeholderLabel?.text = newValue
refreshPlaceholder()
}
}
private func refreshPlaceholder() {
if countElements(text) != 0 {
placeholderLabel?.alpha = 0
} else {
placeholderLabel?.alpha = 1
}
}
override var text: String! {
didSet {
refreshPlaceholder()
}
}
override var font : UIFont? {
didSet {
if let unwrappedFont = font {
placeholderLabel?.font = unwrappedFont
} else {
placeholderLabel?.font = UIFont.systemFontOfSize(12)
}
}
}
override var delegate : UITextViewDelegate? {
get {
refreshPlaceholder()
return super.delegate
}
set {
}
}
}
| mit | 6fd55ebcebb735d5ab35ecbcad4c009a | 30.372727 | 97 | 0.598088 | 5.819562 | false | false | false | false |
mdiep/Tentacle | Sources/Tentacle/Release.swift | 1 | 4424 | //
// Release.swift
// Tentacle
//
// Created by Matt Diephouse on 3/3/16.
// Copyright © 2016 Matt Diephouse. All rights reserved.
//
import Foundation
extension Repository {
/// A request to get the latest release for the repository.
///
/// If the repository doesn't have any releases, this will result in a `.doesNotExist` error.
///
/// https://developer.github.com/v3/repos/releases/#get-the-latest-release
public var latestRelease: Request<Release> {
return Request(method: .get, path: "/repos/\(owner)/\(name)/releases/latest")
}
/// A request for the release corresponding to the given tag.
///
/// If the tag exists, but there's not a correspoding GitHub Release, this will result in a
/// `.doesNotExist` error. This is indistinguishable from a nonexistent tag.
///
/// https://developer.github.com/v3/repos/releases/#get-a-release-by-tag-name
public func release(forTag tag: String) -> Request<Release> {
return Request(method: .get, path: "/repos/\(owner)/\(name)/releases/tags/\(tag)")
}
/// A request for the releases in the repository.
///
/// https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository
public var releases: Request<[Release]> {
return Request(method: .get, path: "/repos/\(owner)/\(name)/releases")
}
}
/// A Release of a Repository.
public struct Release: CustomStringConvertible, ResourceType, Identifiable {
/// An Asset attached to a Release.
public struct Asset: CustomStringConvertible, ResourceType, Identifiable {
/// The unique ID for this release asset.
public let id: ID<Asset>
/// The filename of this asset.
public let name: String
/// The MIME type of this asset.
public let contentType: String
/// The URL at which the asset can be downloaded directly.
public let url: URL
/// The URL at which the asset can be downloaded via the API.
public let apiURL: URL
public var description: String {
return "\(url)"
}
public init(id: ID<Asset>, name: String, contentType: String, url: URL, apiURL: URL) {
self.id = id
self.name = name
self.contentType = contentType
self.url = url
self.apiURL = apiURL
}
private enum CodingKeys: String, CodingKey {
case id
case name
case contentType = "content_type"
case url = "browser_download_url"
case apiURL = "url"
}
}
/// The unique ID of the release.
public let id: ID<Release>
/// Whether this release is a draft (only visible to the authenticted user).
public let isDraft: Bool
/// Whether this release represents a prerelease version.
public let isPrerelease: Bool
/// The name of the tag upon which this release is based.
public let tag: String
/// The name of the release.
public let name: String?
/// The web URL of the release.
public let url: URL
/// Any assets attached to the release.
public let assets: [Asset]
public var description: String {
return "\(url)"
}
public init(id: ID<Release>, tag: String, url: URL, name: String? = nil, isDraft: Bool = false, isPrerelease: Bool = false, assets: [Asset]) {
self.id = id
self.tag = tag
self.url = url
self.name = name
self.isDraft = isDraft
self.isPrerelease = isPrerelease
self.assets = assets
}
private enum CodingKeys: String, CodingKey {
case id
case isDraft = "draft"
case isPrerelease = "prerelease"
case tag = "tag_name"
case name
case url = "html_url"
case assets
}
}
extension Release.Asset: Equatable {
public static func ==(lhs: Release.Asset, rhs: Release.Asset) -> Bool {
return lhs.id == rhs.id && lhs.url == rhs.url
}
}
extension Release: Equatable {
public static func ==(lhs: Release, rhs: Release) -> Bool {
return lhs.id == rhs.id
&& lhs.tag == rhs.tag
&& lhs.url == rhs.url
&& lhs.name == rhs.name
&& lhs.isDraft == rhs.isDraft
&& lhs.isPrerelease == rhs.isPrerelease
&& lhs.assets == rhs.assets
}
}
| mit | 5aee8b19141fdd65711173349f2ded6a | 30.368794 | 146 | 0.599819 | 4.294175 | false | false | false | false |
podverse/podverse-ios | Podverse/PlayerHistoryItem.swift | 1 | 15046 | //
// PlayerHistoryItem.swift
// Podverse
//
// Created by Mitchell Downey on 5/21/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import UIKit
extension Notification.Name {
static let clipUpdated = Notification.Name("clipUpdated")
}
class PlayerHistoryItem: NSObject, NSCoding {
var mediaRefId:String?
let podcastId:String?
let podcastFeedUrl:String?
let podcastTitle:String?
let podcastImageUrl:String?
let episodeDuration:Int64?
let episodeId:String?
let episodeImageUrl:String?
let episodeMediaUrl:String?
let episodePubDate:Date?
let episodeSummary:String?
let episodeTitle:String?
var startTime:Int64? // If startTime and endTime = 0, then item is a clip, else it is an episode
var endTime:Int64?
var clipTitle:String?
var ownerName:String?
var ownerId:String?
var hasReachedEnd:Bool?
var lastPlaybackPosition:Int64?
var lastUpdated:Date?
var isPublic:Bool?
required init(mediaRefId:String? = nil, podcastId:String?, podcastFeedUrl:String? = nil, podcastTitle:String? = nil, podcastImageUrl:String? = nil, episodeDuration: Int64? = nil, episodeId:String? = nil, episodeMediaUrl:String? = nil, episodeTitle:String? = nil, episodeImageUrl:String? = nil, episodeSummary:String? = nil, episodePubDate:Date? = nil, startTime:Int64? = nil, endTime:Int64? = nil, clipTitle:String? = nil, ownerName:String? = nil, ownerId:String? = nil, hasReachedEnd:Bool, lastPlaybackPosition:Int64? = 0, lastUpdated:Date? = nil, isPublic:Bool? = false) {
self.mediaRefId = mediaRefId
self.podcastId = podcastId
self.podcastFeedUrl = podcastFeedUrl
self.podcastTitle = podcastTitle
self.podcastImageUrl = podcastImageUrl
self.episodeDuration = episodeDuration
self.episodeId = episodeId
self.episodeMediaUrl = episodeMediaUrl
self.episodeImageUrl = episodeImageUrl
self.episodePubDate = episodePubDate
self.episodeSummary = episodeSummary
self.episodeTitle = episodeTitle
self.startTime = startTime
self.endTime = endTime
self.clipTitle = clipTitle
self.ownerName = ownerName
self.ownerId = ownerId
self.hasReachedEnd = hasReachedEnd
self.lastPlaybackPosition = lastPlaybackPosition
self.lastUpdated = lastUpdated
self.isPublic = isPublic
}
required init(coder decoder: NSCoder) {
self.mediaRefId = decoder.decodeObject(forKey: "mediaRefId") as? String
self.podcastId = decoder.decodeObject(forKey: "podcastId") as? String
self.podcastFeedUrl = decoder.decodeObject(forKey: "podcastFeedUrl") as? String
self.podcastTitle = decoder.decodeObject(forKey: "podcastTitle") as? String
self.podcastImageUrl = decoder.decodeObject(forKey: "podcastImageUrl") as? String
self.episodeDuration = decoder.decodeObject(forKey: "episodeDuration") as? Int64
self.episodeId = decoder.decodeObject(forKey: "episodeId") as? String
self.episodeImageUrl = decoder.decodeObject(forKey: "episodeImageUrl") as? String
self.episodeMediaUrl = decoder.decodeObject(forKey: "episodeMediaUrl") as? String
self.episodeSummary = decoder.decodeObject(forKey: "episodeSummary") as? String
self.episodePubDate = decoder.decodeObject(forKey: "episodePubDate") as? Date
self.episodeTitle = decoder.decodeObject(forKey: "episodeTitle") as? String
self.startTime = decoder.decodeObject(forKey: "startTime") as? Int64 ?? 0
self.endTime = decoder.decodeObject(forKey: "endTime") as? Int64
self.clipTitle = decoder.decodeObject(forKey: "clipTitle") as? String
self.ownerName = decoder.decodeObject(forKey: "ownerName") as? String
self.ownerId = decoder.decodeObject(forKey: "ownerId") as? String
self.hasReachedEnd = decoder.decodeObject(forKey: "hasReachedEnd") as? Bool
self.lastPlaybackPosition = decoder.decodeObject(forKey: "lastPlaybackPosition") as? Int64
self.lastUpdated = decoder.decodeObject(forKey: "lastUpdated") as? Date
self.isPublic = decoder.decodeObject(forKey: "isPublic") as? Bool
}
func encode(with coder: NSCoder) {
coder.encode(mediaRefId, forKey: "mediaRefId")
coder.encode(podcastId, forKey: "podcastId")
coder.encode(podcastFeedUrl, forKey:"podcastFeedUrl")
coder.encode(podcastTitle, forKey:"podcastTitle")
coder.encode(podcastImageUrl, forKey:"podcastImageUrl")
coder.encode(episodeDuration, forKey:"episodeDuration")
coder.encode(episodeId, forKey:"episodeId")
coder.encode(episodeImageUrl, forKey:"episodeImageUrl")
coder.encode(episodeMediaUrl, forKey:"episodeMediaUrl")
coder.encode(episodePubDate, forKey:"episodePubDate")
coder.encode(episodeSummary, forKey:"episodeSummary")
coder.encode(episodeTitle, forKey:"episodeTitle")
coder.encode(startTime, forKey:"startTime")
coder.encode(endTime, forKey:"endTime")
coder.encode(clipTitle, forKey:"clipTitle")
coder.encode(ownerName, forKey:"ownerName")
coder.encode(ownerId, forKey:"ownerId")
coder.encode(hasReachedEnd, forKey:"hasReachedEnd")
coder.encode(lastPlaybackPosition, forKey:"lastPlaybackPosition")
coder.encode(lastUpdated, forKey:"lastUpdated")
coder.encode(isPublic, forKey:"isPublic")
}
func isClip() -> Bool {
if let startTime = self.startTime {
if startTime > 0 {
return true
}
} else if let endTime = self.endTime {
if endTime > 0 {
return true
}
}
return false
}
func convertClipToEpisode() -> PlayerHistoryItem {
self.clipTitle = nil
self.startTime = 0
self.endTime = nil
self.ownerName = nil
self.ownerId = nil
self.hasReachedEnd = false
self.lastPlaybackPosition = nil
self.lastUpdated = nil
return self
}
func readableStartAndEndTime() -> String? {
var time: String?
if let startTime = self.startTime {
if let endTime = self.endTime {
if endTime > 0 {
time = startTime.toMediaPlayerString() + " to " + endTime.toMediaPlayerString()
}
} else if startTime == 0 {
time = "--:--"
} else {
time = startTime.toMediaPlayerString() + " to " + "..."
}
}
return time
}
func convertToMediaRefPostString(shouldSaveFullEpisode: Bool = false) -> [String: Any] {
var values: [String: Any] = [:]
if shouldSaveFullEpisode {
if let episodeMediaUrl = self.episodeMediaUrl {
values["mediaRefId"] = "episode_" + episodeMediaUrl
}
} else {
if let mediaRefId = self.mediaRefId {
values["mediaRefId"] = mediaRefId
}
}
if let podcastId = self.podcastId {
values["podcastId"] = podcastId
}
if let podcastFeedUrl = self.podcastFeedUrl {
values["podcastFeedUrl"] = podcastFeedUrl
}
if let podcastTitle = self.podcastTitle {
values["podcastTitle"] = podcastTitle
}
if let podcastImageUrl = self.podcastImageUrl {
values["podcastImageUrl"] = podcastImageUrl
}
if let episodeDuration = self.episodeDuration {
values["episodeDuration"] = String(episodeDuration)
}
if let episodeId = self.episodeId {
values["episodeId"] = episodeId
}
if let episodeImageUrl = self.episodeImageUrl {
values["episodeImageUrl"] = episodeImageUrl
}
if let episodeMediaUrl = self.episodeMediaUrl {
values["episodeMediaUrl"] = episodeMediaUrl
}
if let episodePubDate = self.episodePubDate {
values["episodePubDate"] = episodePubDate.toString()
}
if let episodeSummary = self.episodeSummary {
values["episodeSummary"] = episodeSummary
}
if let episodeTitle = self.episodeTitle {
values["episodeTitle"] = episodeTitle
}
if let startTime = self.startTime {
values["startTime"] = String(startTime)
}
if let endTime = self.endTime {
values["endTime"] = String(endTime)
}
if let clipTitle = self.clipTitle {
values["title"] = clipTitle
}
if let ownerName = self.ownerName {
values["ownerName"] = ownerName
}
if let ownerId = self.ownerId {
values["ownerId"] = ownerId
}
if let isPublic = self.isPublic {
values["isPublic"] = isPublic.description
}
return values
}
func convertToMediaRefUpdateBody() -> [String: Any] {
var body:[String: Any] = [:]
if let mediaRefId = self.mediaRefId {
body["id"] = mediaRefId
}
if let startTime = self.startTime {
body["startTime"] = String(startTime)
}
if let endTime = self.endTime {
body["endTime"] = String(endTime)
}
if let clipTitle = self.clipTitle {
body["title"] = clipTitle
}
if let isPublic = self.isPublic {
body["isPublic"] = isPublic.description
}
return body
}
func updateMediaRefOnServer(completion: @escaping (Bool) -> Void) {
if let url = URL(string: BASE_URL + "clips") {
var request = URLRequest(url: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 20)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "PUT"
if let idToken = UserDefaults.standard.string(forKey: "idToken") {
request.setValue(idToken, forHTTPHeaderField: "Authorization")
}
let putBody = self.convertToMediaRefUpdateBody()
do {
request.httpBody = try JSONSerialization.data(withJSONObject: putBody, options: JSONSerialization.WritingOptions())
showNetworkActivityIndicator()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
hideNetworkActivityIndicator()
guard error == nil else {
DispatchQueue.main.async {
completion(false)
}
return
}
PVMediaPlayer.shared.loadPlayerHistoryItem(item: self)
DispatchQueue.main.async {
NotificationCenter.default.post(name:NSNotification.Name(rawValue: kClipUpdated), object: self, userInfo: nil)
completion(true)
}
}
task.resume()
} catch {
print(error)
}
}
}
func saveToServerAsMediaRef(completion: @escaping (_ mediaRef: MediaRef?) -> Void) {
if let url = URL(string: BASE_URL + "clips/") {
var request = URLRequest(url: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 20)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
if let idToken = UserDefaults.standard.string(forKey: "idToken") {
request.setValue(idToken, forHTTPHeaderField: "Authorization")
}
let postBody = self.convertToMediaRefPostString()
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postBody, options: JSONSerialization.WritingOptions())
showNetworkActivityIndicator()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
hideNetworkActivityIndicator()
guard error == nil else {
DispatchQueue.main.async {
completion(nil)
}
return
}
if let data = data {
do {
let mediaRef: MediaRef?
if let item = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
mediaRef = MediaRef.jsonToMediaRef(item: item)
DispatchQueue.main.async {
completion(mediaRef)
}
}
} catch {
print("Error: " + error.localizedDescription)
}
}
}
task.resume()
} catch {
print(error.localizedDescription)
}
}
}
func copyPlayerHistoryItem() -> PlayerHistoryItem {
let copy = PlayerHistoryItem(mediaRefId: mediaRefId, podcastId: podcastId, podcastFeedUrl: podcastFeedUrl, podcastTitle: podcastTitle, podcastImageUrl: podcastImageUrl, episodeDuration: episodeDuration, episodeId: episodeId, episodeMediaUrl: episodeMediaUrl, episodeTitle: episodeTitle, episodeImageUrl: episodeImageUrl, episodeSummary: episodeSummary, episodePubDate: episodePubDate, startTime: startTime, endTime: endTime, clipTitle: clipTitle, ownerName: ownerName, ownerId: ownerId, hasReachedEnd: false, lastPlaybackPosition: lastPlaybackPosition, lastUpdated: lastUpdated, isPublic: isPublic)
return copy
}
func removeClipData() {
self.clipTitle = nil
self.startTime = nil
self.endTime = nil
self.hasReachedEnd = false
self.mediaRefId = nil
self.ownerId = nil
self.ownerName = nil
}
}
| agpl-3.0 | cc7a8b788504b6f729e47ce7a4471332 | 37.576923 | 606 | 0.572881 | 5.159465 | false | false | false | false |
gaurav1981/eidolon | Kiosk/App/Views/Button Subclasses/Button.swift | 1 | 3319 | import UIKit
import QuartzCore
import Artsy_UIButtons
class Button: ARFlatButton {
override func setup() {
super.setup()
setTitleShadowColor(UIColor.clearColor(), forState: .Normal)
setTitleShadowColor(UIColor.clearColor(), forState: .Highlighted)
setTitleShadowColor(UIColor.clearColor(), forState: .Disabled)
shouldDimWhenDisabled = false;
}
}
class ActionButton: Button {
override func intrinsicContentSize() -> CGSize {
return CGSizeMake(UIViewNoIntrinsicMetric, ButtonHeight)
}
override func setup() {
super.setup()
setBorderColor(UIColor.blackColor(), forState: .Normal, animated: false)
setBorderColor(UIColor.artsyPurple(), forState: .Highlighted, animated: false)
setBorderColor(UIColor.artsyMediumGrey(), forState: .Disabled, animated: false)
setBackgroundColor(UIColor.blackColor(), forState: .Normal, animated: false)
setBackgroundColor(UIColor.artsyPurple(), forState: .Highlighted, animated: false)
setBackgroundColor(UIColor.whiteColor(), forState: .Disabled, animated: false)
setTitleColor(UIColor.whiteColor(), forState:.Normal)
setTitleColor(UIColor.whiteColor(), forState:.Highlighted)
setTitleColor(UIColor.artsyHeavyGrey(), forState:.Disabled)
}
}
class SecondaryActionButton: Button {
override func intrinsicContentSize() -> CGSize {
return CGSizeMake(UIViewNoIntrinsicMetric, ButtonHeight)
}
override func setup() {
super.setup()
setBorderColor(UIColor.artsyMediumGrey(), forState: .Normal, animated: false)
setBorderColor(UIColor.artsyPurple(), forState: .Highlighted, animated: false)
setBorderColor(UIColor.artsyLightGrey(), forState: .Disabled, animated: false)
setBackgroundColor(UIColor.whiteColor(), forState: .Normal, animated: false)
setBackgroundColor(UIColor.artsyPurple(), forState: .Highlighted, animated: false)
setBackgroundColor(UIColor.whiteColor(), forState: .Disabled, animated: false)
setTitleColor(UIColor.blackColor(), forState:.Normal)
setTitleColor(UIColor.whiteColor(), forState:.Highlighted)
setTitleColor(UIColor.artsyHeavyGrey(), forState:.Disabled)
}
}
class KeypadButton: Button {
override func setup() {
super.setup()
shouldAnimateStateChange = false;
layer.borderWidth = 0
setBackgroundColor(UIColor.blackColor(), forState: .Highlighted, animated: false)
setBackgroundColor(UIColor.whiteColor(), forState: .Normal, animated: false)
}
}
class LargeKeypadButton: KeypadButton {
override func setup() {
super.setup()
self.titleLabel!.font = UIFont.sansSerifFontWithSize(20)
}
}
class MenuButton: ARMenuButton {
override func setup() {
super.setup()
if let titleLabel = titleLabel {
titleLabel.font = titleLabel.font.fontWithSize(12)
}
}
override func layoutSubviews() {
super.layoutSubviews()
if let titleLabel = titleLabel { self.bringSubviewToFront(titleLabel) }
if let imageView = imageView { self.bringSubviewToFront(imageView) }
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: 45, height: 45)
}
}
| mit | b3831232ac8c19f2ce07ac15e8e8ba9f | 32.867347 | 90 | 0.691775 | 5.036419 | false | false | false | false |
externl/ice | swift/test/Ice/operations/AllTests.swift | 4 | 1798 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
import TestCommon
func allTests(helper: TestHelper) throws -> MyClassPrx {
func test(_ value: Bool, file: String = #file, line: Int = #line) throws {
try helper.test(value, file: file, line: line)
}
let output = helper.getWriter()
let communicator = helper.communicator()
let baseProxy = try communicator.stringToProxy("test:\(helper.getTestEndpoint(num: 0))")!
let cl = try checkedCast(prx: baseProxy, type: MyClassPrx.self)!
let derivedProxy = try checkedCast(prx: cl, type: MyDerivedClassPrx.self)!
let bprx = try checkedCast(prx: try communicator.stringToProxy("b:\(helper.getTestEndpoint(num: 0))")!,
type: MBPrx.self)!
output.write("testing twoway operations... ")
try twoways(helper, cl, bprx)
try twoways(helper, derivedProxy, bprx)
try derivedProxy.opDerived()
output.writeLine("ok")
output.write("testing oneway operations... ")
try oneways(helper, cl)
try oneways(helper, derivedProxy)
output.writeLine("ok")
output.write("testing twoway operations with AMI... ")
try twowaysAMI(helper, cl)
try twowaysAMI(helper, derivedProxy)
try derivedProxy.opDerived()
output.writeLine("ok")
output.write("testing oneway operations with AMI... ")
try onewaysAMI(helper, cl)
try onewaysAMI(helper, derivedProxy)
output.writeLine("ok")
output.write("testing batch oneway operations... ")
try batchOneways(helper, cl)
try batchOneways(helper, derivedProxy)
output.writeLine("ok")
output.write("testing batch oneway operations with AMI... ")
try batchOneways(helper, cl)
try batchOneways(helper, derivedProxy)
output.writeLine("ok")
return cl
}
| gpl-2.0 | c386e4a7e1cdadfc426bc4387da24600 | 31.107143 | 107 | 0.678532 | 3.785263 | false | true | false | false |
wunshine/FoodStyle | FoodStyle/FoodStyle/Classes/Catogry/UIImage+extension.swift | 1 | 1011 | //
// UIImage+extension.swift
// FoodStyle
//
// Created by Woz Wong on 16/3/5.
// Copyright © 2016年 code4Fun. All rights reserved.
//
import Foundation
import UIKit
extension UIImage{
func imageWithColor(color:UIColor)->UIImage{
let rect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func imageWithCorner()->UIImage{
UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
let path = UIBezierPath(ovalInRect: CGRectMake(0,0,self.size.width,self.size.height))
path.addClip()
drawAtPoint(CGPointZero)
let cornerImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return cornerImage
}
}
| mit | 7164bc5d57c30c96abf6a09befc9d777 | 30.5 | 93 | 0.696429 | 5.04 | false | false | false | false |
SummerHH/swift3.0WeBo | WeBo/Classes/Controller/Home(首页)/UIPopover/PopoverAnimator.swift | 1 | 4319 |
//
// PopoverAnimator.swift
// WeBo
//
// Created by 叶炯 on 16/9/17.
// Copyright © 2016年 叶炯. All rights reserved.
//
import UIKit
class PopoverAnimator: NSObject {
//MARK: - 属性
fileprivate var isPersent: Bool = false
var presentedFrame: CGRect = CGRect.zero
//闭包回调
var callBack: ((_ persented: Bool) -> ())?
//MARK: - 自定义构造函数
//注意:如果自定义了一个构造函数,但是没有对默认构造函数 init()进行重写,那么自定义的构造函数会覆盖默认的 init() 构造函数
init(callBack: @escaping (_ persented: Bool) -> ()) {
self.callBack = callBack
}
}
//MARK:- 设置自定义转场动画代理方法
extension PopoverAnimator: UIViewControllerTransitioningDelegate {
//目的: 改变弹出 view 的fream
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let presentation = YJPresentationController(presentedViewController: presented, presenting: presenting)
presentation.presentedFrame = presentedFrame
return presentation
}
//目的: 自定义弹出的动画 返回是一个协议
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPersent = true
//调用闭包
callBack!(isPersent)
return self
}
//目的: 自定义消失动画
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPersent = false
//调用闭包
callBack!(isPersent)
return self
}
}
//MARK: - 弹出和消失动画代理的方法
extension PopoverAnimator : UIViewControllerAnimatedTransitioning {
//动画持续的时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
//获取"转场的上下文": 可以通过转场上下文获取弹出的 View 和消失的 View
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPersent ? animateTransitionPersentView(transitionContext) : animateTransitionDismissView(transitionContext)
}
//自定义弹出动画
fileprivate func animateTransitionPersentView(_ transitionContext: UIViewControllerContextTransitioning) {
//1.获取弹出的 view
//UITransitionContextToViewKey 获取消失的 view
//UITransitionContextFromViewKey 获取弹出的 View
let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
//2. 将弹出的 View 添加到 containerView 中
transitionContext.containerView.addSubview(presentedView)
//3.执行动画
//执行动画的比例
presentedView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
//设置锚点
presentedView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
//回到最初的位置
presentedView.transform = CGAffineTransform.identity
}, completion: { (_) in
//必须告诉上下文,已完成动画
transitionContext.completeTransition(true)
})
}
//自定义消失动画
fileprivate func animateTransitionDismissView(_ transitionContext: UIViewControllerContextTransitioning) {
//1.获取消失的 view
let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from)
//2.执行动画
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
dismissView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.001)
}, completion: { (_) in
dismissView?.removeFromSuperview()
//必须告诉上下文,已完成动画
transitionContext.completeTransition(true)
})
}
}
| apache-2.0 | 050f6f8a90f72276e1ed9d099f362b23 | 30.163934 | 170 | 0.660179 | 5.236915 | false | false | false | false |
MukeshKumarS/Swift | test/SILGen/lifetime.swift | 2 | 23807 | // RUN: %target-swift-frontend -use-native-super-method -parse-as-library -emit-silgen -primary-file %s | FileCheck %s
struct Buh<T> {
var x: Int {
get {}
set {}
}
}
class Ref {
init() { }
}
struct Val {
}
// CHECK-LABEL: sil hidden @_TF8lifetime13local_valtypeFT_T_
func local_valtype() {
var b: Val
// CHECK: [[B:%[0-9]+]] = alloc_box $Val
// CHECK: release [[B]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime20local_valtype_branch
func local_valtype_branch(a: Bool) {
var a = a
// CHECK: [[A:%[0-9]+]] = alloc_box $Bool
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: br [[EPILOG:bb[0-9]+]]
var x:Int
// CHECK: [[X:%[0-9]+]] = alloc_box $Int
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: release [[X]]
// CHECK: br [[EPILOG]]
while a {
// CHECK: cond_br
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK-NOT: release [[X]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: release [[X]]
// CHECK: br [[EPILOG]]
var y:Int
// CHECK: [[Y:%[0-9]+]] = alloc_box $Int
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: release [[Y]]
// CHECK-NOT: release [[X]]
// CHECK-NOT: release [[A]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: release [[Y]]
// CHECK: release [[X]]
// CHECK: br [[EPILOG]]
if true {
var z:Int
// CHECK: [[Z:%[0-9]+]] = alloc_box $Int
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: release [[Z]]
// CHECK: release [[Y]]
// CHECK-NOT: release [[X]]
// CHECK-NOT: release [[A]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: release [[Z]]
// CHECK: release [[Y]]
// CHECK: release [[X]]
// CHECK: br [[EPILOG]]
// CHECK: release [[Z]]
}
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: release [[Y]]
// CHECK-NOT: release [[X]]
// CHECK-NOT: release [[A]]
// CHECK: br
// CHECK: {{bb.*:}}
// CHECK: release [[Y]]
// CHECK: br
}
// CHECK: release [[X]]
// CHECK: [[EPILOG]]:
// CHECK: return
}
func reftype_func() -> Ref {}
func reftype_func_with_arg(x: Ref) -> Ref {}
// CHECK-LABEL: sil hidden @_TF8lifetime14reftype_returnFT_CS_3Ref
func reftype_return() -> Ref {
return reftype_func()
// CHECK: [[RF:%[0-9]+]] = function_ref @_TF8lifetime12reftype_funcFT_CS_3Ref : $@convention(thin) () -> @owned Ref
// CHECK-NOT: release
// CHECK: [[RET:%[0-9]+]] = apply [[RF]]()
// CHECK-NOT: release
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_TF8lifetime11reftype_arg
func reftype_arg(a: Ref) {
var a = a
// CHECK: bb0([[A:%[0-9]+]] : $Ref):
// CHECK: [[AADDR:%[0-9]+]] = alloc_box $Ref
// CHECK: store [[A]] to [[AADDR]]
// CHECK: release [[AADDR]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime17reftype_inout_arg
func reftype_inout_arg(inout a: Ref) {
// CHECK: bb0([[A:%[0-9]+]] : $*Ref):
// -- initialize local box for inout
// CHECK: [[A_LOCAL:%.*]] = alloc_box $Ref
// CHECK: copy_addr [[A]] to [initialization] [[A_LOCAL]]
// -- write back to inout
// CHECK: copy_addr [[A_LOCAL]]#1 to [[A]]
// CHECK: strong_release [[A_LOCAL]]#0
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime26reftype_call_ignore_returnFT_T_
func reftype_call_ignore_return() {
reftype_func()
// CHECK: = function_ref @_TF8lifetime12reftype_funcFT_CS_3Ref : $@convention(thin) () -> @owned Ref
// CHECK-NEXT: [[R:%[0-9]+]] = apply
// CHECK: release [[R]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime27reftype_call_store_to_localFT_T_
func reftype_call_store_to_local() {
var a = reftype_func()
// CHECK: [[A:%[0-9]+]] = alloc_box $Ref
// CHECK: = function_ref @_TF8lifetime12reftype_funcFT_CS_3Ref : $@convention(thin) () -> @owned Ref
// CHECK-NEXT: [[R:%[0-9]+]] = apply
// CHECK-NOT: retain [[R]]
// CHECK: store [[R]] to [[A]]
// CHECK-NOT: release [[R]]
// CHECK: release [[A]]
// CHECK-NOT: release [[R]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime16reftype_call_argFT_T_
func reftype_call_arg() {
reftype_func_with_arg(reftype_func())
// CHECK: [[RFWA:%[0-9]+]] = function_ref @_TF8lifetime21reftype_func_with_arg
// CHECK: [[RF:%[0-9]+]] = function_ref @_TF8lifetime12reftype_func
// CHECK: [[R1:%[0-9]+]] = apply [[RF]]
// CHECK: [[R2:%[0-9]+]] = apply [[RFWA]]([[R1]])
// CHECK: release [[R2]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime21reftype_call_with_arg
func reftype_call_with_arg(a: Ref) {
var a = a
// CHECK: bb0([[A1:%[0-9]+]] : $Ref):
// CHECK: [[AADDR:%[0-9]+]] = alloc_box $Ref
// CHECK: store [[A1]] to [[AADDR]]
reftype_func_with_arg(a)
// CHECK: [[RFWA:%[0-9]+]] = function_ref @_TF8lifetime21reftype_func_with_arg
// CHECK: [[A2:%[0-9]+]] = load [[AADDR]]
// CHECK: retain [[A2]]
// CHECK: = apply [[RFWA]]([[A2]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime16reftype_reassign
func reftype_reassign(inout a: Ref, b: Ref) {
var b = b
// CHECK: bb0([[AADDR:%[0-9]+]] : $*Ref, [[B1:%[0-9]+]] : $Ref):
// CHECK: [[A_LOCAL:%[0-9]+]] = alloc_box $Ref
// CHECK: copy_addr [[AADDR]] to [initialization] [[A_LOCAL]]
// CHECK: [[BADDR:%[0-9]+]] = alloc_box $Ref
a = b
// CHECK: copy_addr [[BADDR]]#1 to [[A_LOCAL]]
// CHECK: release
// CHECK: return
}
func tuple_with_ref_elements() -> (Val, (Ref, Val), Ref) {}
// CHECK-LABEL: sil hidden @_TF8lifetime28tuple_with_ref_ignore_returnFT_T_
func tuple_with_ref_ignore_return() {
tuple_with_ref_elements()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF8lifetime23tuple_with_ref_elementsFT_TVS_3ValTCS_3RefS0__S1__
// CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]]
// CHECK: [[T1:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1
// CHECK: [[T1_0:%[0-9]+]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[T2:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 2
// CHECK: release [[T2]]
// CHECK: release [[T1_0]]
// CHECK: return
}
struct Aleph {
var a:Ref
var b:Val
// -- loadable value constructor:
// CHECK-LABEL: sil hidden @_TFV8lifetime5AlephC{{.*}} : $@convention(thin) (@owned Ref, Val, @thin Aleph.Type) -> @owned Aleph
// CHECK: bb0([[A:%.*]] : $Ref, [[B:%.*]] : $Val, {{%.*}} : $@thin Aleph.Type):
// CHECK-NEXT: [[RET:%.*]] = struct $Aleph ([[A]] : {{.*}}, [[B]] : {{.*}})
// CHECK-NEXT: return [[RET]]
}
struct Beth {
var a:Val
var b:Aleph
var c:Ref
func gimel() {}
}
protocol Unloadable {}
struct Daleth {
var a:Aleph
var b:Beth
var c:Unloadable
// -- address-only value constructor:
// CHECK-LABEL: sil hidden @_TFV8lifetime6DalethC{{.*}} : $@convention(thin) (@out Daleth, @owned Aleph, @owned Beth, @in Unloadable, @thin Daleth.Type) -> () {
// CHECK: bb0([[THIS:%.*]] : $*Daleth, [[A:%.*]] : $Aleph, [[B:%.*]] : $Beth, [[C:%.*]] : $*Unloadable, {{%.*}} : $@thin Daleth.Type):
// CHECK-NEXT: [[A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.a
// CHECK-NEXT: store [[A]] to [[A_ADDR]]
// CHECK-NEXT: [[B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.b
// CHECK-NEXT: store [[B]] to [[B_ADDR]]
// CHECK-NEXT: [[C_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.c
// CHECK-NEXT: copy_addr [take] [[C]] to [initialization] [[C_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
class He {
// -- default initializer:
// CHECK-LABEL: sil hidden @_TFC8lifetime2Hec{{.*}} : $@convention(method) (@owned He) -> @owned He {
// CHECK: bb0([[THIS:%.*]] : $He):
// CHECK-NEXT: debug_value
// CHECK-NEXT: mark_uninitialized
// CHECK-NEXT: return
// CHECK: }
// -- default allocator:
// CHECK-LABEL: sil hidden @_TFC8lifetime2HeC{{.*}} : $@convention(thin) (@thick He.Type) -> @owned He {
// CHECK: bb0({{%.*}} : $@thick He.Type):
// CHECK-NEXT: [[THIS:%.*]] = alloc_ref $He
// CHECK-NEXT: // function_ref lifetime.He.init
// CHECK-NEXT: [[INIT:%.*]] = function_ref @_TFC8lifetime2Hec{{.*}} : $@convention(method) (@owned He) -> @owned He
// CHECK-NEXT: [[THIS1:%.*]] = apply [[INIT]]([[THIS]])
// CHECK-NEXT: return [[THIS1]]
// CHECK-NEXT: }
init() { }
}
struct Waw {
var a:(Ref, Val)
var b:Val
// -- loadable value initializer with tuple destructuring:
// CHECK-LABEL: sil hidden @_TFV8lifetime3WawC{{.*}} : $@convention(thin) (@owned Ref, Val, Val, @thin Waw.Type) -> @owned Waw
// CHECK: bb0([[A0:%.*]] : $Ref, [[A1:%.*]] : $Val, [[B:%.*]] : $Val, {{%.*}} : $@thin Waw.Type):
// CHECK-NEXT: [[A:%.*]] = tuple ([[A0]] : {{.*}}, [[A1]] : {{.*}})
// CHECK-NEXT: [[RET:%.*]] = struct $Waw ([[A]] : {{.*}}, [[B]] : {{.*}})
// CHECK-NEXT: return [[RET]]
}
struct Zayin {
var a:(Unloadable, Val)
var b:Unloadable
// -- address-only value initializer with tuple destructuring:
// CHECK-LABEL: sil hidden @_TFV8lifetime5ZayinC{{.*}} : $@convention(thin) (@out Zayin, @in Unloadable, Val, @in Unloadable, @thin Zayin.Type) -> ()
// CHECK: bb0([[THIS:%.*]] : $*Zayin, [[A0:%.*]] : $*Unloadable, [[A1:%.*]] : $Val, [[B:%.*]] : $*Unloadable, {{%.*}} : $@thin Zayin.Type):
// CHECK-NEXT: [[THIS_A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.a
// CHECK-NEXT: [[THIS_A0_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 0
// CHECK-NEXT: [[THIS_A1_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 1
// CHECK-NEXT: copy_addr [take] [[A0]] to [initialization] [[THIS_A0_ADDR]]
// CHECK-NEXT: store [[A1]] to [[THIS_A1_ADDR]]
// CHECK-NEXT: [[THIS_B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.b
// CHECK-NEXT: copy_addr [take] [[B]] to [initialization] [[THIS_B_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
func fragile_struct_with_ref_elements() -> Beth {}
// CHECK-LABEL: sil hidden @_TF8lifetime29struct_with_ref_ignore_returnFT_T_
func struct_with_ref_ignore_return() {
fragile_struct_with_ref_elements()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF8lifetime32fragile_struct_with_ref_elementsFT_VS_4Beth
// CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]
// CHECK: release_value [[STRUCT]] : $Beth
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8lifetime28struct_with_ref_materializedFT_T_
func struct_with_ref_materialized() {
fragile_struct_with_ref_elements().gimel()
// CHECK: [[METHOD:%[0-9]+]] = function_ref @_TFV8lifetime4Beth5gimel{{.*}}
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF8lifetime32fragile_struct_with_ref_elementsFT_VS_4Beth
// CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]
// CHECK: apply [[METHOD]]([[STRUCT]])
}
class RefWithProp {
var int_prop: Int { get {} set {} }
var aleph_prop: Aleph { get {} set {} }
}
// CHECK-LABEL: sil hidden @_TF8lifetime23logical_lvalue_lifetimeFTCS_11RefWithPropSiVS_3Val_T_ : $@convention(thin) (@owned RefWithProp, Int, Val) -> () {
func logical_lvalue_lifetime(r: RefWithProp, _ i: Int, _ v: Val) {
var i = i
var v = v
var r = r
// CHECK: [[IADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[VADDR:%[0-9]+]] = alloc_box $Val
// CHECK: [[RADDR:%[0-9]+]] = alloc_box $RefWithProp
// -- Reference types need to be retained as property method args.
r.int_prop = i
// CHECK: [[R1:%[0-9]+]] = load [[RADDR]]
// CHECK: strong_retain [[R1]]
// CHECK: [[SETTER_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.int_prop!setter.1 : RefWithProp -> (Int) -> () , $@convention(method) (Int, @guaranteed RefWithProp) -> ()
// CHECK: apply [[SETTER_METHOD]]({{.*}}, [[R1]])
// CHECK: strong_release [[R1]]
r.aleph_prop.b = v
// CHECK: [[R2:%[0-9]+]] = load [[RADDR]]
// CHECK: strong_retain [[R2]]
// CHECK: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[ALEPH_PROP_TEMP:%[0-9]+]] = alloc_stack $Aleph
// CHECK: [[T0:%.*]] = address_to_pointer [[ALEPH_PROP_TEMP]]#1
// CHECK: [[MATERIALIZE_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.aleph_prop!materializeForSet.1 :
// CHECK: [[MATERIALIZE:%.*]] = apply [[MATERIALIZE_METHOD]]([[T0]], [[STORAGE]]#1, [[R2]])
// CHECK: [[PTR:%.*]] = tuple_extract [[MATERIALIZE]] : {{.*}}, 0
// CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]]
// CHECK: [[OPTCALLBACK:%.*]] = tuple_extract [[MATERIALIZE]] : {{.*}}, 1
// CHECK: [[MARKED_ADDR:%.*]] = mark_dependence [[ADDR]] : $*Aleph on [[R2]]
// CHECK: {{.*}}([[CALLBACK:%.*]] :
// CHECK: [[TEMP:%.*]] = alloc_stack $RefWithProp
// CHECK: store [[R2]] to [[TEMP]]#1
// CHECK: apply [[CALLBACK]]({{.*}}, [[STORAGE]]#1, [[TEMP]]#1, {{%.*}})
}
func bar() -> Int {}
class Foo<T> {
var x : Int
var y = (Int(), Ref())
var z : T
var w = Ref()
class func makeT() -> T {}
// Class initializer
init() {
// -- initializing entry point
// CHECK-LABEL: sil hidden @_TFC8lifetime3Fooc{{.*}} :
// CHECK: bb0([[THISIN:%[0-9]+]] : $Foo<T>):
// CHECK: [[THIS:%[0-9]+]] = mark_uninitialized
// initialization for y
// CHECK: [[INTCTOR:%[0-9]+]] = function_ref @_TFSiC{{.*}} : $@convention(thin) (@thin Int.Type) -> Int
// CHECK: [[INTMETA:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[INTVAL:%[0-9]+]] = apply [[INTCTOR]]([[INTMETA]])
x = bar()
// CHECK: function_ref @_TF8lifetime3barFT_Si : $@convention(thin) () -> Int
// CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.x
// CHECK: assign {{.*}} to [[THIS_X]]
z = Foo<T>.makeT()
// CHECK: [[FOOMETA:%[0-9]+]] = metatype $@thick Foo<T>.Type
// CHECK: [[MAKET:%[0-9]+]] = class_method [[FOOMETA]] : {{.*}}, #Foo.makeT!1
// CHECK: ref_element_addr
// -- cleanup this lvalue and return this
// CHECK: return [[THIS]]
// -- allocating entry point
// CHECK-LABEL: sil hidden @_TFC8lifetime3FooC{{.*}} :
// CHECK: bb0([[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type):
// CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T>
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @_TFC8lifetime3Fooc{{.*}}
// CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[THIS]])
// CHECK: return [[INIT_THIS]]
}
init(chi: Int) {
var chi = chi
z = Foo<T>.makeT()
// -- initializing entry point
// CHECK-LABEL: sil hidden @_TFC8lifetime3Fooc{{.*}} :
// CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[THISIN:%[0-9]+]] : $Foo<T>):
// CHECK: [[THIS:%[0-9]+]] = mark_uninitialized
// CHECK: [[CHIADDR:%[0-9]+]] = alloc_box $Int
// CHECK: store [[CHI]] to [[CHIADDR]]
// CHECK: ref_element_addr {{.*}}, #Foo.z
x = chi
// CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.x
// CHECK: copy_addr [[CHIADDR]]#1 to [[THIS_X]]
// -- cleanup chi
// CHECK: release [[CHIADDR]]
// CHECK: return [[THIS]]
// -- allocating entry point
// CHECK-LABEL: sil hidden @_TFC8lifetime3FooC{{.*}} :
// CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type):
// CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T>
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @_TFC8lifetime3Fooc{{.*}}
// CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[CHI]], [[THIS]])
// CHECK: return [[INIT_THIS]]
}
// -- initializing entry point
// CHECK-LABEL: sil hidden @_TFC8lifetime3Fooc{{.*}} :
// -- allocating entry point
// CHECK-LABEL: sil hidden @_TFC8lifetime3FooC{{.*}} :
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @_TFC8lifetime3Fooc{{.*}}
init<U:Intifiable>(chi:U) {
z = Foo<T>.makeT()
x = chi.intify()
}
// Deallocating destructor for Foo.
// CHECK-LABEL: sil hidden @_TFC8lifetime3FooD : $@convention(method) <T> (@owned Foo<T>) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : $Foo<T>):
// CHECK: [[DESTROYING_REF:%[0-9]+]] = function_ref @_TFC8lifetime3Food : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK-NEXT: [[RESULT_SELF:%[0-9]+]] = apply [[DESTROYING_REF]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK-NEXT: [[SELF:%[0-9]+]] = unchecked_ref_cast [[RESULT_SELF]] : $Builtin.NativeObject to $Foo<T>
// CHECK-NEXT: dealloc_ref [[SELF]] : $Foo<T>
// CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-LABEL: sil hidden @_TFC8lifetime3Food : $@convention(method) <T> (@guaranteed Foo<T>) -> @owned Builtin.NativeObject
deinit {
// CHECK: bb0([[THIS:%[0-9]+]] : $Foo<T>):
bar()
// CHECK: function_ref @_TF8lifetime3barFT_Si
// CHECK: apply
// CHECK: [[PTR:%.*]] = unchecked_ref_cast [[THIS]] : ${{.*}} to $Builtin.NativeObject
// -- don't need to release x because it's trivial
// CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #Foo.x
// -- release y
// CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.y
// CHECK: destroy_addr [[YADDR]]
// -- release z
// CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.z
// CHECK: destroy_addr [[ZADDR]]
// -- release w
// CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.w
// CHECK: destroy_addr [[WADDR]]
// -- return back this
// CHECK: return [[PTR]]
}
}
class ImplicitDtor {
var x:Int
var y:(Int, Ref)
var w:Ref
init() { }
// CHECK-LABEL: sil hidden @_TFC8lifetime12ImplicitDtord
// CHECK: bb0([[THIS:%[0-9]+]] : $ImplicitDtor):
// -- don't need to release x because it's trivial
// CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.x
// -- release y
// CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.y
// CHECK: destroy_addr [[YADDR]]
// -- release w
// CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.w
// CHECK: destroy_addr [[WADDR]]
// CHECK: return
}
class ImplicitDtorDerived<T> : ImplicitDtor {
var z:T
init(z : T) {
super.init()
self.z = z
}
// CHECK: bb0([[THIS:%[0-9]+]] : $ImplicitDtorDerived<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtor
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @_TFC8lifetime12ImplicitDtord
// CHECK: apply [[BASE_DTOR]]([[BASE]])
// -- release z
// CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtorDerived.z
// CHECK: destroy_addr [[ZADDR]]
}
class ImplicitDtorDerivedFromGeneric<T> : ImplicitDtorDerived<Int> {
init() { super.init(z: 5) }
// CHECK-LABEL: sil hidden @_TFC8lifetime30ImplicitDtorDerivedFromGenericc{{.*}}
// CHECK: bb0([[THIS:%[0-9]+]] : $ImplicitDtorDerivedFromGeneric<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtorDerived<Int>
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @_TFC8lifetime19ImplicitDtorDerivedd
// CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<Int>([[BASE]])
// CHECK: return [[PTR]]
}
protocol Intifiable {
func intify() -> Int
}
struct Bar {
var x:Int
// Loadable struct initializer
// CHECK-LABEL: sil hidden @_TFV8lifetime3BarC{{.*}}
init() {
// CHECK: bb0([[METATYPE:%[0-9]+]] : $@thin Bar.Type):
// CHECK: [[THISADDRBOX:%[0-9]+]] = alloc_box $Bar
// CHECK: [[THISADDR:%[0-9]+]] = mark_uninitialized [rootself] [[THISADDRBOX]]
x = bar()
// CHECK: [[THIS_X:%[0-9]+]] = struct_element_addr [[THISADDR]] : $*Bar, #Bar.x
// CHECK: assign {{.*}} to [[THIS_X]]
// -- load and return this
// CHECK: [[THISVAL:%[0-9]+]] = load [[THISADDR]]
// CHECK: release [[THISADDRBOX]]
// CHECK: return [[THISVAL]]
}
init<T:Intifiable>(xx:T) {
x = xx.intify()
}
}
struct Bas<T> {
var x:Int
var y:T
// Address-only struct initializer
// CHECK-LABEL: sil hidden @_TFV8lifetime3BasC{{.*}}
init(yy:T) {
// CHECK: bb0([[THISADDRPTR:%[0-9]+]] : $*Bas<T>, [[YYADDR:%[0-9]+]] : $*T, [[META:%[0-9]+]] : $@thin Bas<T>.Type):
// CHECK: alloc_box
// CHECK: [[THISADDRBOX:%[0-9]+]] = alloc_box $Bas
// CHECK: [[THISADDR:%[0-9]+]] = mark_uninitialized [rootself] [[THISADDRBOX]]
x = bar()
// CHECK: [[THIS_X:%[0-9]+]] = struct_element_addr [[THISADDR]] : $*Bas<T>, #Bas.x
// CHECK: assign {{.*}} to [[THIS_X]]
y = yy
// CHECK: [[THIS_Y:%[0-9]+]] = struct_element_addr [[THISADDR]] : $*Bas<T>, #Bas.y
// CHECK: copy_addr {{.*}} to [[THIS_Y]]
// CHECK: release
// -- 'self' was emplaced into indirect return slot
// CHECK: return
}
init<U:Intifiable>(xx:U, yy:T) {
x = xx.intify()
y = yy
}
}
class B { init(y:Int) {} }
class D : B {
// CHECK-LABEL: sil hidden @_TFC8lifetime1Dc{{.*}} : $@convention(method) (Int, Int, @owned D) -> @owned D
// CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int, [[THIS:%[0-9]+]] : $D):
init(x: Int, y: Int) {
var x = x
var y = y
// CHECK: [[THISADDR1:%[0-9]+]] = alloc_box $D
// CHECK: [[THISADDR:%[0-9]+]] = mark_uninitialized [derivedself] [[THISADDR1]]
// CHECK: store [[THIS]] to [[THISADDR]]
// CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int
// CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int
super.init(y: y)
// CHECK: [[THIS1:%[0-9]+]] = load [[THISADDR]]
// CHECK: [[THIS1_SUP:%[0-9]+]] = upcast [[THIS1]] : ${{.*}} to $B
// CHECK: [[SUPER_CTOR:%[0-9]+]] = super_method %12 : $D, #B.init!initializer.1
// CHECK: [[Y:%[0-9]+]] = load [[YADDR]]
// CHECK: [[THIS2_SUP:%[0-9]+]] = apply [[SUPER_CTOR]]([[Y]], [[THIS1_SUP]])
// CHECK: [[THIS2:%[0-9]+]] = unchecked_ref_cast [[THIS2_SUP]] : $B to $D
// CHECK: [[THIS1:%[0-9]+]] = load [[THISADDR]]
// CHECK: release
}
func foo() {}
}
// CHECK-LABEL: sil hidden @_TF8lifetime8downcast
func downcast(b: B) {
var b = b
// CHECK: [[BADDR:%[0-9]+]] = alloc_box $B
(b as! D).foo()
// CHECK: [[B:%[0-9]+]] = load [[BADDR]]
// CHECK: retain [[B]]
// CHECK: [[D:%[0-9]+]] = unconditional_checked_cast [[B]] : {{.*}} to $D
// CHECK: apply {{.*}}([[D]])
// CHECK-NOT: release [[B]]
// CHECK: release [[D]]
// CHECK: release [[BADDR]]
// CHECK: return
}
func int(x: Int) {}
func ref(x: Ref) {}
func tuple() -> (Int, Ref) { return (1, Ref()) }
func tuple_explosion() {
int(tuple().0)
// CHECK: [[F:%[0-9]+]] = function_ref @_TF8lifetime5tupleFT_TSiCS_3Ref_
// CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]()
// CHECK: [[T1:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1
// CHECK: release [[T1]]
// CHECK-NOT: tuple_extract [[TUPLE]] : {{.*}}, 1
// CHECK-NOT: release
ref(tuple().1)
// CHECK: [[F:%[0-9]+]] = function_ref @_TF8lifetime5tupleFT_TSiCS_3Ref_
// CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]()
// CHECK: [[T1:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1
// CHECK-NOT: release [[T1]]
// CHECK-NOT: tuple_extract [[TUPLE]] : {{.*}}, 1
// CHECK-NOT: release
}
class C {
var v = ""
// CHECK-LABEL: sil hidden @_TFC8lifetime1C18ignored_assignment{{.*}}
func ignored_assignment() {
// CHECK: [[STRING:%.*]] = alloc_stack $String
// CHECK: [[UNINIT:%.*]] = mark_uninitialized [var] [[STRING]]
// CHECK: assign {{%.*}} to [[UNINIT]]
// CHECK: destroy_addr [[UNINIT]]
_ = self.v
}
}
| apache-2.0 | feeb66d8fdc52be9b4bc45547bf053ac | 33.698251 | 195 | 0.537285 | 3.074529 | false | false | false | false |
tejen/codepath-instagram | Instagram/Instagram/RelationshipCell.swift | 1 | 3014 | //
// RelationshipCell.swift
// Instagram
//
// Created by Tejen Hasmukh Patel on 3/15/16.
// Copyright © 2016 Tejen. All rights reserved.
//
import UIKit
class RelationshipCell: UITableViewCell {
@IBOutlet weak var profilePic: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var followButton: UIButton!
weak var parentViewController: UIViewController!;
var localUser: User?;
var remoteUser: User? {
didSet {
usernameLabel.text = remoteUser!.username;
profilePic.setImageWithURL(remoteUser!.profilePicURL!);
if(remoteUser!.objectId == User.currentUser()!.objectId){
followButton.hidden = true;
} else if(remoteUser!.isFollowed) {
followButtonSetStyleComplete();
} else {
followButtonSetStyleActionable();
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
profilePic.clipsToBounds = true;
profilePic.layer.cornerRadius = 15;
followButton.layer.cornerRadius = 5;
let tap = UITapGestureRecognizer(target: self, action: Selector("openRemoteUser"));
profilePic.userInteractionEnabled = true;
profilePic.addGestureRecognizer(tap);
let tap2 = UITapGestureRecognizer(target: self, action: Selector("openRemoteUser"));
usernameLabel.userInteractionEnabled = true;
usernameLabel.addGestureRecognizer(tap);
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func followButtonSetStyleActionable(){
followButton.setTitle("Follow", forState: .Normal);
followButton.backgroundColor = UIColor.clearColor();
followButton.setTitleColor(InstagramActionableColor, forState: .Normal);
followButton.layer.borderColor = InstagramActionableColor.CGColor;
followButton.layer.borderWidth = 1;
}
func followButtonSetStyleComplete(){
followButton.setTitle("Following", forState: .Normal);
followButton.backgroundColor = InstagramGreenColor;
followButton.setTitleColor(UIColor.whiteColor(), forState: .Normal);
followButton.layer.borderWidth = 0;
}
func openRemoteUser() {
let pVc = storyboard.instantiateViewControllerWithIdentifier("ProfileTableViewController") as! ProfileTableViewController;
pVc.user = remoteUser!;
parentViewController.navigationController?.pushViewController(pVc, animated: true);
}
@IBAction func onFollowButton(sender: UIButton) {
if(remoteUser!.isFollowed != true) {
remoteUser!.follow(true);
followButtonSetStyleComplete();
} else {
remoteUser!.follow(false);
followButtonSetStyleActionable();
}
}
}
| apache-2.0 | 2d02ca189e93435f71842fc159ee6734 | 33.632184 | 130 | 0.655161 | 5.399642 | false | false | false | false |
Geor9eLau/WorkHelper | Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartPointsLineLayer.swift | 1 | 2718 | //
// ChartPointsLineLayer.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
private struct ScreenLine {
let points: [CGPoint]
let color: UIColor
let lineWidth: CGFloat
let animDuration: Float
let animDelay: Float
let dashPattern: [Double]?
init(points: [CGPoint], color: UIColor, lineWidth: CGFloat, animDuration: Float, animDelay: Float, dashPattern: [Double]?) {
self.points = points
self.color = color
self.lineWidth = lineWidth
self.animDuration = animDuration
self.animDelay = animDelay
self.dashPattern = dashPattern
}
}
open class ChartPointsLineLayer<T: ChartPoint>: ChartPointsLayer<T> {
fileprivate let lineModels: [ChartLineModel<T>]
fileprivate var lineViews: [ChartLinesView] = []
fileprivate let pathGenerator: ChartLinesViewPathGenerator
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, lineModels: [ChartLineModel<T>], pathGenerator: ChartLinesViewPathGenerator = StraightLinePathGenerator(), displayDelay: Float = 0) {
self.lineModels = lineModels
self.pathGenerator = pathGenerator
let chartPoints: [T] = lineModels.flatMap{$0.chartPoints}
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay)
}
fileprivate func toScreenLine(lineModel: ChartLineModel<T>, chart: Chart) -> ScreenLine {
return ScreenLine(
points: lineModel.chartPoints.map{self.chartPointScreenLoc($0)},
color: lineModel.lineColor,
lineWidth: lineModel.lineWidth,
animDuration: lineModel.animDuration,
animDelay: lineModel.animDelay,
dashPattern: lineModel.dashPattern
)
}
override func display(chart: Chart) {
let screenLines = self.lineModels.map{self.toScreenLine(lineModel: $0, chart: chart)}
for screenLine in screenLines {
let lineView = ChartLinesView(
path: self.pathGenerator.generatePath(points: screenLine.points, lineWidth: screenLine.lineWidth),
frame: chart.bounds,
lineColor: screenLine.color,
lineWidth: screenLine.lineWidth,
animDuration: screenLine.animDuration,
animDelay: screenLine.animDelay,
dashPattern: screenLine.dashPattern)
self.lineViews.append(lineView)
lineView.isUserInteractionEnabled = false
chart.addSubview(lineView)
}
}
}
| mit | db1cae0260e36353b7b6693d13fe5e07 | 35.72973 | 215 | 0.65379 | 4.978022 | false | false | false | false |
bradhilton/Table | Example/TodoListController.swift | 1 | 4060 | //
// TodoListController.swift
// Table
//
// Created by Bradley Hilton on 1/24/17.
// Copyright © 2017 Brad Hilton. All rights reserved.
//
import Table
import UIKit
var idCounter: Int = 0
var nextId: Int {
defer { idCounter += 1 }
return idCounter
}
struct Todo : Equatable {
let id = nextId
var description = ""
static func ==(lhs: Todo, rhs: Todo) -> Bool {
return lhs.id == rhs.id
}
}
class TextFieldCell : UITableViewCell {
let textField = UITextField()
var editingDidEnd: (String) -> () = { _ in }
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(textField)
textField.translatesAutoresizingMaskIntoConstraints = false
textField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16).isActive = true
textField.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true
textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -30).isActive = true
textField.addTarget(self, action: #selector(editingDidEnd(textField:)), for: .editingDidEnd)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func editingDidEnd(textField: UITextField) {
editingDidEnd(textField.text ?? "")
}
}
class TodoListController : UITableViewController {
init() {
super.init(style: .plain)
title = "Todos"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var todos: [Todo] = [] {
didSet {
render()
}
}
override func viewDidLoad() {
super.viewDidLoad()
isEditing = true
tableView.rowHeight = 44
tableView.estimatedRowHeight = 44
tableView.allowsSelectionDuringEditing = true
todos = []
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
render()
}
func render() {
tableView.sections = [
Section { (section: inout Section) in
section.rows = todos.map { todo in
Row { row in
row.key = "\(todo.id)"
let reloadKey = "\(todo.description, isEditing)"
row.cell = Cell { (cell: TextFieldCell) in
cell.textField.text = todo.description
cell.textField.placeholder = "Describe Todo Here..."
cell.editingDidEnd = { [unowned self] text in
if let index = self.todos.index(of: todo) {
self.todos[index].description = text
}
}
}
row.commitDelete = { [unowned self] in
self.todos.remove(at: self.todos.index(of: todo)!)
}
row.commitMove = { [unowned self, section = section] (sectionIdentifier, index) in
guard sectionIdentifier == section.key else { return }
self.todos.remove(at: self.todos.index(of: todo)!)
self.todos.insert(todo, at: index)
}
}
} + [
Row { row in
row.cell = Cell { cell in
cell.textLabel?.text = "Add Todo"
}
row.didTap = { [unowned self] in
self.todos.append(Todo())
}
row.commitInsert = row.didTap
}
]
}
]
}
}
| mit | 77ea57789e6d0a31bc84f1d2700f6407 | 32.270492 | 111 | 0.515398 | 5.197183 | false | false | false | false |
tattn/HackathonStarter | HackathonStarter/Utility/Extension/UIImageView+.swift | 1 | 1808 | //
// UIImageView+.swift
// HackathonStarter
//
// Created by 田中 達也 on 2016/07/20.
// Copyright © 2016年 tattn. All rights reserved.
//
import UIKit
import Kingfisher
private let activityIndicatorViewTag = 2018
extension UIImageView {
func setImage(with url: URL?, isIndicatorHidden: Bool = false, indicatorColor: UIColor = .white) {
if !isIndicatorHidden { addLoading(color: indicatorColor) }
kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil) { [weak self] _ in
if !isIndicatorHidden { self?.removeLoading() }
}
}
func cancelDownload() {
kf.cancelDownloadTask()
}
private func addLoading(color indicatorColor: UIColor = .white) {
if let loading = viewWithTag(activityIndicatorViewTag) as? UIActivityIndicatorView {
loading.startAnimating()
} else {
let activityIndicatorView = UIActivityIndicatorView(frame: .init(x: 0, y: 0, width: 50, height: 50))
activityIndicatorView.center = center
activityIndicatorView.hidesWhenStopped = false
activityIndicatorView.style = .white
activityIndicatorView.layer.opacity = 0.8
activityIndicatorView.color = indicatorColor
activityIndicatorView.tag = activityIndicatorViewTag
activityIndicatorView.startAnimating()
addSubview(activityIndicatorView)
activityIndicatorView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
private func removeLoading() {
if let activityIndicatorView = self.viewWithTag(activityIndicatorViewTag) as? UIActivityIndicatorView {
activityIndicatorView.stopAnimating()
activityIndicatorView.removeFromSuperview()
}
}
}
| mit | f1699732e87e7695a050803d9e444b8e | 34.9 | 112 | 0.674095 | 5.326409 | false | false | false | false |
gigascorp/fiscal-cidadao | ios/FiscalCidadao/BaseController.swift | 1 | 1760 | /*
Copyright (c) 2009-2014, Apple Inc. All rights reserved.
Copyright (C) 2016 Andrea Mendonça, Emílio Weba, Guilherme Ribeiro, Márcio Oliveira, Thiago Nunes, Wallas Henrique
This file is part of Fiscal Cidadão.
Fiscal Cidadão 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.
Fiscal Cidadão 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 Fiscal Cidadão. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
class BaseController: NSObject
{
var observers : [Observer] = []
func addObserver(observer: Observer)
{
observers.append(observer)
}
func removeObserver(observer : Observer)
{
var i = 0;
for o in observers
{
if o.equals(observer)
{
i += 1
break;
}
i += 1
}
if i < observers.count
{
observers.removeAtIndex(i)
}
}
func notify(message: Int)
{
for o in observers
{
if let selector = o.getSelectorForMessage(message, sender: self)
{
if o.theObserver!.respondsToSelector(selector)
{
o.theObserver?.performSelector(selector)
}
}
}
}
}
| gpl-3.0 | 9703b23df2477f70c74a3d3ed9a3e11b | 25.560606 | 116 | 0.599544 | 4.494872 | false | false | false | false |
brokenseal/iOS-exercises | Others/Test1234/Test1234/ViewController.swift | 1 | 2940 | //
// ViewController.swift
// Test1234
//
// Created by Davide Callegari on 19/04/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let sampleView = UIView()
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var secondView: UIView!
@IBOutlet weak var thirdView: UIView!
@IBOutlet weak var fourthView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setConstraints()
}
func setConstraints(){
let topLayoutGuide = UILayoutGuide()
let centerLayoutGuide = UILayoutGuide()
let bottomLayoutGuide = UILayoutGuide()
view.addLayoutGuide(topLayoutGuide)
view.addLayoutGuide(centerLayoutGuide)
view.addLayoutGuide(bottomLayoutGuide)
let firstViewToTopGuideConstraint = NSLayoutConstraint(item: firstView, attribute: .bottom, relatedBy: .equal, toItem: topLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
let secondViewToTopGuideConstraint = NSLayoutConstraint(item: secondView, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let secondViewToBottomGuideConstraint = NSLayoutConstraint(item: secondView, attribute: .bottom, relatedBy: .equal, toItem: centerLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
let thirdViewToCenterGuideConstraint = NSLayoutConstraint(item: thirdView, attribute: .top, relatedBy: .equal, toItem: centerLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let thirdViewToBottomGuideConstraint = NSLayoutConstraint(item: thirdView, attribute: .bottom, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
let fourthViewToBottomGuideConstraint = NSLayoutConstraint(item: fourthView, attribute: .top, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let topGuideHeightConstraint = NSLayoutConstraint(item: topLayoutGuide, attribute: .height, relatedBy: .equal, toItem: centerLayoutGuide, attribute: .height, multiplier: 1.0, constant: 0.0)
let centerGuideHeightConstraint = NSLayoutConstraint(item: centerLayoutGuide, attribute: .height, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .height, multiplier: 1.0, constant: 0.0)
view.addConstraints([firstViewToTopGuideConstraint, secondViewToTopGuideConstraint, secondViewToBottomGuideConstraint, thirdViewToCenterGuideConstraint, thirdViewToBottomGuideConstraint, fourthViewToBottomGuideConstraint, topGuideHeightConstraint, centerGuideHeightConstraint])
//NSLayoutConstraint.activate()
}
}
| mit | 4fec8cf1d97ff54ea28779b5a7f3b511 | 49.672414 | 285 | 0.721674 | 4.989813 | false | false | false | false |
RhythmTap/RhythmTap | RhythmTap/LevelViewController.swift | 1 | 3484 | //
// ViewController.swift
// RhythmTap
//
// Created by Richard Sage on 2016-03-09.
// Copyright © 2016 Brian Yip. All rights reserved.
//
import UIKit
class LevelViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var difficulty : Difficulty!
var selectedSong = -1
let difficultyViewSegueIdentifier = "difficultyViewSegue"
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == self.difficultyViewSegueIdentifier {
if let difficultyView = segue.destinationViewController as? DifficultyViewController {
if(selectedSong > -1) {
difficultyView.currentTrack = Globals.tracks[selectedSong]
}
}
}
}
//number of cells
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Globals.tracks.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: UIScreen.mainScreen().bounds.width/5, height: UIScreen.mainScreen().bounds.width/5);
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 60, left: 5, bottom: 10, right: 5)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 3
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 3
}
//creating the data cells
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("LevelViewCell", forIndexPath: indexPath) as! LevelViewCell
cell.levelSelect.setTitle( String(indexPath.item + 1), forState: UIControlState.Normal)
cell.levelSelect.songNum = indexPath.item
//format the cell
formatDataCell(cell, indexPath: indexPath);
cell.levelSelect.addTarget(self, action: "levelSelect:", forControlEvents: UIControlEvents.TouchUpInside)
return cell;
}
//formatting cell initially
func formatDataCell(cell: LevelViewCell, indexPath: NSIndexPath) {
cell.layer.borderWidth = 5;
cell.layer.borderColor = UIColor.clearColor().CGColor;
cell.layer.masksToBounds = true;
cell.layer.cornerRadius = 5;
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
}
func levelSelect (sender : LevelButton!) {
selectedSong = sender.songNum
self.performSegueWithIdentifier(self.difficultyViewSegueIdentifier, sender: self)
}
}
| apache-2.0 | 7ff7c0a09d3d963c770616d6c63b4499 | 38.134831 | 178 | 0.706575 | 5.776119 | false | false | false | false |
southfox/jfwindguru | Example/JFWindguru/Common.swift | 1 | 587 | //
// Common.swift
// JFWindguru
//
// Created by javierfuchs on 7/9/17.
// Copyright © 2017 Mobile Patagonia. All rights reserved.
//
import Foundation
/*
* WDCommon
*
* Discussion:
* Some common and global constants.
*/
let kWDForecastUpdated : String = "WDForecastUpdated"
let kWDWatchPlist: String = "WDWatch.plist"
let kWDGroup : String = "group.fuchs.windguru"
let kWDKeyLocality : String = "locality"
let kWDKeyCountry : String = "country"
let kWDMinimumDistanceFilterInMeters : Double = 60.0 // update every 200ft
let kWDAnimationDuration: Double = 2.0
| mit | f1959b6a2a822218b8fa826612e66cc1 | 17.3125 | 74 | 0.713311 | 3.13369 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Create/Cells/ConversationCreateOptionsCell.swift | 1 | 3243 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireCommonComponents
import UIKit
final class ConversationCreateOptionsCell: RightIconDetailsCell {
var expanded = false {
didSet { applyColorScheme(colorSchemeVariant) }
}
override var accessibilityLabel: String? {
get {
return title
}
set {
super.accessibilityLabel = newValue
}
}
override var accessibilityValue: String? {
get {
return status
}
set {
super.accessibilityValue = newValue
}
}
override var accessibilityHint: String? {
get {
typealias CreateConversation = L10n.Accessibility.CreateConversation
return expanded ? CreateConversation.HideSettings.hint : CreateConversation.OpenSettings.hint
}
set {
super.accessibilityHint = newValue
}
}
override func setUp() {
super.setUp()
title = L10n.Localizable.Conversation.Create.Options.title
icon = nil
showSeparator = false
contentLeadingOffset = 16
setupAccessibility()
}
override func applyColorScheme(_ colorSchemeVariant: ColorSchemeVariant) {
super.applyColorScheme(colorSchemeVariant)
let color = SemanticColors.Icon.foregroundPlainDownArrow
let image = StyleKitIcon.downArrow.makeImage(size: .tiny, color: color).withRenderingMode(.alwaysTemplate)
// flip upside down if necessary
if let cgImage = image.cgImage, expanded {
accessory = UIImage(cgImage: cgImage, scale: image.scale, orientation: .downMirrored).withRenderingMode(.alwaysTemplate)
} else {
accessory = image
}
accessoryColor = color
}
private func setupAccessibility() {
accessibilityIdentifier = "cell.groupdetails.options"
isAccessibilityElement = true
accessibilityTraits = .button
}
}
extension ConversationCreateOptionsCell: ConversationCreationValuesConfigurable {
func configure(with values: ConversationCreationValues) {
let guests = values.allowGuests.localized.localizedUppercase
let services = values.allowServices.localized.localizedUppercase
let receipts = values.enableReceipts.localized.localizedUppercase
status = L10n.Localizable.Conversation.Create.Options.subtitle(guests, services, receipts)
}
}
private extension Bool {
var localized: String {
return self ? "general.on".localized : "general.off".localized
}
}
| gpl-3.0 | fa386cb742fce4fe45fe2e289106f00c | 29.885714 | 132 | 0.679926 | 5.131329 | false | false | false | false |
nodes-ios/model-generator | Frameworks/CommandLine/CommandLine.swift | 1 | 9488 | /*
* CommandLine.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/* Required for setlocale(3) */
import Darwin
let ShortOptionPrefix = "-"
let LongOptionPrefix = "--"
/* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt
* convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
*/
let ArgumentStopper = "--"
/* Allow arguments to be attached to flags when separated by this character.
* --flag=argument is equivalent to --flag argument
*/
let ArgumentAttacher: Character = "="
/* An output stream to stderr; used by CommandLine.printUsage(). */
private struct StderrOutputStream: TextOutputStream {
static let stream = StderrOutputStream()
func write(_ s: String) {
fputs(s, stderr)
}
}
/**
* The CommandLine class implements a command-line interface for your app.
*
* To use it, define one or more Options (see Option.swift) and add them to your
* CommandLine object, then invoke `parse()`. Each Option object will be populated with
* the value given by the user.
*
* If any required options are missing or if an invalid value is found, `parse()` will throw
* a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage
* message.
*/
public class CommandLineKit {
private var _arguments: [String]
private var _options: [Option] = [Option]()
/** A ParseError is thrown if the `parse()` method fails. */
public enum ParseError: Error, CustomStringConvertible {
/** Thrown if an unrecognized argument is passed to `parse()` in strict mode */
case InvalidArgument(String)
/** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */
case InvalidValueForOption(Option, [String])
/** Thrown if an Option with required: true is missing */
case MissingRequiredOptions([Option])
public var description: String {
switch self {
case let .InvalidArgument(arg):
return "Invalid argument: \(arg)"
case let .InvalidValueForOption(opt, vals):
let vs = vals.joined(separator: ", ")
return "Invalid value(s) for option \(opt.flagDescription): \(vs)"
case let .MissingRequiredOptions(opts):
return "Missing required options: \(opts.map { return $0.flagDescription })"
}
}
}
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = CommandLine.arguments) {
self._arguments = arguments
/* Initialize locale settings from the environment */
setlocale(LC_ALL, "")
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
private func _getFlagValues(flagIndex: Int) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
/* Grab attached arg, if any */
var attachedArg = _arguments[flagIndex].splitByCharacter(splitBy: ArgumentAttacher, maxSplits: 1)
if attachedArg.count > 1 {
args.append(attachedArg[1])
}
for i in flagIndex + 1 ..< _arguments.count {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
_arguments[i].toDouble() == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
public func addOption(option: Option) {
_options.append(option)
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
public func addOptions(options: [Option]) {
_options += options
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
public func addOptions(_ options: Option...) {
_options += options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
public func setOptions(options: [Option]) {
_options = options
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
public func setOptions(options: Option...) {
_options = options
}
/**
* Parses command-line arguments into their matching Option values. Throws `ParseError` if
* argument parsing fails.
*
* - parameter strict: Fail if any unrecognized arguments are present (default: false).
*/
public func parse(strict: Bool = false) throws {
for (idx, arg) in _arguments.enumerated() {
if arg == ArgumentStopper {
break
}
if !arg.hasPrefix(ShortOptionPrefix) {
continue
}
let skipChars = arg.hasPrefix(LongOptionPrefix) ?
LongOptionPrefix.count : ShortOptionPrefix.count
let flagWithArg = arg[arg.index(arg.startIndex, offsetBy: skipChars) ..< arg.endIndex]
/* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */
if flagWithArg.isEmpty {
continue
}
/* Remove attached argument from flag */
let flag = flagWithArg.splitByCharacter(splitBy: ArgumentAttacher, maxSplits: 1)[0]
var flagMatched = false
for option in _options {
if option.flagMatch(flag: flag) {
let vals = self._getFlagValues(flagIndex: idx)
guard option.setValue(values: vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
flagMatched = true
break
}
}
/* Flags that do not take any arguments can be concatenated */
let flagLength = flag.count
if !flagMatched && !arg.hasPrefix(LongOptionPrefix) {
for (i, c) in flag.characters.enumerated() {
for option in _options {
if option.flagMatch(flag: String(c)) {
/* Values are allowed at the end of the concatenated flags, e.g.
* -xvf <file1> <file2>
*/
let vals = (i == flagLength - 1) ? self._getFlagValues(flagIndex: idx) : [String]()
guard option.setValue(values: vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
flagMatched = true
break
}
}
}
}
/* Invalid flag */
guard !strict || flagMatched else {
throw ParseError.InvalidArgument(arg)
}
}
/* Check to see if any required options were not matched */
let missingOptions = _options.filter { $0.required && !$0.wasSet }
guard missingOptions.count == 0 else {
throw ParseError.MissingRequiredOptions(missingOptions)
}
}
/* printUsage() is generic for OutputStreamType because the Swift compiler crashes
* on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694).
*/
/**
* Prints a usage message.
*
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: TextOutputStream>(to: inout TargetStream) {
let name = _arguments[0]
var flagWidth = 0
for opt in _options {
flagWidth = max(flagWidth, " \(opt.flagDescription):".count)
}
print("Usage: \(name) [options]", to: &to)
for opt in _options {
let flags = " \(opt.flagDescription):".padding(toLength: flagWidth, withPad: " ", startingAt: 0)
print("\(flags)\n \(opt.helpMessage)", to: &to)
}
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: TextOutputStream>(error: Error, to: inout TargetStream) {
print("\(error)\n", to: &to)
printUsage(to: &to)
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
*/
public func printUsage(error: Error) {
var out = StderrOutputStream.stream
printUsage(error: error, to: &out)
}
/**
* Prints a usage message.
*/
public func printUsage() {
var out = StderrOutputStream.stream
printUsage(to: &out)
}
}
| mit | cebd2e9e0244a39c936eb9cbdfde1e6b | 30.626667 | 103 | 0.63828 | 4.39056 | false | false | false | false |
macc704/iKF | iKF/KFPostRefView.swift | 1 | 8592 | //
// KFPostRefView.swift
// iKF
//
// Created by Yoshiaki Matsuzawa on 2014-06-09.
// Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved.
//
import UIKit
class KFPostRefView: UIView {
var mainController: KFCanvasViewController!;
private var _model: KFReference!;
private var panGesture:UIPanGestureRecognizer?;
private var singleTapGesture:UITapGestureRecognizer?;
private var doubleTapGesture:UITapGestureRecognizer?;
private var longPressGesture:UILongPressGestureRecognizer?;
private var gestureAttached = false;
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(controller: KFCanvasViewController, ref: KFReference) {
self.mainController = controller;
super.init(frame: CGRectMake(0,0,0,0));
self.setModel(ref);
bindEvents();
}
func getModel()->KFReference!{
return self._model;
}
func setModel(newModel:KFReference){
self._model = newModel;
}
private func bindEvents(){
//Single Tap
singleTapGesture = UITapGestureRecognizer(target:self, action:"handleSingleTap:");
singleTapGesture!.numberOfTapsRequired = 1;
//self.addGestureRecognizer(recognizerSingleTap);
//Double Tap
doubleTapGesture = UITapGestureRecognizer(target:self, action:"handleDoubleTap:");
doubleTapGesture!.numberOfTapsRequired = 2;
//long Tap
longPressGesture = UILongPressGestureRecognizer(target:self, action:"handleLongPress:");
self.addGestureRecognizer(self.longPressGesture!);
singleTapGesture!.requireGestureRecognizerToFail(doubleTapGesture!);
//Pan Gesture
self.panGesture = UIPanGestureRecognizer(target:self, action:"handlePanning:");
//update event binding
updateEventBinding();
}
func handleLongPress(sender:UILongPressGestureRecognizer) {
if(sender.state == UIGestureRecognizerState.Began){
tapB();
}
}
func updateEventBinding(){
if(self.getModel().isLocked() && gestureAttached){//tolock
self.removeGestureRecognizer(self.singleTapGesture!);
self.removeGestureRecognizer(self.doubleTapGesture!);
self.removeGestureRecognizer(self.panGesture!);
gestureAttached = false;
}
else if(!self.getModel().isLocked() && !gestureAttached){//tounlock
self.addGestureRecognizer(self.singleTapGesture!);
self.addGestureRecognizer(self.doubleTapGesture!);
self.addGestureRecognizer(self.panGesture!);
gestureAttached = true;
}
}
func getMenuItems() -> [KFMenu]{
let refModel = self.getModel();
var menues:[KFMenu] = [];
let operatable = KFDefaultMenu();
operatable.name = "Operatable";
operatable.checked = refModel.isOperatable();
operatable.exec = {
refModel.setOperatable(!refModel.isOperatable());
operatable.checked = refModel.isOperatable();
self.updateFromModel();
self.mainController.updatePostRef(self);
}
let border = KFDefaultMenu();
border.name = "Border";
border.checked = refModel.isBorder();
border.exec = {
refModel.setBorder(!refModel.isBorder());
border.checked = refModel.isBorder();
self.updateFromModel();
self.mainController.updatePostRef(self);
}
let fitscale = KFDefaultMenu();
fitscale.name = "FitScale";
fitscale.checked = refModel.isFitScale();
fitscale.exec = {
refModel.setFitScale(!refModel.isFitScale())
fitscale.checked = refModel.isFitScale();
self.updateFromModel();
self.mainController.updatePostRef(self);
}
return [operatable, border, fitscale];
}
func kfSetSize(width:CGFloat, height:CGFloat){
self.getModel().width = width;
self.getModel().height = height;
self.updateFromModel();
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if(!getModel().isLocked()){
mainController.suppressScroll();
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
mainController.unlockSuppressScroll();
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
mainController.unlockSuppressScroll();
}
private var originalPosition:CGPoint?;
private var dropTarget:KFDropTargetView?
func handlePanning(recognizer: UIPanGestureRecognizer){
switch(recognizer.state){
case .Began:
self.originalPosition = self.frame.origin;
self.superview!.bringSubviewToFront(self);
mainController.putToDraggingLayer(self);
self.makeShadow();
break;
case .Changed:
let location = recognizer.translationInView(self);
let movePoint = CGPointMake(self.center.x+location.x, self.center.y+location.y);
self.center = movePoint;
recognizer.setTranslation(CGPointZero, inView:self);
self.droptargetManagement();
break;
case .Ended:
if(dropTarget == nil){
mainController.requestConnectionsRepaint();
mainController.postLocationChanged(self);
mainController.pullBackFromDraggingLayer(self);
}else{
dropTarget!.leaveDroppable(self);
dropTarget!.dropped(self);
dropTarget = nil;
UIView.animateWithDuration(0.25, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.frame.origin = self.originalPosition!;
}, completion: {(Bool) in self.mainController.pullBackFromDraggingLayer(self);return;});
}
self.removeShadow();
break;
default:
break;
}
}
private func droptargetManagement(){
let newdropTarget = self.mainController.findDropTargetWindow(self);
if(dropTarget == nil && newdropTarget != nil){
newdropTarget!.enterDroppable(self);
}
else if(dropTarget != nil && newdropTarget != nil && dropTarget != newdropTarget){
dropTarget!.leaveDroppable(self);
newdropTarget!.enterDroppable(self);
}
else if(dropTarget != nil && newdropTarget == nil){
dropTarget!.leaveDroppable(self);
}
dropTarget = newdropTarget;
}
private var savedBackgroundColor:UIColor?;
func makeShadow(){
self.savedBackgroundColor = self.backgroundColor;
self.backgroundColor = UIColor.whiteColor();
self.layer.shadowColor = UIColor.blackColor().CGColor;
self.layer.shadowOpacity = 0.7;
self.layer.shadowOffset = CGSizeMake(10.0, 10.0);
self.layer.shadowRadius = 5.0;
self.layer.masksToBounds = false;
let path = UIBezierPath(rect: self.bounds);
self.layer.shadowPath = path.CGPath;
}
func removeShadow(){
self.backgroundColor = savedBackgroundColor;
self.layer.shadowOpacity = 0.0;
}
func handleSingleTap(recognizer: UIGestureRecognizer){
self.tapA();
}
func handleDoubleTap(recognizer: UIGestureRecognizer){
self.tapB();
}
func tapA(){
}
func tapB(){
mainController.showHalo(self);
}
func updateToModel(){
}
var border:Bool = false;
func updateFromModel(){
if(!border && getModel().isBorder() && getModel().isShowInPlace()){
self.layer.borderColor = UIColor.grayColor().CGColor;
self.layer.borderWidth = 1.0;
border = true;
}else if (border && (!getModel().isBorder() || !getModel().isShowInPlace())){
self.layer.borderWidth = 0.0;
border = false;
}
let r = self.frame;
self.frame = CGRectMake(getModel().location.x, getModel().location.y, r.size.width, r.size.height);
}
func getReference() -> CGRect{
return self.frame;
}
}
| gpl-2.0 | ebbdf7709ad37ed6fc53193b082c2bcb | 32.173745 | 122 | 0.606727 | 4.966474 | false | false | false | false |
phatblat/realm-cocoa | examples/ios/swift/Encryption/ViewController.swift | 2 | 4850 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import RealmSwift
import Security
import UIKit
// Model definition
class EncryptionObject: Object {
@Persisted var stringProp: String
}
class ViewController: UIViewController {
let textView = UITextView(frame: UIScreen.main.applicationFrame)
// Create a view to display output in
override func loadView() {
super.loadView()
view.addSubview(textView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Use an autorelease pool to close the Realm at the end of the block, so
// that we can try to reopen it with different keys
autoreleasepool {
let configuration = Realm.Configuration(encryptionKey: getKey() as Data)
let realm = try! Realm(configuration: configuration)
// Add an object
try! realm.write {
let obj = EncryptionObject()
obj.stringProp = "abcd"
realm.add(obj)
}
}
// Opening with wrong key fails since it decrypts to the wrong thing
autoreleasepool {
do {
let configuration = Realm.Configuration(encryptionKey: "1234567890123456789012345678901234567890123456789012345678901234".data(using: .utf8, allowLossyConversion: false))
_ = try Realm(configuration: configuration)
} catch {
log(text: "Open with wrong key: \(error)")
}
}
// Opening without supplying a key at all fails
autoreleasepool {
do {
_ = try Realm()
} catch {
log(text: "Open with no key: \(error)")
}
}
// Reopening with the correct key works and can read the data
autoreleasepool {
let configuration = Realm.Configuration(encryptionKey: getKey() as Data)
let realm = try! Realm(configuration: configuration)
if let stringProp = realm.objects(EncryptionObject.self).first?.stringProp {
log(text: "Saved object: \(stringProp)")
}
}
}
func log(text: String) {
textView.text += "\(text)\n\n"
}
func getKey() -> NSData {
// Identifier for our keychain entry - should be unique for your application
let keychainIdentifier = "io.Realm.EncryptionExampleKey"
let keychainIdentifierData = keychainIdentifier.data(using: String.Encoding.utf8, allowLossyConversion: false)!
// First check in the keychain for an existing key
var query: [NSString: AnyObject] = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecReturnData: true as AnyObject
]
// To avoid Swift optimization bug, should use withUnsafeMutablePointer() function to retrieve the keychain item
// See also: http://stackoverflow.com/questions/24145838/querying-ios-keychain-using-swift/27721328#27721328
var dataTypeRef: AnyObject?
var status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
return dataTypeRef as! NSData
}
// No pre-existing key from this application, so generate a new one
let keyData = NSMutableData(length: 64)!
let result = SecRandomCopyBytes(kSecRandomDefault, 64, keyData.mutableBytes.bindMemory(to: UInt8.self, capacity: 64))
assert(result == 0, "Failed to get random bytes")
// Store the key in the keychain
query = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecValueData: keyData
]
status = SecItemAdd(query as CFDictionary, nil)
assert(status == errSecSuccess, "Failed to insert the new key in the keychain")
return keyData
}
}
| apache-2.0 | e5b8849f65083a7d9697fa5778ca485f | 37.188976 | 186 | 0.622062 | 5.198285 | false | true | false | false |
Liquidsoul/LocalizationConverter | Sources/LocalizationConverter/Formatters/LocalizableFormatter.swift | 1 | 2008 | //
// LocalizableFormatter.swift
//
// Created by Sébastien Duperron on 14/05/2016.
// Copyright © 2016 Sébastien Duperron
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
struct LocalizableFormatter {
let includePlurals: Bool
init(includePlurals: Bool = true) {
self.includePlurals = includePlurals
}
func format(_ localization: LocalizationMap) throws -> Data {
let formattedString = format(localization.convertedLocalization(to: .ios).localizations)
guard let data = formattedString.data(using: String.Encoding.utf8) else {
throw NSError(domain: "\(self)", code: 500)
}
return data
}
fileprivate func format(_ localizations: [String: LocalizationItem]) -> String {
var localizableEntries = [String]()
localizations.forEach { (key, localizationItem) in
switch localizationItem {
case .string(let value):
localizableEntries.append("\"\(key)\" = \"\(escapeDoubleQuotes(in: value))\";")
case .plurals(let values):
if includePlurals, let value = pluralValue(from: values) {
localizableEntries.append("\"\(key)\" = \"\(escapeDoubleQuotes(in: value))\";")
}
}
}
if localizableEntries.count == 0 { return "" }
return localizableEntries.sorted { $0.lowercased() < $1.lowercased() }.joined(separator: "\n") + "\n"
}
fileprivate func pluralValue(from values: [PluralType: String]) -> String? {
let priorities: [PluralType] = [.other, .many, .few, .two, .one, .zero]
return priorities.reduce(nil) { (value: String?, type) -> String? in
if value != nil {
return value
}
return values[type]
}
}
fileprivate func escapeDoubleQuotes(in string: String) -> String {
return string.replacingOccurrences(of: "\"", with: "\\\"")
}
}
| mit | 558f72239e3011824db41e8f3d414548 | 33.568966 | 109 | 0.6 | 4.515766 | false | false | false | false |
CalQL8ed-K-OS/value-types-should-conform-to-Equatable | value types should conform to Equatable.playground/Contents.swift | 1 | 710 | //: the __Foo__ struct conforms to Equatable
struct Foo {
let value: Int
}
extension Foo : Equatable {}
func ==(left: Foo, right: Foo) -> Bool {
return left.value == right.value
}
//: the __Bar__ structure does not
struct Bar {
let value: Int
}
let foos = [Foo(value: 3), Foo(value: 5), Foo(value: 34)]
let bars = [Bar(value: 4), Bar(value: 6), Bar(value: 67)]
//: __CollectionType__'s `where Generator.Element : Equatable` can use the simpler `contains` method
foos.contains(Foo(value: 3))
foos.contains(Foo(value: 234))
//: __CollectionType__'s that don't fulfil the constrained extension have to resort to this uglier version
bars.contains { $0.value == 4 }
bars.contains { $0.value == 3 }
| mit | b65015f7c27ccdf256d75e5308063768 | 27.4 | 106 | 0.664789 | 3.317757 | false | false | false | false |
airspeedswift/swift-compiler-crashes | fixed/00161-swift-tupletype-get.swift | 12 | 875 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
class ed<a>: NSObject {
var o: a
y(o: a) {
r.o = o
b.y()
}
}
protocol dc {
typealias t
func v(t)
}
struct v<l> : dc {
func v(v: v.u) {
}
}
func ^(x: j, s) -> s {
typealias w
typealias m = w
typealias v = w
}
class v<o : k, cb : k n o.dc == cb> : x {
}
class v<o, cb> {
}
protocol k {
typealias dc
}
class x {
typealias v = v
}
enum m<a> {
w cb(a, () -> ())
}
protocol v {
class func m()
}
struct k {
var w: v.u
func m() {
w.m()
}
}
protocol dc {
}
struct t : dc {
}
struct cb<k, p: dc n k.cb == p> {
}
struct w<v : m, dc: m n dc.o == v.o> {
}
protocol m {
q v {
w k
}
}
class dc<a : dc
| mit | 4a72fe52acf656eb52666c14eeaf4d65 | 13.344262 | 87 | 0.514286 | 2.675841 | false | false | false | false |
ssathy2/Hakken | Hakken/Hakken/Views/RotatableArrow.swift | 1 | 3610 | //
// SubcommentsVisibleIndicator.swift
// Hakken
//
// Created by Sidd Sathyam on 11/30/15.
// Copyright © 2015 dotdotdot. All rights reserved.
//
import UIKit
@objc enum ArrowDirection : Int {
case ArrowDirectionDown = 0
case ArrowDirectionRight = 1
}
class RotatableArrow : UIView {
private var direction : ArrowDirection = ArrowDirection.ArrowDirectionDown
private var arrowLayer : CAShapeLayer?
private var arrowBezierPath : UIBezierPath?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupArrowLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.updateArrowLayer(self.bounds)
}
private func updateArrowLayer(var newFrame: CGRect) {
newFrame.origin.x += 2
newFrame.origin.y += 2
newFrame.size.height -= 2
newFrame.size.width -= 2
self.arrowLayer!.frame = newFrame
self.arrowLayer!.lineWidth = 1.0
self.arrowLayer!.strokeColor = UIColor.grayColor().CGColor
self.updateArrowBezierPath(self.arrowLayer!.bounds)
}
private func updateArrowBezierPath(newFrame: CGRect) {
self.arrowBezierPath = UIBezierPath.init()
let startPoint = CGPointZero
self.arrowBezierPath!.moveToPoint(startPoint)
self.arrowBezierPath!.addLineToPoint(CGPointMake(CGRectGetMidX(newFrame), CGRectGetMaxY(newFrame)))
self.arrowBezierPath!.addLineToPoint(CGPointMake(CGRectGetMaxX(newFrame), CGRectGetMinY(newFrame)))
self.arrowBezierPath!.closePath()
self.arrowLayer!.path = self.arrowBezierPath!.CGPath
}
private func setupArrowLayer() {
self.arrowLayer = CAShapeLayer()
self.arrowLayer!.anchorPoint = CGPointMake(0.5, 0.5);
self.updateArrowLayer(self.bounds)
self.updateArrowBezierPath(self.arrowLayer!.bounds)
self.layer.addSublayer(self.arrowLayer!)
}
func setDirection(newDirection: ArrowDirection, animated: Bool) {
if (direction != newDirection)
{
// animate the direction changing here
self.updateLayer(direction, newDirection: newDirection, animated: animated)
// update the stored direction with newDirection
direction = newDirection
}
}
private func updateLayer(oldDirection: ArrowDirection, newDirection: ArrowDirection, animated: Bool) {
// if the bezier path property is nil, we're drawing for the first time
if (self.arrowLayer == nil)
{
self.setupArrowLayer()
}
let totalRotations = (newDirection.rawValue - oldDirection.rawValue) * -1
// figure out how many radians to rotate layer by
let CGRotationTransform = CGAffineTransformRotate(CATransform3DGetAffineTransform(self.arrowLayer!.transform), CGFloat(Double(totalRotations) * M_PI_2))
let rotationTransform = CATransform3DMakeAffineTransform(CGRotationTransform)
let transformClosure = {
self.arrowLayer!.transform = rotationTransform
}
// 3. animate the rotation of the layer from oldDirection to newDirection
// derive the angle of rotation from the oldDirection to newDirection AND clockwise param
if (animated)
{
UIView.animateWithDuration(0.2, animations: transformClosure)
}
else
{
transformClosure()
}
}
} | mit | 4f1a01a06d71df58cd8be9630b12d483 | 34.392157 | 160 | 0.660848 | 4.863881 | false | false | false | false |
IBM-Swift/BluePic | BluePic-iOS/BluePic/Controllers/SearchViewController.swift | 1 | 8505 | /**
* Copyright IBM Corporation 2016, 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
class SearchViewController: UIViewController {
//string property that holds the popular tags of BluePic
var popularTags = [String]()
//search text field that the user can type searches in
@IBOutlet weak var searchField: UITextField!
//tags button that just says tags, has no fuction at this time
@IBOutlet weak var tagsButton: UIButton!
//collection view that displays the popular tags
@IBOutlet weak var tagCollectionView: UICollectionView!
//constraint outlet for the bottom of the collection view
@IBOutlet weak var bottomCollectionViewConstraint: NSLayoutConstraint!
//padding used for the width of the collection view cell in sizeForItemAtIndexPath method
let kCellPadding: CGFloat = 30
/**
Method called upon view did load. It sets up the popular tags collection view, observes when the keyboard is shown, and begins the fetch of popular tags
*/
override func viewDidLoad() {
super.viewDidLoad()
setupPopularTags()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
initializeDataRetrieval()
}
/**
Method sets up the popular tags collection view
*/
func setupPopularTags() {
let layout = KTCenterFlowLayout()
layout.leftAlignedLayout = true
layout.minimumInteritemSpacing = 10.0
layout.minimumLineSpacing = 10.0
layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 15.0)
tagCollectionView.setCollectionViewLayout(layout, animated: false)
if let label = tagsButton.titleLabel {
Utils.kernLabelString(label, spacingValue: 1.7)
}
Utils.registerNibWith("TagCollectionViewCell", collectionView: tagCollectionView)
}
/**
Method called upon view will appear. It sets the search text field to become a first responder so it becomes selected and the keyboard shows
- parameter animated: Bool
*/
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchField.becomeFirstResponder()
}
/**
Method called by the OS when the application receieves a memory warning
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/**
Method to make sure keyboard doesn't hide parts of the collectionView
- parameter n: Notification
*/
@objc func keyboardWillShow(_ n: Notification) {
let userInfo = n.userInfo
if let info = userInfo, let keyboardRect = info[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let rectValue = keyboardRect.cgRectValue
bottomCollectionViewConstraint.constant = rectValue.height - 40 // with offset
}
}
/**
Method called when the back button is pressed
- parameter sender: Any
*/
@IBAction func popVC(_ sender: Any) {
searchField.resignFirstResponder()
_ = self.navigationController?.popViewController(animated: true)
}
}
// MARK: - extension to separate out data handling code
extension SearchViewController {
/**
Method initializes data retrieval by observing the PopularTagsReceieved notification of the BluemixDataManager, and starting the fetch to get popular tags
- returns:
*/
func initializeDataRetrieval() {
NotificationCenter.default.addObserver(self, selector: #selector(updateWithTagData), name: .popularTagsReceived, object: nil)
BluemixDataManager.SharedInstance.getPopularTags()
}
/**
Method is called when the BluemixDataManager has successfully received tags. It updates the tag collection view with this new data
*/
@objc func updateWithTagData() {
DispatchQueue.main.async(execute: {
self.popularTags = BluemixDataManager.SharedInstance.tags
self.tagCollectionView.performBatchUpdates({
self.tagCollectionView.reloadSections(IndexSet(integer: 0))
}, completion: nil)
})
}
}
extension SearchViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
/**
Method returns the number of items in each section
- parameter collectionView: UICollectionView
- parameter section: Int
- returns: Int
*/
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return popularTags.count
}
/**
Method sets up the cell for item at indexPath
- parameter collectionView: UICollectionView
- parameter indexPath: IndexPath
- returns: UICollectionViewCell
*/
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCollectionViewCell", for: indexPath) as? TagCollectionViewCell else {
return UICollectionViewCell()
}
cell.tagLabel.text = popularTags[indexPath.item]
return cell
}
/**
Method returns the size for item at indexPath
- parameter collectionView: UICollectionVIew
- parameter collectionViewLayout: UICollectionViewLayout
- parameter indexPath: IndexPath
- returns: CGSize
*/
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = NSString(string: popularTags[indexPath.item].uppercased()).size(withAttributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 13.0)])
return CGSize(width: size.width + kCellPadding, height: 30.0)
}
/**
Method is called when a cell in the collection view is selected. In this case we segue to the feed vc with search results for that tag
- parameter collectionView: UICollectionView
- parameter indexPath: IndexPath
*/
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
// open feed of items with selected tag
if let vc = Utils.vcWithNameFromStoryboardWithName("FeedViewController", storyboardName: "Feed") as? FeedViewController {
vc.searchQuery = popularTags[indexPath.item]
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
extension SearchViewController: UITextFieldDelegate {
/**
Method defines the action taken when the return key of the keyboard is pressed
- parameter textField: UITextField
- returns: Bool
*/
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if let query = textField.text, let vc = Utils.vcWithNameFromStoryboardWithName("FeedViewController", storyboardName: "Feed") as? FeedViewController, query.count > 0 {
vc.searchQuery = query
self.navigationController?.pushViewController(vc, animated: true)
} else {
print(NSLocalizedString("Invalid search query", comment: ""))
textField.shakeView()
}
return true
}
/**
Method limits the amount of characters that can be entered in the search text field
- parameter textField: UITextField
- parameter range: NSRange
- parameter string: String
- returns: Bool
*/
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text, text.count + string.count <= 40 {
return true
}
return false
}
}
| apache-2.0 | 8d9c9ebfa9cbc71eeaf62973d37bfe43 | 34 | 174 | 0.694297 | 5.403431 | false | false | false | false |
inacioferrarini/York | Example/Tests/York/DataSyncRules/Entities/EntitySyncHistoryTests.swift | 1 | 2768 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// 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 XCTest
import York
class EntitySyncHistoryTests: XCTestCase {
// MARK: - Tests
func test_fetchEntityAutoSyncHistory_withEmptyName_mustReturnNil() {
let coreDataStack = TestUtil().appContext().coreDataStack
let context = coreDataStack.managedObjectContext
let sincHistory = EntitySyncHistory.fetchEntityAutoSyncHistoryByName("", inManagedObjectContext: context)
XCTAssertNil(sincHistory)
}
func test_newEntityAutoSyncHistory_withEmptyName_mustReturnNil() {
let coreDataStack = TestUtil().appContext().coreDataStack
let context = coreDataStack.managedObjectContext
let sincHistory = EntitySyncHistory.entityAutoSyncHistoryByName("", lastExecutionDate: nil, inManagedObjectContext: context)
XCTAssertNil(sincHistory)
}
func test_removeAll_withoutEntities_mustNotCrash() {
let coreDataStack = TestUtil().appContext().coreDataStack
let context = coreDataStack.managedObjectContext
EntitySyncHistory.removeAll(inManagedObjectContext: context)
}
func test_removeAll_withEntities_mustNotCrash() {
let coreDataStack = TestUtil().appContext().coreDataStack
let context = coreDataStack.managedObjectContext
let ruleName = TestUtil().randomString()
_ = EntitySyncHistory.entityAutoSyncHistoryByName(ruleName, lastExecutionDate: nil, inManagedObjectContext: context)
coreDataStack.saveContext()
EntitySyncHistory.removeAll(inManagedObjectContext: context)
coreDataStack.saveContext()
}
}
| mit | 11998b4d1ef5fd5e93340ea3c198e46a | 43.629032 | 132 | 0.736176 | 4.888693 | false | true | false | false |
ktatroe/MPA-Horatio | HoratioDemo/HoratioDemo/Classes/Persistence/PersistentStoreController.swift | 2 | 5529 | //
// Copyright © 2016 Kevin Tatroe. All rights reserved.
// See LICENSE.txt for this sample’s licensing information
import Foundation
import CoreData
public typealias CoreDataActivityBlock = (context: NSManagedObjectContext) -> Void
public typealias CoreDataCompletionBlock = (Void) -> Void
public class PersistentStoreController {
var mainContext: NSManagedObjectContext
// MARK: - Initialization
init?(storeName: String) {
guard let storeURL = self.dynamicType.persistentStoreURL() else { return nil }
guard let model = NSManagedObjectModel.mergedModelFromBundles(nil) else { return nil }
self.storeName = storeName
self.coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
self.mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
self.writeContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
self.childContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
var error = makeStore(coordinator, atURL: storeURL)
if coordinator.persistentStores.isEmpty {
destroyStore(coordinator, atURL: storeURL)
error = makeStore(coordinator, atURL: storeURL)
}
if coordinator.persistentStores.isEmpty {
print("Error creating SQLite store: \(error).")
print("Falling back to `.InMemory` store.")
error = makeStore(coordinator, atURL: nil, type: NSInMemoryStoreType)
}
guard error == nil else { return nil }
writeContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
writeContext.persistentStoreCoordinator = coordinator
mainContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
mainContext.parentContext = writeContext
childContext.parentContext = mainContext
}
// MARK: - Public
/// Generate and return the a `NSURL` to store the local store in.
static func persistentStoreURL() -> NSURL? {
let searchDirectory: NSSearchPathDirectory = .DocumentDirectory
if let url = NSFileManager.defaultManager().URLsForDirectory(searchDirectory, inDomains: .UserDomainMask).last {
return url.URLByAppendingPathComponent(storeName)
}
return nil
}
/// Returns `true` if a persistent store has been created; or `false`, otherwise.
func persistentStoreExists() -> Bool {
if !coordinator.persistentStores.isEmpty {
return true
}
return false
}
/**
Perform a block in a newly-created child context, attempt to save that context, then
run a completion once done.
- Parameter block: The block to run to in a child context.
- Parameter completion: A block run when after the activity block is run and the context saved.
*/
func backgroundPerformBlock(block: CoreDataActivityBlock, completion: CoreDataCompletionBlock? = nil) {
childContext.performBlock { () -> Void in
block(context: self.childContext)
do {
try self.childContext.obtainPermanentIDsForObjects(Array(self.childContext.insertedObjects))
} catch { }
self.saveContext(self.childContext)
self.mainContext.performBlock({ () -> Void in
assert(NSThread.isMainThread() == true, "Save not performed on main thread!")
self.saveContext(self.mainContext)
self.writeContext.performBlock({ () -> Void in
self.saveContext(self.writeContext)
if let completion = completion {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion()
})
}
})
})
}
}
// MARK: - Private
private let storeName: String
private var writeContext: NSManagedObjectContext
private var childContext: NSManagedObjectContext
private var coordinator: NSPersistentStoreCoordinator
private func makeStore(coordinator: NSPersistentStoreCoordinator, atURL URL: NSURL?, type: String = NSSQLiteStoreType) -> NSError? {
var error: NSError?
do {
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
let _ = try coordinator.addPersistentStoreWithType(type, configuration: nil, URL: URL, options: options)
} catch let storeError as NSError {
error = storeError
}
return error
}
private func destroyStore(coordinator: NSPersistentStoreCoordinator, atURL URL: NSURL, type: String = NSSQLiteStoreType) {
do {
let _ = try coordinator.destroyPersistentStoreAtURL(URL, withType: type, options: nil)
} catch { }
}
private func saveContext(context: NSManagedObjectContext) -> Bool {
guard persistentStoreExists() else { return false }
guard context.hasChanges else { return false }
do {
try context.save()
} catch let error as NSError {
assertionFailure("Could not save context \(context). Error: \(error)")
return false
}
return true
}
}
| mit | fc1ce2b5e655bb925eb8fce21c63720a | 32.490909 | 136 | 0.655447 | 5.75625 | false | false | false | false |
JohnEstropia/CoreStore | Sources/UnsafeDataTransaction+Observing.swift | 1 | 15357 | //
// UnsafeDataTransaction+Observing.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - UnsafeDataTransaction
extension UnsafeDataTransaction {
/**
Creates an `ObjectMonitor` for the specified `DynamicObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `DynamicObject`.
- parameter object: the `DynamicObject` to observe changes from
- returns: an `ObjectMonitor` that monitors changes to `object`
*/
public func monitorObject<O: DynamicObject>(_ object: O) -> ObjectMonitor<O> {
return .init(objectID: object.cs_id(), context: self.unsafeContext())
}
/**
Creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list
*/
public func monitorList<O>(_ from: From<O>, _ fetchClauses: FetchClause...) -> ListMonitor<O> {
return self.monitorList(from, fetchClauses)
}
/**
Creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list
*/
public func monitorList<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) -> ListMonitor<O> {
Internals.assert(
fetchClauses.filter { $0 is OrderBy<O> }.count > 0,
"A ListMonitor requires an OrderBy clause."
)
return ListMonitor(
unsafeTransaction: self,
from: from,
sectionBy: nil,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
}
)
}
/**
Asynchronously creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
```
transaction.monitorList(
{ (monitor) in
self.monitor = monitor
},
From<MyPersonEntity>()
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter createAsynchronously: the closure that receives the created `ListMonitor` instance
- parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses
- returns: a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType`
*/
public func monitorList<B: FetchChainableBuilderType>(_ clauseChain: B) -> ListMonitor<B.ObjectType> {
return self.monitorList(clauseChain.from, clauseChain.fetchClauses)
}
/**
Asynchronously creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
- parameter createAsynchronously: the closure that receives the created `ListMonitor` instance
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorList<O>(createAsynchronously: @escaping (ListMonitor<O>) -> Void, _ from: From<O>, _ fetchClauses: FetchClause...) {
self.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses)
}
/**
Asynchronously creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
- parameter createAsynchronously: the closure that receives the created `ListMonitor` instance
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorList<O>(createAsynchronously: @escaping (ListMonitor<O>) -> Void, _ from: From<O>, _ fetchClauses: [FetchClause]) {
Internals.assert(
fetchClauses.filter { $0 is OrderBy<O> }.count > 0,
"A ListMonitor requires an OrderBy clause."
)
_ = ListMonitor(
unsafeTransaction: self,
from: from,
sectionBy: nil,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
},
createAsynchronously: createAsynchronously
)
}
/**
Asynchronously creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
```
dataStack.monitorList(
createAsynchronously: { (monitor) in
self.monitor = monitor
},
From<MyPersonEntity>()
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter createAsynchronously: the closure that receives the created `ListMonitor` instance
- parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses
*/
public func monitorList<B: FetchChainableBuilderType>(createAsynchronously: @escaping (ListMonitor<B.ObjectType>) -> Void, _ clauseChain: B) {
self.monitorList(
createAsynchronously: createAsynchronously,
clauseChain.from,
clauseChain.fetchClauses
)
}
/**
Creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list
*/
public func monitorSectionedList<O>(_ from: From<O>, _ sectionBy: SectionBy<O>, _ fetchClauses: FetchClause...) -> ListMonitor<O> {
return self.monitorSectionedList(from, sectionBy, fetchClauses)
}
/**
Creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list.
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: a `ListMonitor` instance that monitors changes to the list
*/
public func monitorSectionedList<O>(_ from: From<O>, _ sectionBy: SectionBy<O>, _ fetchClauses: [FetchClause]) -> ListMonitor<O> {
Internals.assert(
fetchClauses.filter { $0 is OrderBy<O> }.count > 0,
"A ListMonitor requires an OrderBy clause."
)
return ListMonitor(
unsafeTransaction: self,
from: from,
sectionBy: sectionBy,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
}
)
}
/**
Creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified `SectionMonitorBuilderType` built from a chain of clauses.
```
let monitor = transaction.monitorSectionedList(
From<MyPersonEntity>()
.sectionBy(\.age, { "\($0!) years old" })
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter clauseChain: a `SectionMonitorBuilderType` built from a chain of clauses
- returns: a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified `SectionMonitorBuilderType`
*/
public func monitorSectionedList<B: SectionMonitorBuilderType>(_ clauseChain: B) -> ListMonitor<B.ObjectType> {
return self.monitorSectionedList(
clauseChain.from,
clauseChain.sectionBy,
clauseChain.fetchClauses
)
}
/**
Asynchronously creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
- parameter createAsynchronously: the closure that receives the created `ListMonitor` instance
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorSectionedList<O>(createAsynchronously: @escaping (ListMonitor<O>) -> Void, _ from: From<O>, _ sectionBy: SectionBy<O>, _ fetchClauses: FetchClause...) {
self.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses)
}
/**
Asynchronously creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.
- parameter createAsynchronously: the closure that receives the created `ListMonitor` instance
- parameter from: a `From` clause indicating the entity type
- parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections.
- parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
*/
public func monitorSectionedList<O>(createAsynchronously: @escaping (ListMonitor<O>) -> Void, _ from: From<O>, _ sectionBy: SectionBy<O>, _ fetchClauses: [FetchClause]) {
Internals.assert(
fetchClauses.filter { $0 is OrderBy<O> }.count > 0,
"A ListMonitor requires an OrderBy clause."
)
_ = ListMonitor(
unsafeTransaction: self,
from: from,
sectionBy: sectionBy,
applyFetchClauses: { fetchRequest in
fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
},
createAsynchronously: createAsynchronously
)
}
/**
Asynchronously creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified `SectionMonitorBuilderType` built from a chain of clauses.
```
transaction.monitorSectionedList(
{ (monitor) in
self.monitor = monitor
},
From<MyPersonEntity>()
.sectionBy(\.age, { "\($0!) years old" })
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter createAsynchronously: the closure that receives the created `ListMonitor` instance
- parameter clauseChain: a `SectionMonitorBuilderType` built from a chain of clauses
*/
public func monitorSectionedList<B: SectionMonitorBuilderType>(createAsynchronously: @escaping (ListMonitor<B.ObjectType>) -> Void, _ clauseChain: B) {
self.monitorSectionedList(
createAsynchronously: createAsynchronously,
clauseChain.from,
clauseChain.sectionBy,
clauseChain.fetchClauses
)
}
}
| mit | ae10d648fc0226bf235a0eedcbe4df23 | 51.409556 | 455 | 0.684749 | 5.219579 | false | false | false | false |
ebpo90/2200 | 2200/StepCounter.swift | 1 | 5661 | //
// StepCounter.swift
// 2200
//
// Created by Francisco Soares on 2/4/15.
// Copyright (c) 2015 Eduardo Borges Pinto Osório. All rights reserved.
//
import Foundation
import UIKit
import HealthKit
class StepCounter {
var healthStore : HKHealthStore;
var anchor : Int = 0;
var obQuery : HKObserverQuery?
var start : NSDate;
// var predicate : NSPredicate?
var stepCount : Int {
didSet{
self.delegate.countUpdated(stepCount)
}
}
var delegate : CountDelegate;
init(healthStore : HKHealthStore, delegate : CountDelegate){
self.healthStore = healthStore
let calendar = NSCalendar.currentCalendar()
var comp = calendar.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: NSDate())
comp.hour = 0
comp.minute = 0
self.start = calendar.dateFromComponents(comp)!;
// self.start = NSDate(timeIntervalSinceNow: -24*60*60) // now - 1 day
self.stepCount = 0;
self.delegate = delegate;
}
func initStepCount(){
// let past : NSDate = NSDate.distantPast() as NSDate
let yesterday = start; //NSDate(timeIntervalSinceNow: -24*60*60)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false);
let idSteps = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
// let statQuery = HKStatisticsQuery(quantityType: idSteps, quantitySamplePredicate: mostRecentPredicate, options: HKStatisticsOptions.CumulativeSum, completionHandler: {(_,statistics,_) -> Void in
// if (statistics != nil) {
//
// if let quantity : HKQuantity! = statistics.sumQuantity(){
// if let q = quantity {
// var unit = HKUnit(fromString: "count")
// self.stepCount = Int(q.doubleValueForUnit(unit));
// }
// }
//
// }
// })
// if let setUpQuery = self.obQuery {
// self.healthStore.stopQuery(setUpQuery);
// self.obQuery = nil;
// }
//
if let setUpQuery = self.obQuery {
// skip;
}
else{
self.obQuery = HKObserverQuery(sampleType: idSteps, predicate:nil, updateHandler: {(_, handler, _) -> Void in
let mostRecentPredicate = HKQuery.predicateForSamplesWithStartDate(yesterday, endDate: NSDate(), options: HKQueryOptions.StrictStartDate)
// dispatch_after(5*1000,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { self.initStepCount() });
// // self.initStepCount();
let anchorQuery = HKAnchoredObjectQuery(type: idSteps, predicate: mostRecentPredicate, anchor: self.anchor, limit: 0, completionHandler: {(_, results, newAnchor,_) -> Void in
if (results != nil) {
if(newAnchor > self.anchor){
self.anchor = newAnchor
var sum:Int = 0
var unit = HKUnit(fromString: "count")
for quantitySample : HKQuantitySample in results as [HKQuantitySample]! {
var quantity = quantitySample.quantity
sum += Int(quantity.doubleValueForUnit(unit))
}
self.stepCount += sum
// if let quantity : HKQuantity! = statistics.sumQuantity(){
// if let q = quantity {
// var unit = HKUnit(fromString: "count")
// self.stepCount = Int(q.doubleValueForUnit(unit));
// }
// }
}
}
})
self.healthStore.executeQuery(anchorQuery);
//
// healthStore.executeQuery(statQuery);
handler()
/* For testing purposes */
// dispatch_async(dispatch_get_main_queue(), {
//
// var alert = UIAlertView(title: "Update", message: "Passos atualizados", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "ok" );
// alert.show()
//
// });
})
self.healthStore.executeQuery(self.obQuery);
}
}
func startObservingBackgroundChanges(){
let idSteps = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
self.healthStore.enableBackgroundDeliveryForType(idSteps, frequency: .Immediate, withCompletion: {(success, error) -> Void in
if success {
println("Enabled background delivery of steps increase")
// self.healthStore.executeQuery(self.obQuery)
}
else{
if let theError = error {
print("Failed to enable background delivery of weight changes")
println("Error = \(theError)")
}
}
})
}
func stopObservingChanges(){
healthStore.stopQuery(obQuery)
healthStore.disableAllBackgroundDeliveryWithCompletion({(succeeded:Bool, error: NSError!) in
if succeeded {
println("Disabled background delivery of step count increase")
}
else{
if let theError = error{
println("Failed to disable background delivery of steps")
println("Error = \(theError)")
}
}
})
}
}
protocol CountDelegate{
func countUpdated(newCount:Int);
}
| mit | 75242fb748324559dbeb550deea572f7 | 27.3 | 204 | 0.560247 | 5.013286 | false | false | false | false |
SheffieldKevin/SwiftGraphics | Playgrounds/Ellipse.playground/contents.swift | 1 | 2677 | // Playground - noun: a place where people can play
// Order of imports is very important
import CoreGraphics
import SwiftUtilities
import SwiftRandom
import SwiftGraphics
import SwiftGraphicsPlayground
var ellipses = [
Ellipse(
center: CGPoint.zero, semiMajorAxis: 300.0, eccentricity: 0.9, rotation: degreesToRadians(45)
), Ellipse(
center: CGPoint.zero, semiMajorAxis: 300.0, semiMinorAxis: 65.3834841531101 * 2, rotation: degreesToRadians(0)
), Ellipse(frame: CGRect(center: CGPoint.zero, size: CGSize(w: 600, h: 65.3834841531101 * 4))), Ellipse(frame: CGRect(center: CGPoint.zero, size: CGSize(w: 400, h: 400))),
]
let s = Int(ceil(sqrt(Double(ellipses.count))))
let style1 = SwiftGraphics.Style(elements: [
.StrokeColor(CGColor.redColor()),
])
let style2 = SwiftGraphics.Style(elements: [
.StrokeColor(CGColor.blueColor()),
.LineDash([5,5]),
])
let style3 = SwiftGraphics.Style(elements: [
.StrokeColor(CGColor.purpleColor()),
.LineDash([2,2]),
])
let styles = [
"center": style1,
"foci": style1,
"corner": style1,
"-a": style3,
"+a": style3,
"-b": style3,
"+b": style3,
"A": style3,
"B": style3,
"frame": style2,
"boundingBox": style2,
]
let cgpath = CGPathCreateWithEllipseInRect(CGRect(center: CGPoint.zero, radius: 1.0), nil)
cgpath.dump()
var generator = ellipses.generate()
let tileSize = CGSize(width: 800, height: 800)
let bitmapSize = tileSize * CGFloat(s)
let cgimage = CGContextRef.imageWithBlock(bitmapSize, color: CGColor.lightGrayColor(), origin: CGPoint.zero) {
(context: CGContext) -> Void in
CGContextSetShouldAntialias(context, false)
tiled(context, tileSize: tileSize, dimension: IntSize(width: s, height: s), origin: CGPoint(x: 0.5, y: 0.5)) {
(context: CGContext) -> Void in
if let ellipse = generator.next() {
var c: CGFloat = 0.551915024494
context.strokeColor = CGColor.greenColor()
var curves = ellipse.toBezierCurves(c)
context.stroke(curves.0)
context.stroke(curves.1)
context.stroke(curves.2)
context.stroke(curves.3)
context.strokeColor = CGColor.redColor()
c = 4.0 * (sqrt(2.0) - 1.0) / 3.0 // 0.5522847498307936
curves = ellipse.toBezierCurves(c)
context.stroke(curves.0)
context.stroke(curves.1)
context.stroke(curves.2)
context.stroke(curves.3)
let markup = ellipse.markup
context.draw(markup, styles: styles)
}
}
}
let image = NSImage(CGImage: cgimage, size: cgimage.size)
| bsd-2-clause | eedc193aab727374d5f93ee203264cf9 | 28.744444 | 179 | 0.639522 | 3.617568 | false | false | false | false |
dekatotoro/FluxWithRxSwiftSample | FluxWithRxSwiftSample/Actions/SearchUser/SearchUserAction.swift | 1 | 2531 | //
// SearchUserAction.swift
// FluxWithRxSwiftSample
//
// Created by Yuji Hato on 2016/10/13.
// Copyright © 2016年 dekatotoro. All rights reserved.
//
import RxSwift
class SearchUserAction {
static let shared = SearchUserAction()
private let dispatcher: SearchUserDispatcher
private let store: SearchUserStore
private let disposeBag = DisposeBag()
init(dispatcher: SearchUserDispatcher = .shared,
store: SearchUserStore = .shared) {
self.dispatcher = dispatcher
self.store = store
}
func loading(_ value: Bool) {
self.dispatcher.loading.dispatch(value)
}
func searchUser(query: String, page: Int) {
// before the request, the task in the request cancel
GitHubAPI.cancelSearchUser()
dispatcher.loading.dispatch(true)
if query.isEmpty {
dispatcher.searchUser.dispatch((0, SearchModel<GitHubUser>()))
dispatcher.loading.dispatch(false)
return
}
let params = ["q" : query,
"page" : page,
"per_page" : 30] as [String : Any]
GitHubAPI.searchUser(with: params)
.do(onError: { [unowned self] error in
self.dispatcher.error.dispatch(error)
self.dispatcher.loading.dispatch(false)
})
.do(onCompleted: { error in
// do nothing
})
.subscribe(onNext: { [unowned self] response in
let searchUser = SearchModel.make(from: query, gitHubResponse: response)
self.dispatcher.searchUser.dispatch((page, searchUser))
self.dispatcher.loading.dispatch(false)
})
.addDisposableTo(disposeBag)
}
func contentOffset(_ value: CGPoint) {
dispatcher.contentOffset.dispatch(value)
}
func scrollViewDidEndDragging(decelerate: Bool) {
dispatcher.scrollViewDidEndDragging.dispatch(decelerate)
}
}
extension SearchUserAction {
static func loading(_ value: Bool) {
shared.loading(value)
}
static func searchUser(query: String, page: Int) {
shared.searchUser(query: query, page: page)
}
static func contentOffset(_ value: CGPoint) {
shared.contentOffset(value)
}
static func scrollViewDidEndDragging(decelerate: Bool) {
shared.scrollViewDidEndDragging(decelerate: decelerate)
}
}
| mit | c24421029a3975078331b644e4e05c44 | 28.057471 | 88 | 0.597706 | 4.889749 | false | false | false | false |
SoneeJohn/WWDC | ConfCore/ContributorsFetcher.swift | 1 | 4784 | //
// ContributorsFetcher.swift
// WWDC
//
// Created by Guilherme Rambo on 28/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import SwiftyJSON
public final class ContributorsFetcher {
public static let shared: ContributorsFetcher = ContributorsFetcher()
fileprivate struct Constants {
static let contributorsURL = "https://api.github.com/repos/insidegui/WWDC/contributors"
}
private let syncQueue = DispatchQueue(label: "io.wwdc.app.contributorsfetcher.sync")
private var names = [String]()
public var infoTextChangedCallback: (_ newText: String) -> () = { _ in }
public var infoText = "" {
didSet {
DispatchQueue.main.async {
self.infoTextChangedCallback(self.infoText)
}
}
}
/// Loads the list of contributors from the GitHub repository and builds the infoText
public func load() {
guard let url = URL(string: Constants.contributorsURL) else { return }
names = [String]()
loadFrom(url: url)
}
private func loadFrom(url: URL) {
let task = URLSession.shared.dataTask(with: url) { [unowned self] data, response, error in
guard let data = data, error == nil else {
if let error = error {
NSLog("[ContributorsFetcher] Error fetching contributors: \(error)")
} else {
NSLog("[ContributorsFetcher] Error fetching contributors: no data returned")
}
self.buildInfoText(self.names)
return
}
self.syncQueue.async {
self.names += self.parseResponse(data)
if let linkHeader = (response as? HTTPURLResponse)?.allHeaderFields["Link"] as? String,
let nextPage = GitHubPagination(linkHeader: linkHeader)?.next {
self.loadFrom(url: nextPage)
} else {
self.buildInfoText(self.names)
}
}
}
task.resume()
}
fileprivate func parseResponse(_ data: Data) -> [String] {
let jsonData = JSON(data: data)
guard let contributors = jsonData.array else { return [String]() }
var contributorNames = [String]()
for contributor in contributors {
if let name = contributor["login"].string {
contributorNames.append(name)
}
}
return contributorNames
}
fileprivate func buildInfoText(_ names: [String]) {
var text = "Contributors (GitHub usernames):\n"
var prefix = ""
for name in names {
text.append("\(prefix)\(name)")
prefix = ", "
}
infoText = text
}
}
private struct GitHubPagination {
var first: URL?
var next: URL?
var previous: URL?
var last: URL?
private static let urlRegex = try! NSRegularExpression(pattern: "<(.*)>", options: [])
private static let typeRegex = try! NSRegularExpression(pattern: "rel=\"(.*)\"", options: [])
init?(linkHeader: String) {
let links: [(URL, String)] = linkHeader.components(separatedBy: ",").flatMap { link in
let section = link.components(separatedBy: ";")
if section.count < 2 {
return nil
}
let urlRange = NSRange(location: 0, length: section[0].characters.count)
var urlString = GitHubPagination.urlRegex.stringByReplacingMatches(in: section[0],
range: urlRange,
withTemplate: "$1")
urlString = urlString.trimmingCharacters(in: .whitespaces)
guard let url = URL(string: urlString) else {
return nil
}
let typeRange = NSRange(location: 0, length: section[1].characters.count)
var type = GitHubPagination.typeRegex.stringByReplacingMatches(in: section[1],
range: typeRange,
withTemplate: "$1")
type = type.trimmingCharacters(in: .whitespaces)
return (url, type)
}
for (url, type) in links {
switch type {
case "first":
first = url
case "next":
next = url
case "prev":
previous = url
case "last":
last = url
default:
break;
}
}
}
}
| bsd-2-clause | f767c96d5b05c976d199f163ef8360e3 | 30.058442 | 103 | 0.520803 | 5.215921 | false | false | false | false |
terietor/GTForms | Source/Forms/FormSegmentedPicker.swift | 1 | 3140 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SnapKit
import GTSegmentedControl
private class SegmentedControlLabelView<L: UILabel>: ControlLabelView<L> {
let segmentedControl = SegmentedControl()
override init() {
super.init()
self.control = self.segmentedControl
configureView() { (label, control) in
label.snp.makeConstraints() { make in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(0.4)
make.top.equalTo(self)
make.bottom.equalTo(self)
} // end label
control.snp.makeConstraints() { make in
make.centerY.equalTo(label.snp.centerY).priority(UILayoutPriorityDefaultLow)
make.right.equalTo(self)
make.left.equalTo(label.snp.right).offset(10)
make.height.lessThanOrEqualTo(self)
} // end control
} // end configureView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public class FormSegmentedPicker: BaseResultForm<String> {
private let segmentedControlView = SegmentedControlLabelView()
public var segmentedControl: SegmentedControl {
return self.segmentedControlView.segmentedControl
}
public init(text: String, items: [String], itemsPerRow: Int = 3) {
super.init()
self.text = text
self.segmentedControlView.segmentedControl.items = items
self.segmentedControlView.segmentedControl.itemsPerRow = itemsPerRow
self.segmentedControlView.controlLabel.text = self.text
self.segmentedControlView.segmentedControl.valueDidChange = { result in
self.updateResult(result)
}
}
public override func formView() -> UIView {
return self.segmentedControlView
}
}
| mit | 3c4a4df98df28aafc5ec27bd2add8a1c | 34.681818 | 92 | 0.666561 | 4.937107 | false | false | false | false |
TheHolyGrail/Swallow | ELWebServiceExample/ELWebServiceExample/View Controllers/BrewIndexViewController.swift | 3 | 2806 | //
// BrewIndexViewController.swift
// SwallowExample
//
// Created by Angelo Di Paolo on 9/30/15.
// Copyright © 2015 TheHolyGrail. All rights reserved.
//
import UIKit
class BrewIndexViewController: UIViewController {
@IBOutlet weak var tableView: UITableView?
fileprivate(set) var brewClient = BrewClient()
fileprivate var brews = [Brew]() {
didSet {
tableView?.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchBrews()
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Tasty Brews"
tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "BrewCell")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add Brew", style: UIBarButtonItemStyle.plain, target: self, action: #selector(BrewIndexViewController.addBrewTapped))
}
}
// MARK: - Fetching Data
extension BrewIndexViewController {
func fetchBrews() {
brewClient
.fetchAllBrews()
.responseAsBrews { [weak self] brews in
self?.brews = brews
}
.responseError {error in
print("I AM ERROR = \(error)")
}
.resume()
}
}
// MARK: - Table View
extension BrewIndexViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return brews.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BrewCell", for: indexPath)
let brew = brews[indexPath.row]
cell.textLabel?.text = brew.name
return cell
}
}
extension BrewIndexViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let brew = brews[indexPath.row]
brewTapped(brew)
}
}
// MARK: - Actions
extension BrewIndexViewController {
func addBrewTapped() {
let brewAddViewController = BrewAddViewController(brewClient: brewClient)
let navigationController = UINavigationController(rootViewController: brewAddViewController)
present(navigationController, animated: true, completion: nil)
}
func brewTapped(_ brew: Brew) {
let brewDetailViewController = BrewDetailViewController(brew: brew)
navigationController?.pushViewController(brewDetailViewController, animated: true)
}
}
| mit | 875e283a8c5eae57ee5d904c285521e2 | 27.333333 | 185 | 0.65098 | 5 | false | false | false | false |
longjianjiang/BlogDemo | CAGradientLayerDemo/CAGradientLayerDemo/ViewController.swift | 1 | 1778 | //
// ViewController.swift
// CAGradientLayerDemo
//
// Created by longjianjiang on 2017/10/7.
// Copyright © 2017年 Jiang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var tableView = UITableView()
var titles = ["gradient effect", "gradient animation"]
override func viewDidLoad() {
super.viewDidLoad()
title = "CAGradientLayer"
tableView.frame = view.bounds
tableView.rowHeight = 44
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = titles[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
navigationController?.pushViewController(GradientEffectViewController(), animated: true)
} else if indexPath.row == 1 {
navigationController?.pushViewController(GradientAnimationViewController(), animated: true)
}
}
}
| apache-2.0 | cbadb6e03230d095e1972101b6d11ed9 | 29.603448 | 103 | 0.667042 | 5.444785 | false | false | false | false |
mubassirhayat/Neon | Source/Neon.swift | 1 | 56066 | //
// Neon.swift
// Neon
//
// Created by Mike on 9/16/15.
// Copyright © 2015 Mike Amaral. All rights reserved.
//
import UIKit
extension UIView {
// MARK: Frame shortcuts
//
/// Get the x origin of a view.
///
/// - returns: The minimum x value of the view's frame.
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.x() // returns 10.0
///
func x() -> CGFloat {
return CGRectGetMinX(frame)
}
/// Get the mid x of a view.
///
/// - returns: The middle x value of the view's frame
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.midX() // returns 7.5
///
func xMid() -> CGFloat {
return CGRectGetMinX(frame) + (CGRectGetWidth(frame) / 2.0)
}
/// Get the max x of a view.
///
/// - returns: The maximum x value of the view's frame
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.maxX() // returns 15.0
///
func xMax() -> CGFloat {
return CGRectGetMaxX(frame)
}
/// Get the y origin of a view.
///
/// - returns: The minimum y value of the view's frame.
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.y() // returns 20.0
///
func y() -> CGFloat {
return CGRectGetMinY(frame)
}
/// Get the mid y of a view.
///
/// - returns: The middle y value of the view's frame
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.midY() // returns 13.5
///
func yMid() -> CGFloat {
return CGRectGetMinY(frame) + (CGRectGetHeight(frame) / 2.0)
}
/// Get the max y of a view.
///
/// - returns: The maximum y value of the view's frame.
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.maxY() // returns 27.0
///
func yMax() -> CGFloat {
return CGRectGetMaxY(frame)
}
/// Get the width of a view.
///
/// - returns: The width of the view's frame.
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.width() // returns 5.0
///
func width() -> CGFloat {
return CGRectGetWidth(frame)
}
/// Get the height of a view.
///
/// - returns: The height of the view's frame.
///
/// Example
/// -------
/// let frame = CGRectMake(10.0, 20.0, 5.0, 7.0)
/// frame.height() // returns 7.0
///
func height() -> CGFloat {
return CGRectGetHeight(frame)
}
// MARK: Corner
//
///
/// Specifies a corner of a frame.
///
/// **TopLeft**: The upper-left corner of the frame.
///
/// **TopRight**: The upper-right corner of the frame.
///
/// **BottomLeft**: The bottom-left corner of the frame.
///
/// **BottomRight**: The upper-right corner of the frame.
///
enum Corner {
case TopLeft
case TopRight
case BottomLeft
case BottomRight
}
// MARK: Edge
//
///
/// Specifies an edge, or face, of a frame.
///
/// **Top**: The top edge of the frame.
///
/// **Left**: The left edge of the frame.
///
/// **Bottom**: The bottom edge of the frame.
///
/// **Right**: The right edge of the frame.
///
enum Edge {
case Top
case Left
case Bottom
case Right
}
// MARK: Align Type
//
///
/// Specifies how a view will be aligned relative to the sibling view.
///
/// **ToTheRightMatchingTop**: Specifies that the view should be aligned to the right of a sibling, matching the
/// top, or y origin, of the sibling's frame.
///
/// **ToTheRightMatchingBottom**: Specifies that the view should be aligned to the right of a sibling, matching
/// the bottom, or max y value, of the sibling's frame.
///
/// **ToTheRightCentered**: Specifies that the view should be aligned to the right of a sibling, and will be centered
/// to either match the vertical center of the sibling's frame or centered vertically within the superview, depending
/// on the context.
///
/// **ToTheLeftMatchingTop**: Specifies that the view should be aligned to the left of a sibling, matching the top,
/// or y origin, of the sibling's frame.
///
/// **ToTheLeftMatchingBottom**: Specifies that the view should be aligned to the left of a sibling, matching the
/// bottom, or max y value, of the sibling's frame.
///
/// **ToTheLeftCentered**: Specifies that the view should be aligned to the left of a sibling, and will be centered
/// to either match the vertical center of the sibling's frame or centered vertically within the superview, depending
/// on the context.
///
/// **UnderMatchingLeft**: Specifies that the view should be aligned under a sibling, matching the left, or x origin,
/// of the sibling's frame.
///
/// **UnderMatchingRight**: Specifies that the view should be aligned under a sibling, matching the right, or max y
/// of the sibling's frame.
///
/// **UnderCentered**: Specifies that the view should be aligned under a sibling, and will be centered to either match
/// the horizontal center of the sibling's frame or centered horizontally within the superview, depending on the context.
///
/// **AboveMatchingLeft**: Specifies that the view should be aligned above a sibling, matching the left, or x origin
/// of the sibling's frame.
///
/// **AboveMatchingRight**: Specifies that the view should be aligned above a sibling, matching the right, or max x
/// of the sibling's frame.
///
/// **AboveCentered**: Specifies that the view should be aligned above a sibling, and will be centered to either match
/// the horizontal center of the sibling's frame or centered horizontally within the superview, depending on the context.
///
enum Align {
case ToTheRightMatchingTop
case ToTheRightMatchingBottom
case ToTheRightCentered
case ToTheLeftMatchingTop
case ToTheLeftMatchingBottom
case ToTheLeftCentered
case UnderMatchingLeft
case UnderMatchingRight
case UnderCentered
case AboveMatchingLeft
case AboveMatchingRight
case AboveCentered
}
// MARK: Group Type
//
///
/// Specifies how a group will be laid out.
///
/// **Horizontal**: Specifies that the views should be aligned relative to eachother horizontally.
///
/// **Vertical**: Specifies that the views should be aligned relative to eachother vertically.
///
enum Group {
case Horizontal
case Vertical
}
// MARK: Filling superview
//
/// Fill the superview, with optional padding values.
///
/// - note: If you don't want padding, simply call `fillSuperview()` with no parameters.
///
/// - parameters:
/// - left: The padding between the left side of the view and the superview.
///
/// - right: The padding between the right side of the view and the superview.
///
/// - top: The padding between the top of the view and the superview.
///
/// - bottom: The padding between the bottom of the view and the superview.
///
func fillSuperview(left left: CGFloat = 0, right: CGFloat = 0, top: CGFloat = 0, bottom: CGFloat = 0) {
if superview == nil {
print("[NEON] Warning: Can't anchor view without superview!")
return
}
let width : CGFloat = superview!.width() - (left + right)
let height : CGFloat = superview!.height() - (top + bottom)
frame = CGRectMake(left, top, width, height)
}
// MARK: Anchoring in superview
//
/// Anchor a view in the center of its superview.
///
/// - parameters:
/// - width: The width of the view.
///
/// - height: The height of the view.
///
func anchorInCenter(width width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't anchor view without superview!")
return
}
let xOrigin : CGFloat = (superview!.width() / 2.0) - (width / 2.0)
let yOrigin : CGFloat = (superview!.height() / 2.0) - (height / 2.0)
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
/// Anchor a view in one of the four corners of its superview.
///
/// - parameters:
/// - corner: The `CornerType` value used to specify in which corner the view will be anchored.
///
/// - xPad: The *horizontal* padding applied to the view inside its superview, which can be applied
/// to the left or right side of the view, depending upon the `CornerType` specified.
///
/// - yPad: The *vertical* padding applied to the view inside its supeview, which will either be on
/// the top or bottom of the view, depending upon the `CornerType` specified.
///
/// - width: The width of the view.
///
/// - height: The height of the view.
///
func anchorInCorner(corner: Corner, xPad: CGFloat, yPad: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't anchor view without superview!")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
switch corner {
case .TopLeft:
xOrigin = xPad
yOrigin = yPad
case .BottomLeft:
xOrigin = xPad
yOrigin = superview!.height() - height - yPad
case .TopRight:
xOrigin = superview!.width() - width - xPad
yOrigin = yPad
case .BottomRight:
xOrigin = superview!.width() - width - xPad
yOrigin = superview!.height() - height - yPad
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
/// Anchor a view in its superview, centered on a given edge.
///
/// - parameters:
/// - edge: The `Edge` used to specify which face of the superview the view
/// will be anchored against and centered relative to.
///
/// - padding: The padding applied to the view inside its superview. How this padding is applied
/// will vary depending on the `Edge` provided. Views centered against the top or bottom of
/// their superview will have the padding applied above or below them respectively, whereas views
/// centered against the left or right side of their superview will have the padding applied to the
/// right and left sides respectively.
///
/// - width: The width of the view.
///
/// - height: The height of the view.
///
func anchorToEdge(edge: Edge, padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't anchor view without superview!")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
switch edge {
case .Top:
xOrigin = (superview!.width() / 2.0) - (width / 2.0)
yOrigin = padding
case .Left:
xOrigin = padding
yOrigin = (superview!.height() / 2.0) - (height / 2.0)
case .Bottom:
xOrigin = (superview!.width() / 2.0) - (width / 2.0)
yOrigin = superview!.height() - height - padding
case .Right:
xOrigin = superview!.width() - width - padding
yOrigin = (superview!.height() / 2.0) - (height / 2.0)
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
/// Anchor a view in its superview, centered on a given edge and filling either the width or
/// height of that edge. For example, views anchored to the `.Top` or `.Bottom` will have
/// their widths automatically sized to fill their superview, with the xPad applied to both
/// the left and right sides of the view.
///
/// - parameters:
/// - edge: The `Edge` used to specify which face of the superview the view
/// will be anchored against, centered relative to, and expanded to fill.
///
/// - xPad: The horizontal padding applied to the view inside its superview. If the `Edge`
/// specified is `.Top` or `.Bottom`, this padding will be applied to the left and right sides
/// of the view when it fills the width superview.
///
/// - yPad: The vertical padding applied to the view inside its superview. If the `Edge`
/// specified is `.Left` or `.Right`, this padding will be applied to the top and bottom sides
/// of the view when it fills the height of the superview.
///
/// - otherSize: The size parameter that is *not automatically calculated* based on the provided
/// edge. For example, views anchored to the `.Top` or `.Bottom` will have their widths automatically
/// calculated, so `otherSize` will be applied to their height, and subsequently views anchored to
/// the `.Left` and `.Right` will have `otherSize` applied to their width as their heights are
/// automatically calculated.
///
func anchorAndFillEdge(edge: Edge, xPad: CGFloat, yPad: CGFloat, otherSize: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't anchor view without superview!")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var width : CGFloat = 0.0
var height : CGFloat = 0.0
switch edge {
case .Top:
xOrigin = xPad
yOrigin = yPad
width = superview!.width() - (2 * xPad)
height = otherSize
case .Left:
xOrigin = xPad
yOrigin = yPad
width = otherSize
height = superview!.height() - (2 * yPad)
case .Bottom:
xOrigin = xPad
yOrigin = superview!.height() - otherSize - yPad
width = superview!.width() - (2 * xPad)
height = otherSize
case .Right:
xOrigin = superview!.width() - otherSize - xPad
yOrigin = yPad
width = otherSize
height = superview!.height() - (2 * yPad)
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
// MARK: Align relative to sibling views
//
/// Align a view relative to a sibling view in the same superview.
///
/// - parameters:
/// - align: The `Align` type used to specify where and how this view is aligned with its sibling.
///
/// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares
/// the same superview as this view, and that the sibling view is not the same as this view, otherwise a
/// `fatalError` is thrown.
///
/// - padding: The padding to be applied between this view and the sibling view, which is applied differently
/// depending on the `Align` specified. For example, if aligning `.ToTheRightOfMatchingTop` the padding is used
/// to adjust the x origin of this view so it sits to the right of the sibling view, while the y origin is
/// automatically calculated to match the sibling view.
///
/// - width: The width of the view.
///
/// - height: The height of the view.
///
func align(align: Align, relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't align view without superview!")
return
}
if self == sibling {
fatalError("[NEON] Can't align view relative to itself!")
}
if superview != sibling.superview {
fatalError("[NEON] Can't align view relative to another view in a different superview!")
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
switch align {
case .ToTheRightMatchingTop:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.y()
case .ToTheRightMatchingBottom:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMax() - height
case .ToTheRightCentered:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMid() - (height / 2.0)
case .ToTheLeftMatchingTop:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.y()
case .ToTheLeftMatchingBottom:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.yMax() - height
case .ToTheLeftCentered:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.yMid() - (height / 2.0)
case .UnderMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.yMax() + padding
case .UnderMatchingRight:
xOrigin = sibling.xMax() - width
yOrigin = sibling.yMax() + padding
case .UnderCentered:
xOrigin = sibling.xMid() - (width / 2.0)
yOrigin = sibling.yMax() + padding
case .AboveMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.y() - padding - height
case .AboveMatchingRight:
xOrigin = sibling.xMax() - width
yOrigin = sibling.y() - padding - height
case .AboveCentered:
xOrigin = sibling.xMid() - (width / 2.0)
yOrigin = sibling.y() - padding - height
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
/// Align a view relative to a sibling view in the same superview, and automatically expand the width to fill
/// the superview with equal padding between the superview and sibling view.
///
/// - parameters:
/// - align: The `Align` type used to specify where and how this view is aligned with its sibling.
///
/// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares
/// the same superview as this view, and that the sibling view is not the same as this view, otherwise a
/// `fatalError` is thrown.
///
/// - padding: The padding to be applied between this view, the sibling view and the superview.
///
/// - height: The height of the view.
///
func alignAndFillWidth(align align: Align, relativeTo sibling: UIView, padding: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't align view without superview!")
return
}
if self == sibling {
fatalError("[NEON] Can't align view relative to itself!")
}
if superview != sibling.superview {
fatalError("[NEON] Can't align view relative to another view in a different superview!")
}
let superviewWidth = superview!.width()
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var width : CGFloat = 0.0
switch align {
case .ToTheRightMatchingTop:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.y()
width = superviewWidth - xOrigin - padding
case .ToTheRightMatchingBottom:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMax() - height
width = superviewWidth - xOrigin - padding
case .ToTheRightCentered:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMid() - (height / 2.0)
width = superviewWidth - xOrigin - padding
case .ToTheLeftMatchingTop:
xOrigin = padding
yOrigin = sibling.y()
width = sibling.x() - (2 * padding)
case .ToTheLeftMatchingBottom:
xOrigin = padding
yOrigin = sibling.yMax() - height
width = sibling.x() - (2 * padding)
case .ToTheLeftCentered:
xOrigin = padding
yOrigin = sibling.yMid() - (height / 2.0)
width = sibling.x() - (2 * padding)
case .UnderMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.yMax() + padding
width = superviewWidth - xOrigin - padding
case .UnderMatchingRight:
xOrigin = padding
yOrigin = sibling.yMax() + padding
width = superviewWidth - (superviewWidth - sibling.xMax()) - padding
case .UnderCentered:
xOrigin = padding
yOrigin = sibling.yMax() + padding
width = superviewWidth - (2 * padding)
case .AboveMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.y() - padding - height
width = superviewWidth - xOrigin - padding
case .AboveMatchingRight:
xOrigin = padding
yOrigin = sibling.y() - padding - height
width = superviewWidth - (superviewWidth - sibling.xMax()) - padding
case .AboveCentered:
xOrigin = padding
yOrigin = sibling.y() - padding - height
width = superviewWidth - (2 * padding)
}
if width < 0.0 {
width = 0.0
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
/// Align a view relative to a sibling view in the same superview, and automatically expand the height to fill
/// the superview with equal padding between the superview and sibling view.
///
/// - parameters:
/// - align: The `Align` type used to specify where and how this view is aligned with its sibling.
///
/// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares
/// the same superview as this view, and that the sibling view is not the same as this view, otherwise a
/// `fatalError` is thrown.
///
/// - padding: The padding to be applied between this view, the sibling view and the superview.
///
/// - width: The width of the view.
///
func alignAndFillHeight(align align: Align, relativeTo sibling: UIView, padding: CGFloat, width: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't align view without superview!")
return
}
if self == sibling {
fatalError("[NEON] Can't align view relative to itself!")
}
if superview != sibling.superview {
fatalError("[NEON] Can't align view relative to another view in a different superview!")
}
let superviewHeight = superview!.height()
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var height : CGFloat = 0.0
switch align {
case .ToTheRightMatchingTop:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.y()
height = superviewHeight - sibling.y() - padding
case .ToTheRightMatchingBottom:
xOrigin = sibling.xMax() + padding
yOrigin = padding
height = superviewHeight - (superviewHeight - sibling.yMax()) - padding
case .ToTheRightCentered:
xOrigin = sibling.xMax() + padding
yOrigin = padding
height = superviewHeight - (2 * padding)
case .ToTheLeftMatchingTop:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.y()
height = superviewHeight - sibling.y() - padding
case .ToTheLeftMatchingBottom:
xOrigin = sibling.x() - width - padding
yOrigin = padding
height = superviewHeight - (superviewHeight - sibling.yMax()) - padding
case .ToTheLeftCentered:
xOrigin = sibling.x() - width - padding
yOrigin = padding
height = superviewHeight - (2 * padding)
case .UnderMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.yMax() + padding
height = superviewHeight - yOrigin - padding
case .UnderMatchingRight:
xOrigin = sibling.xMax() - width
yOrigin = sibling.yMax() + padding
height = superviewHeight - yOrigin - padding
case .UnderCentered:
xOrigin = sibling.xMid() - (width / 2.0)
yOrigin = sibling.yMax() + padding
height = superviewHeight - yOrigin - padding
case .AboveMatchingLeft:
xOrigin = sibling.x()
yOrigin = padding
height = sibling.y() - (2 * padding)
case .AboveMatchingRight:
xOrigin = sibling.xMax() - width
yOrigin = padding
height = sibling.y() - (2 * padding)
case .AboveCentered:
xOrigin = sibling.xMid() - (width / 2.0)
yOrigin = padding
height = sibling.y() - (2 * padding)
}
if height < 0.0 {
height = 0.0
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
/// Align a view relative to a sibling view in the same superview, and automatically expand the width AND height
/// to fill the superview with equal padding between the superview and sibling view.
///
/// - parameters:
/// - align: The `Align` type used to specify where and how this view is aligned with its sibling.
///
/// - relativeTo: The sibling view this view will be aligned relative to. **NOTE:** Ensure this sibling view shares
/// the same superview as this view, and that the sibling view is not the same as this view, otherwise a
/// `fatalError` is thrown.
///
/// - padding: The padding to be applied between this view, the sibling view and the superview.
///
func alignAndFill(align align: Align, relativeTo sibling: UIView, padding: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't align view without superview!")
return
}
if self == sibling {
fatalError("[NEON] Can't align view relative to itself!")
}
if superview != sibling.superview {
fatalError("[NEON] Can't align view relative to another view in a different superview!")
}
let superviewWidth = superview!.width()
let superviewHeight = superview!.height()
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var width : CGFloat = 0.0
var height : CGFloat = 0.0
switch align {
case .ToTheRightMatchingTop:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.y()
width = superviewWidth - xOrigin - padding
height = superviewHeight - yOrigin - padding
case .ToTheRightMatchingBottom:
xOrigin = sibling.xMax() + padding
yOrigin = padding
width = superviewWidth - xOrigin - padding
height = superviewHeight - (superviewHeight - sibling.yMax()) - padding
case .ToTheRightCentered:
xOrigin = sibling.xMax() + padding
yOrigin = padding
width = superviewWidth - xOrigin - padding
height = superviewHeight - (2 * padding)
case .ToTheLeftMatchingTop:
xOrigin = padding
yOrigin = sibling.y()
width = superviewWidth - (superviewWidth - sibling.x()) - (2 * padding)
height = superviewHeight - yOrigin - padding
case .ToTheLeftMatchingBottom:
xOrigin = padding
yOrigin = padding
width = superviewWidth - (superviewWidth - sibling.x()) - (2 * padding)
height = superviewHeight - (superviewHeight - sibling.yMax()) - padding
case .ToTheLeftCentered:
xOrigin = padding
yOrigin = padding
width = superviewWidth - (superviewWidth - sibling.x()) - (2 * padding)
height = superviewHeight - (2 * padding)
case .UnderMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.yMax() + padding
width = superviewWidth - xOrigin - padding
height = superviewHeight - yOrigin - padding
case .UnderMatchingRight:
xOrigin = padding
yOrigin = sibling.yMax() + padding
width = superviewWidth - (superviewWidth - sibling.xMax()) - padding
height = superviewHeight - yOrigin - padding
case .UnderCentered:
xOrigin = padding
yOrigin = sibling.yMax() + padding
width = superviewWidth - (2 * padding)
height = superviewHeight - yOrigin - padding
case .AboveMatchingLeft:
xOrigin = sibling.x()
yOrigin = padding
width = superviewWidth - xOrigin - padding
height = superviewHeight - (superviewHeight - sibling.y()) - (2 * padding)
case .AboveMatchingRight:
xOrigin = padding
yOrigin = padding
width = superviewWidth - (superviewWidth - sibling.xMax()) - padding
height = superviewHeight - (superviewHeight - sibling.y()) - (2 * padding)
case .AboveCentered:
xOrigin = padding
yOrigin = padding
width = superviewWidth - (2 * padding)
height = superviewHeight - (superviewHeight - sibling.y()) - (2 * padding)
}
if width < 0.0 {
width = 0.0
}
if height < 0.0 {
height = 0.0
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
// MARK: Align between siblings
//
/// Align a view between two sibling views horizontally, automatically expanding the width to extend the full
/// horizontal span between the `primaryView` and the `secondaryView`, with equal padding on both sides.
///
/// - parameters:
/// - align: The `Align` type used to specify where and how this view is aligned with the primary view.
///
/// - primaryView: The primary sibling view this view will be aligned relative to.
///
/// - secondaryView: The secondary sibling view this view will be automatically sized to fill the space between.
///
/// - padding: The horizontal padding to be applied between this view and both sibling views.
///
/// - height: The height of the view.
///
func alignBetweenHorizontal(align align: Align, primaryView: UIView, secondaryView: UIView, padding: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't align view without superview!")
return
}
if self == primaryView || self == secondaryView {
fatalError("[NEON] Can't align view relative to itself!")
}
if superview != primaryView.superview || superview != secondaryView.superview {
fatalError("[NEON] Can't align view relative to another view in a different superview!")
}
let superviewWidth : CGFloat = superview!.width()
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var width : CGFloat = 0.0
switch align {
case .ToTheRightMatchingTop:
xOrigin = primaryView.xMax() + padding
yOrigin = primaryView.y()
width = superviewWidth - primaryView.xMax() - (superviewWidth - secondaryView.x()) - (2 * padding)
case .ToTheRightMatchingBottom:
xOrigin = primaryView.xMax() + padding
yOrigin = primaryView.yMax() - height
width = superviewWidth - primaryView.xMax() - (superviewWidth - secondaryView.x()) - (2 * padding)
case .ToTheRightCentered:
xOrigin = primaryView.xMax() + padding
yOrigin = primaryView.yMid() - (height / 2.0)
width = superviewWidth - primaryView.xMax() - (superviewWidth - secondaryView.x()) - (2 * padding)
case .ToTheLeftMatchingTop:
xOrigin = secondaryView.xMax() + padding
yOrigin = primaryView.y()
width = superviewWidth - secondaryView.xMax() - (superviewWidth - primaryView.x()) - (2 * padding)
case .ToTheLeftMatchingBottom:
xOrigin = secondaryView.xMax() + padding
yOrigin = primaryView.yMax() - height
width = superviewWidth - secondaryView.xMax() - (superviewWidth - primaryView.x()) - (2 * padding)
case .ToTheLeftCentered:
xOrigin = secondaryView.xMax() + padding
yOrigin = primaryView.yMid() - (height / 2.0)
width = superviewWidth - secondaryView.xMax() - (superviewWidth - primaryView.x()) - (2 * padding)
case .UnderMatchingLeft, .UnderMatchingRight, .UnderCentered, .AboveMatchingLeft, .AboveMatchingRight, .AboveCentered:
fatalError("[NEON] Invalid Align specified for alignBetweenHorizonal().")
}
if width < 0.0 {
width = 0.0
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
/// Align a view between two sibling views vertically, automatically expanding the height to extend the full
/// vertical span between the `primaryView` and the `secondaryView`, with equal padding above and below.
///
/// - parameters:
/// - align: The `Align` type used to specify where and how this view is aligned with the primary view.
///
/// - primaryView: The primary sibling view this view will be aligned relative to.
///
/// - secondaryView: The secondary sibling view this view will be automatically sized to fill the space between.
///
/// - padding: The horizontal padding to be applied between this view and both sibling views.
///
/// - width: The width of the view.
///
func alignBetweenVertical(align align: Align, primaryView: UIView, secondaryView: UIView, padding: CGFloat, width: CGFloat) {
if superview == nil {
print("[NEON] Warning: Can't align view without superview!")
return
}
if self == primaryView || self == secondaryView {
fatalError("[NEON] Can't align view relative to itself!")
}
if superview != primaryView.superview || superview != secondaryView.superview {
fatalError("[NEON] Can't align view relative to another view in a different superview!")
}
let superviewHeight : CGFloat = superview!.height()
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var height : CGFloat = 0.0
switch align {
case .UnderMatchingLeft:
xOrigin = primaryView.x()
yOrigin = primaryView.yMax() + padding
height = superviewHeight - primaryView.yMax() - (superviewHeight - secondaryView.y()) - (2 * padding)
case .UnderMatchingRight:
xOrigin = primaryView.xMax() - width
yOrigin = primaryView.yMax() + padding
height = superviewHeight - primaryView.yMax() - (superviewHeight - secondaryView.y()) - (2 * padding)
case .UnderCentered:
xOrigin = primaryView.xMid() - (width / 2.0)
yOrigin = primaryView.yMax() + padding
height = superviewHeight - primaryView.yMax() - (superviewHeight - secondaryView.y()) - (2 * padding)
case .AboveMatchingLeft:
xOrigin = primaryView.x()
yOrigin = secondaryView.yMax() + padding
height = superviewHeight - secondaryView.yMax() - (superviewHeight - primaryView.y()) - (2 * padding)
case .AboveMatchingRight:
xOrigin = primaryView.xMax() - width
yOrigin = secondaryView.yMax() + padding
height = superviewHeight - secondaryView.yMax() - (superviewHeight - primaryView.y()) - (2 * padding)
case .AboveCentered:
xOrigin = primaryView.xMid() - (width / 2.0)
yOrigin = secondaryView.yMax() + padding
height = superviewHeight - secondaryView.yMax() - (superviewHeight - primaryView.y()) - (2 * padding)
case .ToTheLeftMatchingTop, .ToTheLeftMatchingBottom, .ToTheLeftCentered, .ToTheRightMatchingTop, .ToTheRightMatchingBottom, .ToTheRightCentered:
fatalError("[NEON] Invalid Align specified for alignBetweenVertical().")
}
if height < 0 {
height = 0
}
frame = CGRectMake(xOrigin, yOrigin, width, height)
}
// MARK: Grouping siblings
//
/// Tell a view to group an array of its subviews centered, specifying the padding between each subview,
/// as well as the size of each.
///
/// - parameters:
/// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically in the center.
///
/// - views: The array of views to grouped in the center. Depending on if the views are gouped horizontally
/// or vertically, they will be positioned in order from left-to-right and top-to-bottom, respectively.
///
/// - padding: The padding to be applied between the subviews.
///
/// - width: The width of each subview.
///
/// - height: The height of each subview.
///
func groupInCenter(group group: Group, views: [UIView], padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.")
return
}
if views.count == 0 {
print("[NEON] Warning: No subviews provided to groupInCenter().")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var xAdjust : CGFloat = 0.0
var yAdjust : CGFloat = 0.0
switch group {
case .Horizontal:
xOrigin = (self.width() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)) / 2.0
yOrigin = (self.height() / 2.0) - (height / 2.0)
xAdjust = width + padding
case .Vertical:
xOrigin = (self.width() / 2.0) - (width / 2.0)
yOrigin = (self.height() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)) / 2.0
yAdjust = height + padding
}
for view in views {
if view.superview != self {
fatalError("[NEON] Can't group view that is a subview of another view!")
}
view.frame = CGRectMake(xOrigin, yOrigin, width, height)
xOrigin += xAdjust
yOrigin += yAdjust
}
}
/// Tell a view to group an array of its subviews in one of its corners, specifying the padding between each subview,
/// as well as the size of each.
///
/// - parameters:
/// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically in the corner.
///
/// - views: The array of views to grouped in the specified corner. Depending on if the views are gouped horizontally
/// or vertically, they will be positioned in order from left-to-right and top-to-bottom, respectively.
///
/// - inCorner: The specified corner the views will be grouped in.
///
/// - padding: The padding to be applied between the subviews and their superview.
///
/// - width: The width of each subview.
///
/// - height: The height of each subview.
///
func groupInCorner(group group: Group, views: [UIView], inCorner corner: Corner, padding: CGFloat, width: CGFloat, height: CGFloat) {
switch group {
case .Horizontal:
groupInCornerHorizontal(views, inCorner: corner, padding: padding, width: width, height: height)
case .Vertical:
groupInCornerVertical(views, inCorner: corner, padding: padding, width: width, height: height)
}
}
/// Tell a view to group an array of its subviews against one of its edges, specifying the padding between each subview
/// and their superview, as well as the size of each.
///
/// - parameters:
/// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically against the specified
/// edge.
///
/// - views: The array of views to grouped against the spcified edge. Depending on if the views are gouped horizontally
/// or vertically, they will be positioned in-order from left-to-right and top-to-bottom, respectively.
///
/// - againstEdge: The specified edge the views will be grouped against.
///
/// - padding: The padding to be applied between each of the subviews and their superview.
///
/// - width: The width of each subview.
///
/// - height: The height of each subview.
///
func groupAgainstEdge(group group: Group, views: [UIView], againstEdge edge: Edge, padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.")
return
}
if views.count == 0 {
print("[NEON] Warning: No subviews provided to groupAgainstEdge().")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var xAdjust : CGFloat = 0.0
var yAdjust : CGFloat = 0.0
switch edge {
case .Top:
if group == .Horizontal {
xOrigin = (self.width() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)) / 2.0
xAdjust = width + padding
} else {
xOrigin = (self.width() / 2.0) - (width / 2.0)
yAdjust = height + padding
}
yOrigin = padding
case .Left:
if group == .Horizontal {
yOrigin = (self.height() / 2.0) - (height / 2.0)
xAdjust = width + padding
} else {
yOrigin = (self.height() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)) / 2.0
yAdjust = height + padding
}
xOrigin = padding
case .Bottom:
if group == .Horizontal {
xOrigin = (self.width() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)) / 2.0
yOrigin = self.height() - height - padding
xAdjust = width + padding
} else {
xOrigin = (self.width() / 2.0) - (width / 2.0)
yOrigin = self.height() - (CGFloat(views.count) * height) - (CGFloat(views.count) * padding)
yAdjust = height + padding
}
case .Right:
if group == .Horizontal {
xOrigin = self.width() - (CGFloat(views.count) * width) - (CGFloat(views.count) * padding)
yOrigin = (self.height() / 2.0) - (height / 2.0)
xAdjust = width + padding
} else {
xOrigin = self.width() - width - padding
yOrigin = (self.height() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)) / 2.0
yAdjust = height + padding
}
}
for view in views {
if view.superview != self {
fatalError("[NEON] Can't group view that is a subview of another view!")
}
view.frame = CGRectMake(xOrigin, yOrigin, width, height)
xOrigin += xAdjust
yOrigin += yAdjust
}
}
/// Tell a view to group an array of its subviews relative to another of that view's subview, specifying the padding between
/// each.
///
/// - parameters:
/// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically against the specified
/// sibling.
///
/// - andAlign: the `Align` type specifying how the views will be aligned relative to the sibling.
///
/// - views: The array of views to grouped against the sibling. Depending on if the views are gouped horizontally
/// or vertically, they will be positioned in-order from left-to-right and top-to-bottom, respectively.
///
/// - relativeTo: The sibling view that the views will be aligned relative to.
///
/// - padding: The padding to be applied between each of the subviews and the sibling.
///
/// - width: The width of each subview.
///
/// - height: The height of each subview.
///
func groupAndAlign(group group: Group, andAlign align: Align, views: [UIView], relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) {
switch group {
case .Horizontal:
groupAndAlignHorizontal(align, views: views, relativeTo: sibling, padding: padding, width: width, height: height)
case .Vertical:
groupAndAlignVertical(align, views: views, relativeTo: sibling, padding: padding, width: width, height: height)
}
}
/// Tell a view to group an array of its subviews filling the width and height of the superview, specifying the padding between
/// each subview and the superview.
///
/// - parameters:
/// - group: The `Group` type specifying if the subviews will be laid out horizontally or vertically.
///
/// - views: The array of views to be grouped against the sibling. Depending on if the views are grouped horizontally
/// or vertically, they will be positions in-order from left-to-right and top-to-bottom, respectively.
///
/// - padding: The padding to be applied between each of the subviews and the sibling.
///
func groupAndFill(group group: Group, views: [UIView], padding: CGFloat) {
if superview == nil {
print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.")
return
}
if views.count == 0 {
print("[NEON] Warning: No subviews provided to groupAgainstEdge().")
return
}
var xOrigin : CGFloat = padding
var yOrigin : CGFloat = padding
var width : CGFloat = 0.0
var height : CGFloat = 0.0
var xAdjust : CGFloat = 0.0
var yAdjust : CGFloat = 0.0
switch group {
case .Horizontal:
width = (self.width() - (CGFloat(views.count + 1) * padding)) / CGFloat(views.count)
height = self.height() - (2 * padding)
xAdjust = width + padding
case .Vertical:
width = self.width() - (2 * padding)
height = (self.height() - (CGFloat(views.count + 1) * padding)) / CGFloat(views.count)
yAdjust = height + padding
}
for view in views {
if view.superview != self {
fatalError("[NEON] Can't group view that is a subview of another view!")
}
view.frame = CGRectMake(xOrigin, yOrigin, width, height)
xOrigin += xAdjust
yOrigin += yAdjust
}
}
// MARK: Private utils
//
private func groupInCornerHorizontal(views: [UIView], inCorner corner: Corner, padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.")
return
}
if views.count == 0 {
print("[NEON] Warning: No subviews provided to groupInCorner().")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
let xAdjust : CGFloat = width + padding
switch corner {
case .TopLeft:
xOrigin = padding
yOrigin = padding
case .TopRight:
xOrigin = self.width() - ((CGFloat(views.count) * width) + (CGFloat(views.count) * padding))
yOrigin = padding
case .BottomLeft:
xOrigin = padding
yOrigin = self.height() - height - padding
case .BottomRight:
xOrigin = self.width() - ((CGFloat(views.count) * width) + (CGFloat(views.count) * padding))
yOrigin = self.height() - height - padding
}
for view in views {
if view.superview != self {
fatalError("[NEON] Can't group view that is a subview of another view!")
}
view.frame = CGRectMake(xOrigin, yOrigin, width, height)
xOrigin += xAdjust
}
}
private func groupInCornerVertical(views: [UIView], inCorner corner: Corner, padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.")
return
}
if views.count == 0 {
print("[NEON] Warning: No subviews provided to groupInCorner().")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
let yAdjust : CGFloat = height + padding
switch corner {
case .TopLeft:
xOrigin = padding
yOrigin = padding
case .TopRight:
xOrigin = self.width() - width - padding
yOrigin = padding
case .BottomLeft:
xOrigin = padding
yOrigin = self.height() - ((CGFloat(views.count) * height) + (CGFloat(views.count) * padding))
case .BottomRight:
xOrigin = self.width() - width - padding
yOrigin = self.height() - ((CGFloat(views.count) * height) + (CGFloat(views.count) * padding))
}
for view in views {
if view.superview != self {
fatalError("[NEON] Can't group view that is a subview of another view!")
}
view.frame = CGRectMake(xOrigin, yOrigin, width, height)
yOrigin += yAdjust
}
}
private func groupAndAlignHorizontal(align: Align, views: [UIView], relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.")
return
}
if views.count == 0 {
print("[NEON] Warning: No subviews provided to groupAgainstEdge().")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var xAdjust : CGFloat = width + padding
switch align {
case .ToTheRightMatchingTop:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.y()
case .ToTheRightMatchingBottom:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMax() - height
case .ToTheRightCentered:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMid() - (height / 2.0)
case .ToTheLeftMatchingTop:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.y()
xAdjust = -xAdjust
case .ToTheLeftMatchingBottom:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.yMax() - height
xAdjust = -xAdjust
case .ToTheLeftCentered:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.yMid() - (height / 2.0)
xAdjust = -xAdjust
case .UnderMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.yMax() + padding
case .UnderMatchingRight:
xOrigin = sibling.xMax() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)
yOrigin = sibling.yMax() + padding
case .UnderCentered:
xOrigin = sibling.xMid() - ((CGFloat(views.count) * width) + (CGFloat(views.count - 1) * padding)) / 2.0
yOrigin = sibling.yMax() + padding
case .AboveMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.y() - height - padding
case .AboveMatchingRight:
xOrigin = sibling.xMax() - (CGFloat(views.count) * width) - (CGFloat(views.count - 1) * padding)
yOrigin = sibling.y() - height - padding
case .AboveCentered:
xOrigin = sibling.xMid() - ((CGFloat(views.count) * width) + (CGFloat(views.count - 1) * padding)) / 2.0
yOrigin = sibling.y() - height - padding
}
for view in views {
if view.superview != self {
fatalError("[NEON] Can't group view that is a subview of another view!")
}
view.frame = CGRectMake(xOrigin, yOrigin, width, height)
xOrigin += xAdjust
}
}
private func groupAndAlignVertical(align: Align, views: [UIView], relativeTo sibling: UIView, padding: CGFloat, width: CGFloat, height: CGFloat) {
if superview == nil {
print("[NEON] Warning: Attempted to group subviews but view doesn't have a superview of its own.")
return
}
if views.count == 0 {
print("[NEON] Warning: No subviews provided to groupAgainstEdge().")
return
}
var xOrigin : CGFloat = 0.0
var yOrigin : CGFloat = 0.0
var yAdjust : CGFloat = height + padding
switch align {
case .ToTheRightMatchingTop:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.y()
case .ToTheRightMatchingBottom:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMax() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)
case .ToTheRightCentered:
xOrigin = sibling.xMax() + padding
yOrigin = sibling.yMid() - ((CGFloat(views.count) * height) + CGFloat(views.count - 1) * padding) / 2.0
case .ToTheLeftMatchingTop:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.y()
case .ToTheLeftMatchingBottom:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.yMax() - (CGFloat(views.count) * height) - (CGFloat(views.count - 1) * padding)
case .ToTheLeftCentered:
xOrigin = sibling.x() - width - padding
yOrigin = sibling.yMid() - ((CGFloat(views.count) * height) + CGFloat(views.count - 1) * padding) / 2.0
case .UnderMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.yMax() + padding
case .UnderMatchingRight:
xOrigin = sibling.xMax() - width
yOrigin = sibling.yMax() + padding
case .UnderCentered:
xOrigin = sibling.xMid() - (width / 2.0)
yOrigin = sibling.yMax() + padding
case .AboveMatchingLeft:
xOrigin = sibling.x()
yOrigin = sibling.y() - height - padding
yAdjust = -yAdjust
case .AboveMatchingRight:
xOrigin = sibling.xMax() - width
yOrigin = sibling.y() - height - padding
yAdjust = -yAdjust
case .AboveCentered:
xOrigin = sibling.xMid() - (width / 2.0)
yOrigin = sibling.y() - height - padding
yAdjust = -yAdjust
}
for view in views {
if view.superview != self {
fatalError("[NEON] Can't group view that is a subview of another view!")
}
view.frame = CGRectMake(xOrigin, yOrigin, width, height)
yOrigin += yAdjust
}
}
} | mit | ce79fd353008e596de4baecc5ab9218e | 35.430149 | 163 | 0.577187 | 4.576735 | false | false | false | false |
informmegp2/inform-me | InformME/FavoritelistViewController.swift | 1 | 8008 | //
// FavoritelistViewController.swift
// InformME
//
// Created by Amal Ibrahim on 2/9/16.
// Copyright © 2016 King Saud University. All rights reserved.
//
import Foundation
import UIKit
class FavoritelistViewController: CenterViewController,UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var menuButton: UIBarButtonItem!
var contentList = [Content]()
var uid : Int = NSUserDefaults.standardUserDefaults().integerForKey("id");
@IBOutlet var tableView: UITableView!
@IBAction func out(sender: AnyObject) {
print(" iam in 1")
var flag: Bool
flag = false
let current: Authentication = Authentication();
current.logout(){
(login:Bool) in
dispatch_async(dispatch_get_main_queue()) {
flag = login
if(flag) {
self.performSegueWithIdentifier("backtologin", sender: self)
print("I am happy",login,flag) }
}
print("I am Here") }
} //end out */ backtologin
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// loadFavorite ()
}
override func viewDidLoad() {
super.viewDidLoad()
if( Reachability.isConnectedToNetwork()){
loadFavorite () {
() in
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
// self.tableView.reloadData()
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "موافق", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})))
self.presentViewController(alert, animated: true, completion: nil)
}//end fun display alert
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contentList.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("contentCell", forIndexPath: indexPath) as! ContentTableCellViewController
cell.Title.text = contentList[indexPath.row].Title
cell.tag = contentList[indexPath.row].contentId!
cell.ViewContentButton.tag = contentList[indexPath.row].contentId!
cell.SaveButton.tag = indexPath.row
print("HERE IN CELL")
return cell
}
@IBAction func save(sender: UIButton) {
if(Reachability.isConnectedToNetwork()){
let imageFull = UIImage(named: "starF.png") as UIImage!
let imageEmpty = UIImage(named: "star.png") as UIImage!
if (sender.currentImage == imageFull)
{//content saved -> user wants to delete save
sender.setImage(imageEmpty, forState: .Normal)
Content().unsaveContent(uid, cid: contentList[sender.tag].contentId!)
}
else
{//content is not saved -> user wants to save
sender.setImage(imageFull, forState: .Normal)
let image = UIImage(named: "starF.png") as UIImage!
sender.setImage(image, forState: .Normal)
Content().saveContent(uid, cid: contentList[sender.tag].contentId!)
}
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}
override func prepareForSegue (segue: UIStoryboardSegue, sender: AnyObject?)
{ print("in segue")
if (segue.identifier == "ShowView")
{
let upcoming: ContentForAttendeeViewController = segue.destinationViewController as! ContentForAttendeeViewController
let indexPath = self.tableView.indexPathForSelectedRow!
let cid = contentList[indexPath.row].contentId
let imageFull = UIImage(named: "starF.png") as UIImage!
// let imageEmpty = UIImage(named: "star.png") as UIImage!
upcoming.cid = cid!
let content = Content()
if(Reachability.isConnectedToNetwork()){
content.ViewContent(cid!, UserID: uid){
(content:Content) in
dispatch_async(dispatch_get_main_queue()) {
upcoming.content = content
print(content)
// self.commentsTable.reloadData()
upcoming.abstract.text = content.Abstract
upcoming.pdfURL = content.Pdf
if(upcoming.pdfURL == "No PDF"){
upcoming.pdf.enabled = false
upcoming.pdf.setTitle("No PDF", forState: UIControlState.Disabled)
}
upcoming.vidURL = content.Video
if(upcoming.vidURL == "No Video"){
upcoming.video.enabled = false
upcoming.video.setTitle("No Video", forState: UIControlState.Disabled)
}
upcoming.images = content.Images
print(content.like)
print(content.dislike)
if(upcoming.content.like==1){
upcoming.likeButton.setImage(UIImage(named: "like.png"), forState: UIControlState.Normal)
}
else if (upcoming.content.dislike==1){
upcoming.dislikeButton.setImage(UIImage(named: "dislike.png"), forState: UIControlState.Normal)
}
upcoming.save.setImage(imageFull, forState: .Normal)
}
} //end call
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}}
func loadFavorite (completion: () -> Void)
{
//Col::(ContentID, Title, Abstract, Sharecounter, Label, EventID)
let request = NSMutableURLRequest(URL: NSURL(string: "http://bemyeyes.co/API/content/getFavourite.php")!)
request.HTTPMethod = "POST";
let postString = "uid=\(uid)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
print("HERE in task");
if error != nil {
print("error=\(error)")
return
}
else {
do {
if let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [AnyObject]{
print(jsonResults)
for item in jsonResults {
self.contentList.append(Content(json: item as! [String : AnyObject]))
}
}
}
catch {
// failure
print("Fetch failed: \((error as NSError).localizedDescription)")
}
}
completion()
}
task.resume()
}
} | mit | c67d7dd90292854c0bd93498fc82c88d | 31.93361 | 137 | 0.525328 | 5.351315 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/UnbufferedTokenStream.swift | 1 | 9414 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
public class UnbufferedTokenStream<T>: TokenStream {
internal var tokenSource: TokenSource
/**
* A moving window buffer of the data being scanned. While there's a marker,
* we keep adding to buffer. Otherwise, {@link #consume consume()} resets so
* we start filling at index 0 again.
*/
internal var tokens: [Token]
/**
* The number of tokens currently in {@link #tokens tokens}.
*
* <p>This is not the buffer capacity, that's {@code tokens.length}.</p>
*/
internal var n: Int
/**
* 0..n-1 index into {@link #tokens tokens} of next token.
*
* <p>The {@code LT(1)} token is {@code tokens[p]}. If {@code p == n}, we are
* out of buffered tokens.</p>
*/
internal var p: Int = 0
/**
* Count up with {@link #mark mark()} and down with
* {@link #release release()}. When we {@code release()} the last mark,
* {@code numMarkers} reaches 0 and we reset the buffer. Copy
* {@code tokens[p]..tokens[n-1]} to {@code tokens[0]..tokens[(n-1)-p]}.
*/
internal var numMarkers: Int = 0
/**
* This is the {@code LT(-1)} token for the current position.
*/
internal var lastToken: Token!
/**
* When {@code numMarkers > 0}, this is the {@code LT(-1)} token for the
* first token in {@link #tokens}. Otherwise, this is {@code null}.
*/
internal var lastTokenBufferStart: Token!
/**
* Absolute token index. It's the index of the token about to be read via
* {@code LT(1)}. Goes from 0 to the number of tokens in the entire stream,
* although the stream size is unknown before the end is reached.
*
* <p>This value is used to set the token indexes if the stream provides tokens
* that implement {@link org.antlr.v4.runtime.WritableToken}.</p>
*/
internal var currentTokenIndex: Int = 0
public convenience init(_ tokenSource: TokenSource) throws {
try self.init(tokenSource, 256)
}
//TODO: bufferSize don't be use
public init(_ tokenSource: TokenSource, _ bufferSize: Int) throws {
self.tokenSource = tokenSource
//tokens = [Token](count: bufferSize, repeatedValue: Token) ;
tokens = [Token]()
n = 0
try fill(1) // prime the pump
}
public func get(_ i: Int) throws -> Token {
// get absolute index
let bufferStartIndex: Int = getBufferStartIndex()
if i < bufferStartIndex || i >= bufferStartIndex + n {
throw ANTLRError.indexOutOfBounds(msg: "get(\(i)) outside buffer: \(bufferStartIndex)..\(bufferStartIndex + n)")
}
return tokens[i - bufferStartIndex]
}
public func LT(_ i: Int) throws -> Token? {
if i == -1 {
return lastToken
}
try sync(i)
let index: Int = p + i - 1
if index < 0 {
throw ANTLRError.indexOutOfBounds(msg: "LT(\(i) gives negative index")
}
if index >= n {
//Token.EOF
assert(n > 0 && tokens[n - 1].getType() == CommonToken.EOF, "Expected: n>0&&tokens[n-1].getType()==Token.EOF")
return tokens[n - 1]
}
return tokens[index]
}
public func LA(_ i: Int) throws -> Int {
return try LT(i)!.getType()
}
public func getTokenSource() -> TokenSource {
return tokenSource
}
public func getText() -> String {
return ""
}
public func getText(_ ctx: RuleContext) throws -> String {
return try getText(ctx.getSourceInterval())
}
public func getText(_ start: Token?, _ stop: Token?) throws -> String {
return try getText(Interval.of(start!.getTokenIndex(), stop!.getTokenIndex()))
}
public func consume() throws {
//Token.EOF
if try LA(1) == CommonToken.EOF {
throw ANTLRError.illegalState(msg: "cannot consume EOF")
}
// buf always has at least tokens[p==0] in this method due to ctor
lastToken = tokens[p] // track last token for LT(-1)
// if we're at last token and no markers, opportunity to flush buffer
if p == n - 1 && numMarkers == 0 {
n = 0
p = -1 // p++ will leave this at 0
lastTokenBufferStart = lastToken
}
p += 1
currentTokenIndex += 1
try sync(1)
}
/** Make sure we have 'need' elements from current position {@link #p p}. Last valid
* {@code p} index is {@code tokens.length-1}. {@code p+need-1} is the tokens index 'need' elements
* ahead. If we need 1 element, {@code (p+1-1)==p} must be less than {@code tokens.length}.
*/
internal func sync(_ want: Int) throws {
let need: Int = (p + want - 1) - n + 1 // how many more elements we need?
if need > 0 {
try fill(need)
}
}
/**
* Add {@code n} elements to the buffer. Returns the number of tokens
* actually added to the buffer. If the return value is less than {@code n},
* then EOF was reached before {@code n} tokens could be added.
*/
@discardableResult
internal func fill(_ n: Int) throws -> Int {
for i in 0..<n {
if self.n > 0 && tokens[self.n - 1].getType() == CommonToken.EOF {
return i
}
let t: Token = try tokenSource.nextToken()
add(t)
}
return n
}
internal func add(_ t: Token) {
if n >= tokens.count {
//TODO: array count buffer size
//tokens = Arrays.copyOf(tokens, tokens.length * 2);
}
if t is WritableToken {
(t as! WritableToken).setTokenIndex(getBufferStartIndex() + n)
}
tokens[n] = t
n += 1
}
/**
* Return a marker that we can release later.
*
* <p>The specific marker value used for this class allows for some level of
* protection against misuse where {@code seek()} is called on a mark or
* {@code release()} is called in the wrong order.</p>
*/
public func mark() -> Int {
if numMarkers == 0 {
lastTokenBufferStart = lastToken
}
let mark: Int = -numMarkers - 1
numMarkers += 1
return mark
}
public func release(_ marker: Int) throws {
let expectedMark: Int = -numMarkers
if marker != expectedMark {
throw ANTLRError.illegalState(msg: "release() called with an invalid marker.")
}
numMarkers -= 1
if numMarkers == 0 {
// can we release buffer?
if p > 0 {
// Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs
// p is last valid token; move nothing if p==n as we have no valid char
tokens = Array(tokens[p ... n - 1])
//System.arraycopy(tokens, p, tokens, 0, n - p); // shift n-p tokens from p to 0
n = n - p
p = 0
}
lastTokenBufferStart = lastToken
}
}
public func index() -> Int {
return currentTokenIndex
}
public func seek(_ index: Int) throws {
var index = index
// seek to absolute index
if index == currentTokenIndex {
return
}
if index > currentTokenIndex {
try sync(index - currentTokenIndex)
index = min(index, getBufferStartIndex() + n - 1)
}
let bufferStartIndex: Int = getBufferStartIndex()
let i: Int = index - bufferStartIndex
if i < 0 {
throw ANTLRError.illegalState(msg: "cannot seek to negative index \(index)")
} else {
if i >= n {
throw ANTLRError.unsupportedOperation(msg: "seek to index outside buffer: \(index) not in \(bufferStartIndex)..\(bufferStartIndex + n)")
}
}
p = i
currentTokenIndex = index
if p == 0 {
lastToken = lastTokenBufferStart
} else {
lastToken = tokens[p - 1]
}
}
public func size() -> Int {
RuntimeException("Unbuffered stream cannot know its size")
fatalError()
}
public func getSourceName() -> String {
return tokenSource.getSourceName()
}
public func getText(_ interval: Interval) throws -> String {
let bufferStartIndex: Int = getBufferStartIndex()
let bufferStopIndex: Int = bufferStartIndex + tokens.count - 1
let start: Int = interval.a
let stop: Int = interval.b
if start < bufferStartIndex || stop > bufferStopIndex {
throw ANTLRError.unsupportedOperation(msg: "interval \(interval) not in token buffer window: \(bufferStartIndex)..bufferStopIndex)")
}
let a: Int = start - bufferStartIndex
let b: Int = stop - bufferStartIndex
let buf: StringBuilder = StringBuilder()
for i in a...b {
let t: Token = tokens[i]
buf.append(t.getText()!)
}
return buf.toString()
}
internal final func getBufferStartIndex() -> Int {
return currentTokenIndex - p
}
}
| mit | 56f21695371c0296589cfe584b84af23 | 28.791139 | 152 | 0.562566 | 4.246279 | false | false | false | false |
parkera/swift | stdlib/public/Concurrency/SourceCompatibilityShims.swift | 1 | 10883 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file provides source compatibility shims to help migrate code
// using earlier versions of the concurrency library to the latest syntax.
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
@available(*, deprecated, message: "Task.Priority has been removed; use TaskPriority")
public typealias Priority = TaskPriority
@available(*, deprecated, message: "Task.Handle has been removed; use Task")
public typealias Handle = _Concurrency.Task
@available(*, deprecated, message: "Task.CancellationError has been removed; use CancellationError")
@_alwaysEmitIntoClient
public static func CancellationError() -> _Concurrency.CancellationError {
return _Concurrency.CancellationError()
}
@available(*, deprecated, renamed: "yield()")
@_alwaysEmitIntoClient
public static func suspend() async {
await yield()
}
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority {
@available(*, deprecated, message: "unspecified priority will be removed; use nil")
@_alwaysEmitIntoClient
public static var unspecified: TaskPriority {
.init(rawValue: 0x00)
}
@available(*, deprecated, message: "userInteractive priority will be removed")
@_alwaysEmitIntoClient
public static var userInteractive: TaskPriority {
.init(rawValue: 0x21)
}
}
@available(SwiftStdlib 5.5, *)
@_alwaysEmitIntoClient
public func withTaskCancellationHandler<T>(
handler: @Sendable () -> Void,
operation: () async throws -> T
) async rethrows -> T {
try await withTaskCancellationHandler(operation: operation, onCancel: handler)
}
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
@available(*, deprecated, message: "`Task.withCancellationHandler` has been replaced by `withTaskCancellationHandler` and will be removed shortly.")
@_alwaysEmitIntoClient
public static func withCancellationHandler<T>(
handler: @Sendable () -> Void,
operation: () async throws -> T
) async rethrows -> T {
try await withTaskCancellationHandler(handler: handler, operation: operation)
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Error {
@discardableResult
@_alwaysEmitIntoClient
@available(*, deprecated, message: "`Task.runDetached` was replaced by `Task.detached` and will be removed shortly.")
public static func runDetached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> Success
) -> Task<Success, Failure> {
detached(priority: priority, operation: operation)
}
}
@discardableResult
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "`detach` was replaced by `Task.detached` and will be removed shortly.")
@_alwaysEmitIntoClient
public func detach<T>(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> T
) -> Task<T, Never> {
Task.detached(priority: priority, operation: operation)
}
@discardableResult
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "`detach` was replaced by `Task.detached` and will be removed shortly.")
@_alwaysEmitIntoClient
public func detach<T>(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> T
) -> Task<T, Error> {
Task.detached(priority: priority, operation: operation)
}
@discardableResult
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "`asyncDetached` was replaced by `Task.detached` and will be removed shortly.")
@_alwaysEmitIntoClient
public func asyncDetached<T>(
priority: TaskPriority? = nil,
@_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T
) -> Task<T, Never> {
return Task.detached(priority: priority, operation: operation)
}
@discardableResult
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "`asyncDetached` was replaced by `Task.detached` and will be removed shortly.")
@_alwaysEmitIntoClient
public func asyncDetached<T>(
priority: TaskPriority? = nil,
@_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T
) -> Task<T, Error> {
return Task.detached(priority: priority, operation: operation)
}
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "`async` was replaced by `Task.init` and will be removed shortly.")
@discardableResult
@_alwaysEmitIntoClient
public func async<T>(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T
) -> Task<T, Never> {
.init(priority: priority, operation: operation)
}
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "`async` was replaced by `Task.init` and will be removed shortly.")
@discardableResult
@_alwaysEmitIntoClient
public func async<T>(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T
) -> Task<T, Error> {
.init(priority: priority, operation: operation)
}
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
@available(*, deprecated, message: "`Task.Group` was replaced by `ThrowingTaskGroup` and `TaskGroup` and will be removed shortly.")
public typealias Group<TaskResult> = ThrowingTaskGroup<TaskResult, Error>
@available(*, deprecated, message: "`Task.withGroup` was replaced by `withThrowingTaskGroup` and `withTaskGroup` and will be removed shortly.")
@_alwaysEmitIntoClient
public static func withGroup<TaskResult, BodyResult>(
resultType: TaskResult.Type,
returning returnType: BodyResult.Type = BodyResult.self,
body: (inout Task.Group<TaskResult>) async throws -> BodyResult
) async rethrows -> BodyResult {
try await withThrowingTaskGroup(of: resultType) { group in
try await body(&group)
}
}
}
@available(SwiftStdlib 5.5, *)
extension Task {
@available(*, deprecated, message: "get() has been replaced by .value")
@_alwaysEmitIntoClient
public func get() async throws -> Success {
return try await value
}
@available(*, deprecated, message: "getResult() has been replaced by .result")
@_alwaysEmitIntoClient
public func getResult() async -> Result<Success, Failure> {
return await result
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Never {
@available(*, deprecated, message: "get() has been replaced by .value")
@_alwaysEmitIntoClient
public func get() async -> Success {
return await value
}
}
@available(SwiftStdlib 5.5, *)
extension TaskGroup {
@available(*, deprecated, renamed: "addTask(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func add(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) async -> Bool {
return self.addTaskUnlessCancelled(priority: priority) {
await operation()
}
}
@available(*, deprecated, renamed: "addTask(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func spawn(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) {
addTask(priority: priority, operation: operation)
}
@available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func spawnUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) -> Bool {
addTaskUnlessCancelled(priority: priority, operation: operation)
}
@available(*, deprecated, renamed: "addTask(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func async(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) {
addTask(priority: priority, operation: operation)
}
@available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func asyncUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> ChildTaskResult
) -> Bool {
addTaskUnlessCancelled(priority: priority, operation: operation)
}
}
@available(SwiftStdlib 5.5, *)
extension ThrowingTaskGroup {
@available(*, deprecated, renamed: "addTask(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func add(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) async -> Bool {
return self.addTaskUnlessCancelled(priority: priority) {
try await operation()
}
}
@available(*, deprecated, renamed: "addTask(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func spawn(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) {
addTask(priority: priority, operation: operation)
}
@available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func spawnUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) -> Bool {
addTaskUnlessCancelled(priority: priority, operation: operation)
}
@available(*, deprecated, renamed: "addTask(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func async(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) {
addTask(priority: priority, operation: operation)
}
@available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")
@_alwaysEmitIntoClient
public mutating func asyncUnlessCancelled(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> ChildTaskResult
) -> Bool {
addTaskUnlessCancelled(priority: priority, operation: operation)
}
}
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, message: "please use UnsafeContination<..., Error>")
public typealias UnsafeThrowingContinuation<T> = UnsafeContinuation<T, Error>
@available(SwiftStdlib 5.5, *)
@available(*, deprecated, renamed: "UnownedJob")
public typealias PartialAsyncTask = UnownedJob
| apache-2.0 | 07ff42c766e09fc1185c3fbdab0570bd | 34.917492 | 150 | 0.71065 | 4.63896 | false | false | false | false |
WildDogTeam/lib-ios-streambase | StreamBaseExample/StreamBaseKit/UnionStream.swift | 1 | 4298 | //
// UnionStream.swift
// StreamBaseKit
//
// Created by IMacLi on 15/10/12.
// Copyright © 2015年 liwuyang. All rights reserved.
//
import Foundation
/**
Compose a stream out of other streams. Some example use cases are:
- Placeholders
- Multiple Wilddog queries in one view
It's ok for the keys to overlap, and for different substreams to have different
types. The sort order of the first stream is used by the union stream. (The sort orders
of the other streams is ignored.)
*/
public class UnionStream {
private let sources: [StreamBase] // TODO StreamBaseProtocol
private let delegates: [UnionStreamDelegate]
private var timer: NSTimer?
private var numStreamsFinished: Int? = 0
private var union = KeyedArray<BaseItem>()
private var error: NSError?
private var comparator: StreamBase.Comparator {
get {
return sources[0].comparator
}
}
/**
The delegate to notify as the merged stream is updated.
*/
weak public var delegate: StreamBaseDelegate?
/**
Construct a union stream from other streams. The sort order of the first substream
is used for the union.
:param: sources The substreams.
*/
public init(sources: StreamBase...) {
precondition(sources.count > 0)
self.sources = sources
delegates = sources.map{ UnionStreamDelegate(source: $0) }
for (s, d) in zip(sources, delegates) {
d.union = self
s.delegate = d
}
}
private func update() {
var newUnion = [BaseItem]()
var seen = Set<String>()
for source in sources {
for item in source {
if !seen.contains(item.key!) {
newUnion.append(item)
seen.insert(item.key!)
}
}
}
newUnion.sortInPlace(comparator)
StreamBase.applyBatch(union, batch: newUnion, delegate: delegate)
if numStreamsFinished == sources.count {
numStreamsFinished = nil
delegate?.streamDidFinishInitialLoad(error)
}
}
func needsUpdate() {
timer?.invalidate()
timer = NSTimer.schedule(delay: 0.1) { [weak self] timer in
self?.update()
}
}
func didFinishInitialLoad(error: NSError?) {
if let e = error where self.error == nil {
self.error = e
// Any additional errors are ignored.
}
numStreamsFinished = numStreamsFinished!+1
needsUpdate()
}
func changed(t: BaseItem) {
if let row = union.find(t.key!) {
delegate?.streamItemsChanged([NSIndexPath(forRow: row, inSection: 0)])
}
}
}
extension UnionStream : Indexable {
public typealias Index = Int
public var startIndex: Index {
return union.startIndex
}
public var endIndex: Index {
return union.startIndex
}
public subscript(i: Index) -> BaseItem {
return union[i]
}
}
extension UnionStream : CollectionType { }
extension UnionStream : StreamBaseProtocol {
public func find(key: String) -> BaseItem? {
if let row = union.find(key) {
return union[row]
}
return nil
}
public func findIndexPath(key: String) -> NSIndexPath? {
if let row = union.find(key) {
return NSIndexPath(forRow: row, inSection: 0)
}
return nil
}
}
private class UnionStreamDelegate: StreamBaseDelegate {
weak var source: StreamBase?
weak var union: UnionStream?
init(source: StreamBase) {
self.source = source
}
func streamWillChange() {
}
func streamDidChange() {
union?.needsUpdate()
}
func streamItemsAdded(paths: [NSIndexPath]) {
}
func streamItemsDeleted(paths: [NSIndexPath]) {
}
func streamItemsChanged(paths: [NSIndexPath]) {
for path in paths {
if let t = source?[path.row] {
union?.changed(t)
}
}
}
func streamDidFinishInitialLoad(error: NSError?) {
union?.didFinishInitialLoad(error)
}
}
| mit | d10c9afb05078bbd77892be7b8d66303 | 24.873494 | 94 | 0.581607 | 4.578891 | false | false | false | false |
abhayamrastogi/ChatSDKPodSpecs | rgconnectsdk/NetworkHandlers/ChatRoomNetworkHandler.swift | 1 | 3200 | //
// ChatRoomNetworkHandler.swift
// rgconnectsdk
//
// Created by Anurag Agnihotri on 19/07/16.
// Copyright © 2016 RoundGlass Partners. All rights reserved.
//
import Foundation
import ObjectMapper
class ChatRoomNetworkHandler {
/**
Method to fetch a list Of All Chat Rooms.
- parameter meteorClient: Meteor Client Object.
- parameter collectionName: Collection Name.
- parameter successCallback: Success Callback with list of Chat Rooms.
- parameter errorCallback: Error Callback with NSError.
*/
static func getChatRooms(meteorClient: MeteorClient,
successCallback: (chatRooms: [ChatRoom]) -> Void,
errorCallback: (error: NSError) -> Void) {
var chatRooms = [ChatRoom]()
let chatRoomSubscription = meteorClient.collections["rocketchat_subscription"] as? M13MutableOrderedDictionary
if let chatRoomSubscription = chatRoomSubscription {
for key in 0..<chatRoomSubscription.count {
chatRooms.append(Mapper<ChatRoom>().map(chatRoomSubscription[key])!)
}
successCallback(chatRooms: chatRooms)
} else {
let error = NSError(domain: "Chat Rooms Not Found.", code: 0, userInfo: nil)
errorCallback(error: error)
}
}
/**
Method to Create a Public Channel.
- parameter meteorClient: Meteor Client Object.
- parameter channelName: Name of the Channel to be created.
- parameter successCallback: Success response
- parameter errorCallback: Failure Response.
*/
static func createChannel(meteorClient: MeteorClient, channelName: String,
successCallback: (response: [NSObject : AnyObject]) -> Void,
errorCallback: (error: NSError) -> Void) {
meteorClient.callMethodName("createChannel", parameters: [channelName, []]) { (response, error) in
if error != nil {
errorCallback(error: error)
}
if response != nil {
successCallback(response: response)
}
}
}
/**
Method to create a Direct Message.
- parameter meteorClient: Meteor Client Object.
- parameter userName: Name of the User for Direct Message.
- parameter successCallback: Success Response.
- parameter errorCallback: Failure Response.
*/
static func createDirectMessage(meteorClient: MeteorClient, userName: String,
successCallback: ((response: [NSObject: AnyObject]) -> Void),
errorCallback: ((error: NSError) -> Void)) {
meteorClient.callMethodName("createDirectMessage", parameters: [userName, []]) { (response, error) in
if error != nil {
errorCallback(error: error)
}
if response != nil {
successCallback(response: response)
}
}
}
} | mit | b7d5af8d039998d03ccbcde411aaf6df | 33.782609 | 118 | 0.572366 | 5.422034 | false | false | false | false |
Bartlebys/Bartleby | Bartleby.xOS/core/Context.swift | 1 | 599 | //
// Context.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 22/10/2016.
//
//
import Foundation
public struct Context: Consignable {
// A developer set code to provide filtering
public var code: Int=Default.MAX_INT
// A descriptive string for developper to identify the calling context
public var caller: String=Default.NO_NAME
public var message: String=Default.NO_MESSAGE
public init(code: Int!, caller: String!) {
self.code=code
self.caller=caller
}
public init(context: String!) {
self.caller=context
}
}
| apache-2.0 | 015453b9b19c9af728ad002d458fcfac | 18.966667 | 74 | 0.66611 | 3.915033 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Picker/Controller/PhotoPreviewViewController+BottomView.swift | 1 | 10321 | //
// PhotoPreviewViewController+BottomView.swift
// HXPHPicker
//
// Created by Slience on 2021/8/6.
//
import UIKit
// MARK: PhotoPickerBottomViewDelegate
extension PhotoPreviewViewController: PhotoPickerBottomViewDelegate {
func bottomView(didEditButtonClick bottomView: PhotoPickerBottomView) {
let photoAsset = previewAssets[currentPreviewIndex]
openEditor(photoAsset)
}
func openEditor(_ photoAsset: PhotoAsset) {
guard let picker = pickerController else { return }
let shouldEditAsset = picker.shouldEditAsset(
photoAsset: photoAsset,
atIndex: currentPreviewIndex
)
if !shouldEditAsset {
return
}
#if HXPICKER_ENABLE_EDITOR && HXPICKER_ENABLE_PICKER
beforeNavDelegate = navigationController?.delegate
let pickerConfig = picker.config
if photoAsset.mediaType == .video && pickerConfig.editorOptions.isVideo {
let cell = getCell(
for: currentPreviewIndex
)
cell?.scrollContentView.stopVideo()
let videoEditorConfig: VideoEditorConfiguration
let isExceedsTheLimit = picker.videoDurationExceedsTheLimit(
photoAsset: photoAsset
)
if isExceedsTheLimit {
videoEditorConfig = pickerConfig.videoEditor.mutableCopy() as! VideoEditorConfiguration
videoEditorConfig.defaultState = .cropTime
videoEditorConfig.mustBeTailored = true
}else {
videoEditorConfig = pickerConfig.videoEditor
}
if !picker.shouldEditVideoAsset(
videoAsset: photoAsset,
editorConfig: videoEditorConfig,
atIndex: currentPreviewIndex
) {
return
}
if let shouldEdit = delegate?.previewViewController(
self,
shouldEditVideoAsset: photoAsset,
editorConfig: videoEditorConfig
), !shouldEdit {
return
}
videoEditorConfig.languageType = pickerConfig.languageType
videoEditorConfig.appearanceStyle = pickerConfig.appearanceStyle
videoEditorConfig.indicatorType = pickerConfig.indicatorType
let videoEditorVC = VideoEditorViewController(
photoAsset: photoAsset,
editResult: photoAsset.videoEdit,
config: videoEditorConfig
)
videoEditorVC.coverImage = cell?.scrollContentView.imageView.image
videoEditorVC.delegate = self
if pickerConfig.editorCustomTransition {
navigationController?.delegate = videoEditorVC
}
navigationController?.pushViewController(
videoEditorVC,
animated: true
)
}else if pickerConfig.editorOptions.isPhoto {
let photoEditorConfig = pickerConfig.photoEditor
if !picker.shouldEditPhotoAsset(
photoAsset: photoAsset,
editorConfig: photoEditorConfig,
atIndex: currentPreviewIndex
) {
return
}
if let shouldEdit = delegate?.previewViewController(
self,
shouldEditPhotoAsset: photoAsset,
editorConfig: photoEditorConfig
), !shouldEdit {
return
}
photoEditorConfig.languageType = pickerConfig.languageType
photoEditorConfig.appearanceStyle = pickerConfig.appearanceStyle
photoEditorConfig.indicatorType = pickerConfig.indicatorType
let photoEditorVC = PhotoEditorViewController(
photoAsset: photoAsset,
editResult: photoAsset.photoEdit,
config: photoEditorConfig
)
photoEditorVC.delegate = self
if pickerConfig.editorCustomTransition {
navigationController?.delegate = photoEditorVC
}
navigationController?.pushViewController(
photoEditorVC,
animated: true
)
}
#endif
}
func bottomView(
didFinishButtonClick bottomView: PhotoPickerBottomView
) {
guard let pickerController = pickerController else {
return
}
if !pickerController.selectedAssetArray.isEmpty {
delegate?.previewViewController(didFinishButton: self)
pickerController.finishCallback()
return
}
if previewAssets.isEmpty {
ProgressHUD.showWarning(
addedTo: view,
text: "没有可选资源".localized,
animated: true,
delayHide: 1.5
)
return
}
let photoAsset = previewAssets[currentPreviewIndex]
#if HXPICKER_ENABLE_EDITOR
if photoAsset.mediaType == .video &&
pickerController.videoDurationExceedsTheLimit(photoAsset: photoAsset) &&
pickerController.config.editorOptions.isVideo {
if pickerController.canSelectAsset(
for: photoAsset,
showHUD: true
) {
openEditor(photoAsset)
}
return
}
#endif
func addAsset() {
if !isMultipleSelect {
if pickerController.canSelectAsset(
for: photoAsset,
showHUD: true
) {
if isExternalPickerPreview {
delegate?.previewViewController(
self,
didSelectBox: photoAsset,
isSelected: true,
updateCell: false
)
}
delegate?.previewViewController(didFinishButton: self)
pickerController.singleFinishCallback(
for: photoAsset
)
}
}else {
if videoLoadSingleCell {
if pickerController.canSelectAsset(
for: photoAsset,
showHUD: true
) {
if isExternalPickerPreview {
delegate?.previewViewController(
self,
didSelectBox: photoAsset,
isSelected: true,
updateCell: false
)
}
delegate?.previewViewController(didFinishButton: self)
pickerController.singleFinishCallback(
for: photoAsset
)
}
}else {
if pickerController.addedPhotoAsset(
photoAsset: photoAsset
) {
if isExternalPickerPreview {
delegate?.previewViewController(
self,
didSelectBox: photoAsset,
isSelected: true,
updateCell: false
)
}
delegate?.previewViewController(didFinishButton: self)
pickerController.finishCallback()
}
}
}
}
let inICloud = photoAsset.checkICloundStatus(
allowSyncPhoto: pickerController.config.allowSyncICloudWhenSelectPhoto
) { _, isSuccess in
if isSuccess {
addAsset()
}
}
if !inICloud {
addAsset()
}
}
func bottomView(
_ bottomView: PhotoPickerBottomView,
didOriginalButtonClick isOriginal: Bool
) {
delegate?.previewViewController(
self,
didOriginalButton: isOriginal
)
pickerController?.originalButtonCallback()
}
func bottomView(
_ bottomView: PhotoPickerBottomView,
didSelectedItemAt photoAsset: PhotoAsset
) {
if previewAssets.contains(photoAsset) {
let index = previewAssets.firstIndex(of: photoAsset) ?? 0
if index == currentPreviewIndex {
return
}
getCell(for: currentPreviewIndex)?.cancelRequest()
collectionView.scrollToItem(
at: IndexPath(item: index, section: 0),
at: .centeredHorizontally,
animated: false
)
setupRequestPreviewTimer()
}else {
bottomView.selectedView.scrollTo(photoAsset: nil)
}
}
func setupRequestPreviewTimer() {
requestPreviewTimer?.invalidate()
requestPreviewTimer = Timer(
timeInterval: 0.2,
target: self,
selector: #selector(delayRequestPreview),
userInfo: nil,
repeats: false
)
RunLoop.main.add(
requestPreviewTimer!,
forMode: RunLoop.Mode.common
)
}
@objc func delayRequestPreview() {
if let cell = getCell(for: currentPreviewIndex) {
cell.requestPreviewAsset()
requestPreviewTimer = nil
}else {
if previewAssets.isEmpty {
requestPreviewTimer = nil
return
}
setupRequestPreviewTimer()
}
}
public func setOriginal(_ isOriginal: Bool) {
bottomView.boxControl.isSelected = isOriginal
if !isOriginal {
// 取消
bottomView.cancelRequestAssetFileSize()
}else {
// 选中
bottomView.requestAssetBytes()
}
pickerController?.isOriginal = isOriginal
pickerController?.originalButtonCallback()
delegate?.previewViewController(
self,
didOriginalButton: isOriginal
)
}
}
| mit | 2e078970df3c1fd4422a304d3a3bac63 | 35.017483 | 103 | 0.52791 | 6.390199 | false | true | false | false |
tensorflow/swift-models | MiniGo/GameLib/Board.swift | 1 | 3645 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlow
/// Holds the current board stones.
///
/// This struct allows caller to arbitrarily mutate the board information but
/// does not handle validation check for placing new stone. `BoardState` is
/// designed for that.
struct Board: Hashable {
// Holds the stone `Color`s for each position.
private var stones: ShapedArray<Color?>
let size: Int
init(size: Int) {
self.stones = ShapedArray<Color?>(repeating: nil, shape: [size, size])
self.size = size
}
func color(at position: Position) -> Color? {
assert(0..<size ~= position.x && 0..<size ~= position.y)
return stones[position.x][position.y].scalars[0]
}
mutating func placeStone(at position: Position, withColor color: Color) {
assert(0..<size ~= position.x && 0..<size ~= position.y)
stones[position.x][position.y] = ShapedArraySlice(color)
}
mutating func removeStone(at position: Position) {
assert(0..<size ~= position.x && 0..<size ~= position.y)
stones[position.x][position.y] = ShapedArraySlice(nil)
}
}
extension Board: CustomStringConvertible {
var description: String {
var output = ""
// First, generates the head line, which looks like
//
// x/y 0 1 2 3 4 5 6 7 8
//
// for a 9x9 board.
output.append("\nx/y")
// For board size <10, all numbers in head line are single digit. So, we only need one empty
// space between them.
//
// x/y 0 1 2 3 4 5 6 7 8
//
// For board size >=11, we need to print a space between two-digit numbers. So, spaces between
// single-digit numbers are larger.
//
// x/y 0 1 2 3 4 5 6 7 8 9 10 11
for y in 0..<size {
if size >= 11 {
output.append(" ")
}
// As we cannot use Foundation, String(format:) method is not avaiable to use.
if y < 10 {
output.append(" \(y)")
} else {
output.append("\(y)")
}
}
output.append("\n")
// Similarly, we need two spaces between stones for size >= 11, but one space for small board.
let gapBetweenStones = size <= 10 ? " " : " "
for x in 0..<size {
// Prints row index.
if x < 10 {
output.append(" \(x)") // Two leading spaces.
} else {
output.append(" \(x)") // One leading space.
}
// Prints the color of stone at each position.
for y in 0..<size {
output.append(gapBetweenStones)
guard let color = self.color(at: Position(x: x, y: y)) else {
output.append(".") // Empty position.
continue
}
output.append(color == .black ? "X" : "O")
}
output.append("\n")
}
return output
}
}
| apache-2.0 | 114f632cdf7cea9fe1a5c7bb05b8db5d | 34.048077 | 102 | 0.560768 | 4.06808 | false | false | false | false |
mattwelborn/HSTracker | HSTracker/Statistics/StatsHelper.swift | 1 | 12644 | //
// StatsHelper.swift
// HSTracker
//
// Created by Matthew Welborn on 6/9/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
class StatsTableRow: NSObject { // Class instead of struct so we can use sortUsingDescriptors
// Used for display
var classIcon = ""
var opponentClassName = ""
var record = ""
var winRate = ""
var confidenceInterval = ""
// Used for sorting
var totalGames = 0
var winRateNumber = -1.0
var confidenceWindow = 1.0
}
class LadderTableRow: NSObject { // Class instead of struct so we can use sortUsingDescriptors
// Used for display
var rank = ""
var games = ""
var gamesCI = ""
var time = ""
var timeCI = ""
}
struct StatsDeckRecord {
var wins = 0
var losses = 0
var draws = 0
var total = 0
}
class StatsHelper {
static let statsUIConfidence: Double = 0.9 // Maybe this could become user settable
static let lg = LadderGrid()
static func getStatsUITableData(deck: Deck, mode: GameMode = .Ranked) -> [StatsTableRow] {
var tableData = [StatsTableRow]()
for againstClass in [.NEUTRAL] + Cards.classes {
let dataRow = StatsTableRow()
if againstClass == .NEUTRAL {
dataRow.classIcon = "AppIcon"
} else {
dataRow.classIcon = againstClass.rawValue.lowercaseString
}
dataRow.opponentClassName =
NSLocalizedString(againstClass.rawValue.lowercaseString,
comment: "").capitalizedString
let record = getDeckRecord(deck, againstClass: againstClass, mode: mode)
dataRow.record = getDeckRecordString(record)
dataRow.winRate = getDeckWinRateString(record)
dataRow.winRateNumber = getDeckWinRate(record)
dataRow.totalGames = record.total
dataRow.confidenceInterval = getDeckConfidenceString(record,
confidence: statsUIConfidence)
let interval = binomialProportionCondifenceInterval(record.wins,
losses: record.losses,
confidence: statsUIConfidence)
dataRow.confidenceWindow = interval.upper - interval.lower
tableData.append(dataRow)
}
return tableData
}
static func getLadderTableData(deck: Deck, rank: Int, stars: Int, streak: Bool)
-> [LadderTableRow] {
var tableData = [LadderTableRow]()
let record = getDeckRecord(deck, againstClass: .NEUTRAL, mode: .Ranked)
let tpg = getDeckTimePerGame(deck, againstClass: .NEUTRAL, mode: .Ranked)
let winRate = getDeckWinRate(record)
let totalStars = Ranks.starsAtRank[rank]! + stars
var bonus: Int = 0
if streak {
bonus = 2
}
for target_rank in [20, 15, 10, 5, 0] {
let dataRow = LadderTableRow()
if target_rank == 0 {
dataRow.rank = "Legend"
} else {
dataRow.rank = String(target_rank)
}
if rank <= target_rank || winRate == -1.0 {
dataRow.games = "--"
dataRow.gamesCI = "--"
dataRow.time = "--"
dataRow.timeCI = "--"
} else {
// Closures for repeated tasks
let getGames = {
(winp: Double) -> Double? in
return lg.getGamesToRank(target_rank,
stars: totalStars,
bonus: bonus,
winp: winp)
}
let formatGames = {
(games: Double) -> String in
if games > 1000 {
return ">1000"
} else {
return String(Int(round(games)))
}
}
let formatTime = {
(games: Double, timePerGame: Double) -> String in
let hours = games * timePerGame / 3600
if hours > 100 {
return ">100"
} else {
return String(format: "%.1f", hours)
}
}
// Means
if let g2r = getGames(winRate) {
dataRow.games = formatGames(g2r)
dataRow.time = formatTime(g2r, tpg)
} else {
dataRow.games = "Error"
dataRow.time = "Error"
}
//Confidence intervals
let interval = binomialProportionCondifenceInterval(record.wins,
losses: record.losses,
confidence: statsUIConfidence)
if let lg2r = getGames(interval.lower),
ug2r = getGames(interval.upper) {
dataRow.gamesCI = "\(formatGames(ug2r)) - \(formatGames(lg2r))"
dataRow.timeCI = "\(formatTime(ug2r, tpg)) - \(formatTime(lg2r, tpg))"
} else {
dataRow.gamesCI = "Error"
dataRow.timeCI = "Error"
}
}
tableData.append(dataRow)
}
return tableData
}
static func getDeckManagerRecordLabel(deck: Deck) -> String {
let record = getDeckRecord(deck)
let totalGames = record.total
if totalGames == 0 {
return "0 - 0"
}
return "\(record.wins) - \(record.losses) (\(getDeckWinRateString(record)))"
}
static func getDeckRecordString(record: StatsDeckRecord) -> String {
return "\(record.wins)-\(record.losses)"
}
static func getDeckWinRate(record: StatsDeckRecord) -> Double {
let totalGames = record.wins + record.losses
var winRate = -1.0
if totalGames > 0 {
winRate = Double(record.wins)/Double(totalGames)
}
return winRate
}
static func getDeckTimePerGame(deck: Deck, againstClass: CardClass = .NEUTRAL,
mode: GameMode = .Ranked) -> Double {
var stats = deck.statistics
if againstClass != .NEUTRAL {
stats = deck.statistics.filter({$0.opponentClass == againstClass})
}
var rankedStats: [Statistic]
if mode == .All {
rankedStats = stats
} else {
rankedStats = stats.filter({$0.playerMode == mode})
}
var time: Double = 0.0
for stat in rankedStats {
time += Double(stat.duration)
}
time /= Double(rankedStats.count)
return time
}
static func getDeckWinRateString(record: StatsDeckRecord) -> String {
var winRateString = "N/A"
let winRate = getDeckWinRate(record)
if winRate >= 0.0 {
let winPercent = Int(round(winRate * 100))
winRateString = String(winPercent) + "%"
}
return winRateString
}
static func getDeckRecord(deck: Deck, againstClass: CardClass = .NEUTRAL,
mode: GameMode = .Ranked)
-> StatsDeckRecord {
var stats = deck.statistics
if againstClass != .NEUTRAL {
stats = deck.statistics.filter({$0.opponentClass == againstClass})
}
var rankedStats: [Statistic]
if mode == .All {
rankedStats = stats
} else {
rankedStats = stats.filter({$0.playerMode == mode})
}
let wins = rankedStats.filter({$0.gameResult == .Win}).count
let losses = rankedStats.filter({$0.gameResult == .Loss}).count
let draws = rankedStats.filter({$0.gameResult == .Draw}).count
return StatsDeckRecord(wins: wins, losses: losses, draws: draws, total: wins+losses+draws)
}
static func getDeckConfidenceString(record: StatsDeckRecord,
confidence: Double = 0.9) -> String {
let interval = binomialProportionCondifenceInterval(record.wins,
losses: record.losses,
confidence: confidence)
let intLower = Int(round(interval.lower*100))
let intUpper = Int(round(interval.upper*100))
return String(format: "%3d%% - %3d%%", arguments: [intLower, intUpper])
}
static func guessRank(deck: Deck) -> Int {
let isStandard = deck.standardViable()
let decks = Decks.instance.decks()
.filter({$0.standardViable() == isStandard})
.filter({!$0.isArena})
var mostRecent: Statistic?
for deck_i in decks {
let datedRankedGames = deck_i.statistics
.filter({$0.playerMode == .Ranked})
.filter({$0.date != nil})
if let latest = datedRankedGames.maxElement({$0.date! < $1.date!}) {
if let mr = mostRecent {
if mr.date! < latest.date! {
mostRecent = latest
}
} else {
mostRecent = latest
}
}
}
if let mr = mostRecent {
return mr.playerRank
} else {
return 25
}
}
static func binomialProportionCondifenceInterval(wins: Int, losses: Int,
confidence: Double = 0.9)
-> (lower: Double, upper: Double, mean: Double) {
// Implements the Wilson interval
let alpha = 1.0 - confidence
assert(alpha >= 0.0)
assert(alpha <= 1.0)
let n = Double(wins + losses)
// bounds checking
if n < 1 {
return (0.0, 1.0, 0.5)
}
let quantile = 1 - 0.5 * alpha
let z = sqrt(2) * erfinv(2 * quantile - 1)
let p = Double(wins) / Double(n)
let center = p + z * z / (2 * n)
let spread = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n))
let prefactor = 1 / (1 + z * z / n)
var lower = prefactor * (center - spread)
var upper = prefactor * (center + spread)
let mean = prefactor * (center)
lower = max(lower, 0.0)
upper = min(upper, 1.0)
return (lower, upper, mean)
}
static func erfinv(y: Double) -> Double {
// swiftlint:disable line_length
// Taken from:
// http://stackoverflow.com/questions/36784763/is-there-an-inverse-error-function-available-in-swifts-foundation-import
// swiftlint:enable line_length
let center = 0.7
let a = [ 0.886226899, -1.645349621, 0.914624893, -0.140543331]
let b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]
let c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]
let d = [ 3.543889200, 1.637067800]
if abs(y) <= center {
let z = pow(y, 2)
let num = (((a[3] * z + a[2]) * z + a[1]) * z) + a[0]
let den = ((((b[3] * z + b[2]) * z + b[1]) * z + b[0]) * z + 1.0)
var x = y * num / den
x = x - (erf(x) - y) / (2.0 / sqrt(M_PI) * exp(-x * x))
x = x - (erf(x) - y) / (2.0 / sqrt(M_PI) * exp(-x * x))
return x
} else if abs(y) > center && abs(y) < 1.0 {
let z = pow(-log((1.0 - abs(y)) / 2), 0.5)
let num = ((c[3] * z + c[2]) * z + c[1]) * z + c[0]
let den = (d[1] * z + d[0]) * z + 1
// should use the sign function instead of pow(pow(y,2),0.5)
var x = y / pow(pow(y, 2), 0.5) * num / den
x = x - (erf(x) - y) / (2.0 / sqrt(M_PI) * exp(-x * x))
x = x - (erf(x) - y) / (2.0 / sqrt(M_PI) * exp(-x * x))
return x
} else if abs(y) == 1 {
return y * Double(Int.max)
} else {
return Double.NaN
}
}
}
| mit | 9b72f70f24ec94378d24455b6019f60a | 33.829201 | 127 | 0.48161 | 4.502493 | false | false | false | false |
nova-services/FreightScanner | scanner/CustomFunctions.swift | 1 | 1947 | //
// CustomFunctions.swift
// scanner
//
// Created by osvaldo lopez on 8/17/16.
// Copyright © 2016 osvaldo lopez. All rights reserved.
//
import UIKit
class alert: UIViewController {
}
//Cunstom http request
class httpRequest {
var http = ""
var method = ""
var pString = ""
func sendData(result : @escaping (AnyObject?) -> ()) {
let url = URL(string: http)
var request = URLRequest(url: url!)
request.httpMethod = method
let posString = pString
request.httpBody = posString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
DispatchQueue.main.async {
if let urcontent = data {
do {
let json = try JSONSerialization.jsonObject(with: urcontent, options: .mutableContainers)
result(json as? AnyObject)
} catch {
result(error as NSError)
}
}
}
}
task.resume()
}
}
public class customAlert {
var title = ""
var message = ""
init(title: String, message: String) {
self.title = title
self.message = title
}
}
//custom function to count characters from String
public class CumstomString {
private var value : String
private var starIndex : Int
private var endIndex : Int
init(string: String, startIndex : Int, endIndex : Int) {
self.value = string
self.starIndex = startIndex
self.endIndex = endIndex
}
var range : String {
let StringTransform = Array(value.characters)
let result = String(StringTransform[self.starIndex...self.endIndex - 1])
return result
}
}
| agpl-3.0 | 29d5bc75a6025733c7df0b87badf0770 | 23.024691 | 113 | 0.545221 | 4.494226 | false | false | false | false |
suzp1984/algorithms-visualization-polyglot-demos | money-simulation/PISimulateIOS/PISimulateIOS/PISimulateView.swift | 1 | 2353 | //
// PISimulateView.swift
// PISimulateIOS
//
// Created by Jacob Su on 10/12/17.
// Copyright © 2017 Jacob Su. All rights reserved.
//
import UIKit
class PISimulateView: UIView {
var w : CGFloat = 0
var needReDraw = true
var px : CGFloat = 0.0
var py : CGFloat = 0.0
override var bounds: CGRect {
didSet {
needReDraw = true
setNeedsDisplay()
}
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
if bounds.width == 0 {
return
}
if needReDraw {
needReDraw = false
drawFrame(rect: rect)
return
}
if w == 0 {
w = bounds.width < bounds.height ? bounds.width : bounds.height
}
renderAt(x: px, y: py)
}
func renderRandomPoint() -> Void {
let x = CGFloat(arc4random_uniform(UInt32(w)))
let y = CGFloat(arc4random_uniform(UInt32(w)))
px = x
py = y
setNeedsDisplay()
}
func renderAt(x: CGFloat, y: CGFloat) -> Void {
// print("render at (x, y) = \(x) \(y)")
let con = UIGraphicsGetCurrentContext()
guard let ctx = con else {
return
}
if (insideCircle(x: x, y: y)) {
ctx.setFillColor(UIColor.red.cgColor)
} else {
ctx.setFillColor(UIColor.blue.cgColor)
}
ctx.fillEllipse(in: CGRect(x: x, y: y, width: 4, height: 4))
}
private func drawFrame(rect: CGRect) {
print("draw frame")
w = rect.width <= rect.height ? rect.width : rect.height
let con = UIGraphicsGetCurrentContext()
guard let ctx = con else {
return
}
ctx.clear(rect)
ctx.setFillColor(UIColor.white.cgColor)
ctx.fill(rect)
ctx.setStrokeColor(UIColor.black.cgColor)
ctx.setLineWidth(2)
ctx.stroke(CGRect(x: 0, y: 0, width: w, height: w))
}
private func insideCircle(x: CGFloat, y: CGFloat) -> Bool {
let r = w / 2
return (x - r) * (x - r) + (y - r) * (y - r) < r * r;
}
}
| apache-2.0 | d90b88a2e3905872dcbcfba747a10e99 | 24.290323 | 78 | 0.516156 | 3.993209 | false | false | false | false |
tomkowz/TSTextMapper | TSTextMapper/ViewController.swift | 1 | 1494 | //
// ViewController.swift
// TSTextMapper
//
// Created by Tomasz Szulc on 31/10/14.
// Copyright (c) 2014 Tomasz Szulc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.label.text = "All of these words are able to be selected. Spaces too. You can specify ranges of text to be selected too if you want."
}
private var mapper: TSTextMapper?
@IBAction func handleTap(recognizer: UITapGestureRecognizer) {
if self.mapper == nil {
self.mapper = TSTextMapper(self.label)
// 1. All words
self.mapper!.mapTextAndMakeAllTappable(self.label.text!)
// 2. Only "Spaces" word is tappable
// let range = (self.label.text as NSString!).rangeOfString("Spaces")
// self.mapper!.mapTextWithTappableRanges([range], text: self.label.text!)
}
let point = recognizer.locationInView(self.label)
if let word = self.mapper!.textForPoint(point) {
let alert = UIAlertView(title: nil, message: word.value, delegate: nil, cancelButtonTitle: nil)
alert.show()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
alert.dismissWithClickedButtonIndex(0, animated: true)
})
}
}
}
| apache-2.0 | a85c74e52e446d308471a881e952c356 | 34.571429 | 146 | 0.618474 | 4.293103 | false | false | false | false |
monadis/PopupDialog | PopupDialog/Classes/PopupDialog.swift | 1 | 11566 | //
// PopupDialog.swift
//
// Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk)
// Author - Martin Wildfeuer (http://www.mwfire.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
/// Creates a Popup dialog similar to UIAlertController
final public class PopupDialog: UIViewController {
// MARK: Private / Internal
/// First init flag
fileprivate var initialized = false
/// The completion handler
fileprivate var completion: (() -> Void)? = nil
/// The custom transition presentation manager
fileprivate var presentationManager: PresentationManager!
/// Interactor class for pan gesture dismissal
fileprivate lazy var interactor = InteractiveTransition()
/// Returns the controllers view
internal var popupContainerView: PopupDialogContainerView {
return view as! PopupDialogContainerView
}
/// The set of buttons
fileprivate var buttons = [PopupDialogButton]()
/// Whether keyboard has shifted view
internal var keyboardShown = false
/// Keyboard height
internal var keyboardHeight: CGFloat? = nil
// MARK: Public
/// The content view of the popup dialog
public var viewController: UIViewController
/// Whether or not to shift view for keyboard display
public var keyboardShiftsView = true
// MARK: - Initializers
/*!
Creates a standard popup dialog with title, message and image field
- parameter title: The dialog title
- parameter message: The dialog message
- parameter image: The dialog image
- parameter buttonAlignment: The dialog button alignment
- parameter transitionStyle: The dialog transition style
- parameter gestureDismissal: Indicates if dialog can be dismissed via pan gesture
- parameter completion: Completion block invoked when dialog was dismissed
- returns: Popup dialog default style
*/
public convenience init(
title: String?,
message: String?,
image: UIImage? = nil,
buttonAlignment: UILayoutConstraintAxis = .vertical,
transitionStyle: PopupDialogTransitionStyle = .bounceUp,
gestureDismissal: Bool = true,
completion: (() -> Void)? = nil) {
// Create and configure the standard popup dialog view
let viewController = PopupDialogDefaultViewController()
viewController.titleText = title
viewController.messageText = message
viewController.image = image
// Call designated initializer
self.init(viewController: viewController, buttonAlignment: buttonAlignment, transitionStyle: transitionStyle, gestureDismissal: gestureDismissal, completion: completion)
}
/*!
Creates a popup dialog containing a custom view
- parameter viewController: A custom view controller to be displayed
- parameter buttonAlignment: The dialog button alignment
- parameter transitionStyle: The dialog transition style
- parameter gestureDismissal: Indicates if dialog can be dismissed via pan gesture
- parameter completion: Completion block invoked when dialog was dismissed
- returns: Popup dialog with a custom view controller
*/
public init(
viewController: UIViewController,
buttonAlignment: UILayoutConstraintAxis = .vertical,
transitionStyle: PopupDialogTransitionStyle = .bounceUp,
gestureDismissal: Bool = true,
completion: (() -> Void)? = nil) {
self.viewController = viewController
self.completion = completion
super.init(nibName: nil, bundle: nil)
// Init the presentation manager
presentationManager = PresentationManager(transitionStyle: transitionStyle, interactor: interactor)
// Assign the interactor view controller
interactor.viewController = self
// Define presentation styles
transitioningDelegate = presentationManager
modalPresentationStyle = .custom
// Add our custom view to the container
if #available(iOS 9.0, *) {
if let stackView = popupContainerView.stackView as? UIStackView {
stackView.insertArrangedSubview(viewController.view, at: 0)
}
} else {
if let stackView = popupContainerView.stackView as? TZStackView {
stackView.insertArrangedSubview(viewController.view, at: 0)
}
}
// Set button alignment
if #available(iOS 9.0, *) {
if let stackView = popupContainerView.buttonStackView as? UIStackView {
stackView.axis = buttonAlignment
}
} else {
if let stackView = popupContainerView.buttonStackView as? TZStackView {
stackView.axis = buttonAlignment
}
}
// Allow for dialog dismissal on background tap and dialog pan gesture
if gestureDismissal {
let panRecognizer = UIPanGestureRecognizer(target: interactor, action: #selector(InteractiveTransition.handlePan))
popupContainerView.stackView.addGestureRecognizer(panRecognizer)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
popupContainerView.addGestureRecognizer(tapRecognizer)
}
}
// Init with coder not implemented
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View life cycle
/// Replaces controller view with popup view
public override func loadView() {
view = PopupDialogContainerView(frame: UIScreen.main.bounds)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard !initialized else { return }
appendButtons()
addObservers()
initialized = true
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeObservers()
}
deinit {
completion?()
completion = nil
}
// MARK - Dismissal related
@objc fileprivate func handleTap(_ sender: UITapGestureRecognizer) {
// Make sure it's not a tap on the dialog but the background
let point = sender.location(in: popupContainerView.stackView)
guard !popupContainerView.stackView.point(inside: point, with: nil) else { return }
dismiss()
}
/*!
Dismisses the popup dialog
*/
public func dismiss(_ completion: (() -> Void)? = nil) {
self.dismiss(animated: true) {
completion?()
}
}
// MARK: - Button related
/*!
Appends the buttons added to the popup dialog
to the placeholder stack view
*/
fileprivate func appendButtons() {
// Add action to buttons
if #available(iOS 9.0, *) {
let stackView = popupContainerView.stackView as! UIStackView
let buttonStackView = popupContainerView.buttonStackView as! UIStackView
if buttons.isEmpty {
stackView.removeArrangedSubview(popupContainerView.buttonStackView)
}
for (index, button) in buttons.enumerated() {
button.needsLeftSeparator = buttonStackView.axis == .horizontal && index > 0
buttonStackView.addArrangedSubview(button)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
} else {
let stackView = popupContainerView.stackView as! TZStackView
let buttonStackView = popupContainerView.buttonStackView as! TZStackView
if buttons.isEmpty {
stackView.removeArrangedSubview(popupContainerView.buttonStackView)
}
for (index, button) in buttons.enumerated() {
button.needsLeftSeparator = buttonStackView.axis == .horizontal && index > 0
buttonStackView.addArrangedSubview(button)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
}
}
/*!
Adds a single PopupDialogButton to the Popup dialog
- parameter button: A PopupDialogButton instance
*/
public func addButton(_ button: PopupDialogButton) {
buttons.append(button)
}
/*!
Adds an array of PopupDialogButtons to the Popup dialog
- parameter buttons: A list of PopupDialogButton instances
*/
public func addButtons(_ buttons: [PopupDialogButton]) {
self.buttons += buttons
}
/// Calls the action closure of the button instance tapped
@objc fileprivate func buttonTapped(_ button: PopupDialogButton) {
if button.dismissOnTap {
dismiss() { button.buttonAction?() }
} else {
button.buttonAction?()
}
}
/*!
Simulates a button tap for the given index
Makes testing a breeze
- parameter index: The index of the button to tap
*/
public func tapButtonWithIndex(_ index: Int) {
let button = buttons[index]
button.buttonAction?()
}
}
// MARK: - View proxy values
extension PopupDialog {
/// The button alignment of the alert dialog
public var buttonAlignment: UILayoutConstraintAxis {
get {
if #available(iOS 9.0, *) {
let buttonStackView = popupContainerView.buttonStackView as! UIStackView
return buttonStackView.axis
} else {
let buttonStackView = popupContainerView.buttonStackView as! TZStackView
return buttonStackView.axis
}
}
set {
if #available(iOS 9.0, *) {
let buttonStackView = popupContainerView.buttonStackView as! UIStackView
buttonStackView.axis = newValue
} else {
let buttonStackView = popupContainerView.buttonStackView as! TZStackView
buttonStackView.axis = newValue
}
popupContainerView.pv_layoutIfNeededAnimated()
}
}
/// The transition style
public var transitionStyle: PopupDialogTransitionStyle {
get { return presentationManager.transitionStyle }
set { presentationManager.transitionStyle = newValue }
}
}
| mit | c44c41188cd748ed096c2a65302f02e6 | 35.257053 | 177 | 0.65217 | 5.512869 | false | false | false | false |
kevin-zqw/play-swift | swift-lang/16. ARC.playground/section-1.swift | 1 | 14411 | // ------------------------------------------------------------------------------------------------
// Things to know:
//
// * Automatic Reference Counting allows Swift to track and manage your app's memory usage. It
// automatically frees up memory from unused instances that are no longer in use.
//
// * Reference counting only applies to classes as structures and enumerations are value types.
//
// * Whenever a class instance is stored (to a property, constant or variable) a
// "strong reference" is made. A strong reference ensures that the reference is not deallocated
// for as long as the strong reference remains.
// ------------------------------------------------------------------------------------------------
// We can't really see ARC in action within a Playground, but we can still follow along what
// would normally happen.
//
// We'll start by creating a class to work with
class Person
{
let name: String
init (name: String)
{
self.name = name
}
}
// We'll want to create a person and then remove our reference to it, which means we'll need to
// use an optional Person type stored in a variable:
var person: Person? = Person(name: "Bill")
// We now have a single strong reference to a single Person object.
//
// If we assign 'person' to another variable or constant, we'll increse the reference conunt by 1
// for a total of 2:
var copyOfPerson = person
// With a reference count of 2, we can set our original reference to nil. This will drop our
// reference count down to 1.
person = nil
// The copyOfPerson still exists and holds a strong reference to our instance:
copyOfPerson
// If we clear out this reference, we will drop the reference count once more to 0, causing the
// object to be cleaned up by ARC:
copyOfPerson = nil
// ------------------------------------------------------------------------------------------------
// Strong Reference Cycles between class instances
//
// If two classes hold a reference to each other, then they create a "Strong Reference Cycle".
//
// Here's an example of two classes that are capable of holding references to one another, but
// do not do so initially (their references are optional and defaulted to nil):
class Tenant
{
let name: String
var apartment: Apartment?
init(name: String) { self.name = name }
}
class Apartment
{
let number: Int
var tenant: Tenant?
init (number: Int) { self.number = number }
}
// We can create a tenant and an apartment which are not associated to each other. After these
// two lines of code, each instance will have a reference count of 1.
var bill: Tenant? = Tenant(name: "Bill")
var number73: Apartment? = Apartment(number: 73)
// Let's link them up.
//
// This will create a strong reference cycle because each instance will have a reference to the
// other. The end result is that each instance will now have a reference count of 2. For example,
// the two strong references for the Tenant instances are held by 'bill' and the 'tenant'
// property inside the 'number73' apartment.
//
// Note the "!" symbols for forced unwrapping (covered in an earlier section):
bill!.apartment = number73
number73!.tenant = bill
// If we try to clean up, the memory will not be deallocated by ARC. Let's follow along what
// actually happens a step at a time.
//
// First, we set 'bill' to be nil, which drops the strong reference count for this instance of
// Tenant down to 1. Since there is still a strong reference held to this instance, it is never
// deallocated (and the deinit() is also never called on that instance of Person.)
bill = nil
// Next we do the same for 'number73' dropping the strong reference count for this instance of
// Apartment down to 1. Similarly, it is not deallocated or deinitialized.
number73 = nil
// At this point, we have two instances that still exist in memory, but cannot be cleaned up
// because we don't have any references to them in order to solve the problem.
// ------------------------------------------------------------------------------------------------
// Resolving Strong Reference Cycles between Class Instances
//
// Swift provides two methods to resolve strong reference cycles: weak and unowned references.
// ------------------------------------------------------------------------------------------------
// Weak references allow an instance to be held without actually having a strong hold on it (and
// hence, not incrementing the reference count for the target object.)
//
// Use weak references when it's OK for a reference to become nil sometime during its lifetime.
// Since the Apartment can have no tenant at some point during its lifetime, a weak reference
// is the right way to go.
//
// Weak references must always be optional types (because they may be required to be nil.) When
// an object holds a weak reference to an object, if that object is ever deallocated, Swift will
// locate all the weak references to it and set those references to nil.
//
// Weak references are declared using the 'weak' keyword.
//
// Let's fix our Apartment class. Note that we only have to break the cycle. It's perfectly
// fine to let the Tenant continue to hold a strong reference to our apartment. We will also
// create a new Tenant class (we'll just give it a new name, "NamedTenant"), but only so that we
// can change the apartment type to reference our fixed Apartment class.
class NamedTenant
{
let name: String
var apartment: FixedApartment?
init(name: String) { self.name = name }
}
class FixedApartment
{
let number: Int
weak var tenant: NamedTenant?
init (number: Int) { self.number = number }
}
// Here is our new tenant and his new apartment.
//
// This will create a single strong reference to each:
var jerry: NamedTenant? = NamedTenant(name: "Jerry")
var number74: FixedApartment? = FixedApartment(number: 74)
// Let's link them up like we did before. Note that this time we're not creating a new strong
// reference to the NamedTenant so the reference count will remain 1. The FixedApartment
// however, will have a reference count of 2 (because the NamedTenant will hold a strong reference
// to it.)
jerry!.apartment = number74
number74!.tenant = jerry
// At this point, we have one strong reference to the NamedTenant and two strong references to
// FixedApartment.
//
// Let's set jerry to nil, which will drop his reference count to 0 causing it to get
// deallocated. Once this happens, it is also deinitialized.
jerry = nil
// With 'jerry' deallocated, the strong reference it once held to FixedApartment is also cleaned
// up leaving only one strong reference remaining to the FixedApartment class.
//
// If we clear 'number74' then we'll remove the last remaining strong reference:
number74 = nil
// ------------------------------------------------------------------------------------------------
// Unowned References
//
// Unowned refernces are similar to weak references in that they do not hold a strong reference
// to an instance. However, the key difference is that if the object the reference is deallocated
// they will not be set to nil like weak references to. Therefore, it's important to ensure that
// any unowned references will always have a value. If this were to happen, accessing the unowned
// reference will trigger a runtime error. In fact, Swift guraantees that your app will crash in
// this scenario.
//
// Unowned references are created using the 'unowned' keyword and they must not be optional.
//
// We'll showcase this with a Customer and Credit Card. This is a good example case because a
// customer may have the credit card, or they may close the account, but once a Credit Card
// has been created, it will always have a customer.
class Customer
{
let name: String
var card: CreditCard?
init (name: String)
{
self.name = name
}
}
class CreditCard
{
let number: Int
unowned let customer: Customer
// Since 'customer' is not optional, it must be set in the initializer
init (number: Int, customer: Customer)
{
self.number = number
self.customer = customer
}
}
// ------------------------------------------------------------------------------------------------
// Unowned References and Implicitly Unwrapped Optional Properties
//
// We've covered two common scenarios of cyclic references, but there is a third case. Consider
// the case of a country and its capital city. Unlike the case where a customer may have a credit
// card, or the case where an apartment may have a tenant, a country will always have a capital
// city and a capital city will always have a tenant.
//
// The solution is to use an unowned property in one class and an implicitly unwrapped optional
// property in the other class. This allows both properties to be accessed directly (without
// optional unwrapping) once initialization is complete, while avoiding the reference cycle.
//
// Let's see how this is done:
class Country
{
let name: String
// let capitalCity: City!
init(name: String, capitalName: String)
{
self.name = name
// self.capitalCity = City(name: capitalName, country: self)
}
}
class City
{
let name: String
unowned let country: Country
init(name: String, country: Country)
{
self.name = name
self.country = country
}
}
// We can define a Country with a capital city
var america = Country(name: "USA", capitalName: "Washington DC")
// Here's how and why this works.
//
// The relationship between Customer:CreditCard is very similar to the relationship between
// Country:City. The two key differences are that (1) the country initializes its own city and the
// country does not need to reference the city through the optional binding or forced unwrapping
// because the Country defines the city with the implicitly unwrapped optional property (using the
// exclamation mark on the type annotation (City!).
//
// The City uses an unowned Country property in the same way (and for the same reasons) as the
// CreditCard uses an unowned property of a Customer.
//
// The Country still uses an optional (though implicitly unwrapped) for the same reason that the
// Customer uses an optional to store a CreditCard. If we look at Country's initializer, we see
// that it initializes a capitalCity by passing 'self' to the City initializer. Normally, an
// initializer cannot reference its own 'self' until it has fully initialized the object. In this
// case, the Country can access its own 'self' because once 'name' has been initialized, the object
// is considered fully initialized. This is the case because 'capitalCity' is an optional.
//
// We take this just a step further by declaring 'capitalCity' to be an implicitly unwrapped
// optinoal property so that we can avoid having to deal with unwrapping 'capitalCity' whenever we
// want to access it.
// ------------------------------------------------------------------------------------------------
// Strong Reference Cycles for Closures
//
// We've seen how classes can reference each other creating a cyclic reference because classes are
// reference types. However, classes aren't the only way to create a cyclic reference. These
// problematic references can also happen with closures because they, too, are reference types.
//
// This happens when a closure captures an instance of a class (simply because it uses the class
// reference within the closure) and a class maintains a reference to the closure. Note that the
// references that a closure captures are automatically strong references.
//
// Let's see how this problem can manifest. We'll create a class that represents an HTML element
// which includes a variable (asHTML) which stores a reference to a closure.
//
// Quick note: The asHTML variable is defined as lazy so that it can reference 'self' within the
// closure. Try removing the 'lazy' and you'll see that you get an error trying to access 'self'.
// This is an error because we're not allowed to access 'self' during Phase 1 initialization. By
// making 'asHTML' lazy, we solve this problem by deferring its initialization until later.
class HTMLElement
{
let name: String
let text: String?
lazy var asHTML: () -> String =
{
if let text = self.text
{
return "<\(self.name)>\(text)</\(self.name)>"
}
else
{
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil)
{
self.name = name
self.text = text
}
}
// Let's use the HTMLElement. We'll make sure we declare it as optional so we can set it to 'nil'
// later.
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "Hello, world")
paragraph!.asHTML()
// At this point, we've created a strong reference cycle between the HTMLElement instance and the
// asHTML closure because the closure references the object which owns [a reference to] it.
//
// We can set paragraph to nil, but the HTMLElement will not get deallocated:
paragraph = nil
// The solution here is to use a "Closure Capture List" as part of the closure's definition. This
// essentially allows us to modify the default behavior of closures using strong references for
// captured instances.
//
// Here's how we define a capture list:
//
// lazy var someClosure: (Int, String) -> String =
// {
// [unowned self] (index: Int, stringToProcess: String) -> String in
//
// // ... code here ...
// }
//
// Some closures can used simplified syntax if their parameters are inferred while other closures
// may not have any parameters. In both cases the method for declaring the capture list doesn't
// change much. Simply include the capture list followed by the 'in' keyword:
//
// lazy var someClosure: () -> String =
// {
// [unowned self] in
//
// // ... code here ...
// }
//
// Let's see how we can use this to resolve the HTMLElement problem. We'll create a new class,
// FixedHTMLElement which is identical to the previous with the exception of the addition of the
// line: "[unowned self] in"
class FixedHTMLElement
{
let name: String
let text: String?
lazy var asHTML: () -> String =
{
[unowned self] in
if let text = self.text
{
return "<\(self.name)>\(text)</\(self.name)>"
}
else
{
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil)
{
self.name = name
self.text = text
}
}
// Playgrounds do not allow us to test/prove this, so feel free to plug this into a compiled
// application to see it in action.
// ARC and memory are important, although we won't use them explictly very often.
| apache-2.0 | f4aab0a861c85603ae845e4ca1283add | 37.532086 | 99 | 0.69669 | 4.183164 | false | false | false | false |
lenssss/whereAmI | Whereami/Controller/Personal/PersonalAchievementsCollectionViewCell.swift | 1 | 2268 | //
// PersonalAchievementsCollectionViewCell.swift
// Whereami
//
// Created by A on 16/6/1.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
class PersonalAchievementsCollectionViewCell: UICollectionViewCell {
var itemLogo:UIImageView? = nil
var progressLabel:UILabel? = nil
var itemName:UILabel? = nil
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
func setupUI(){
itemLogo = UIImageView()
itemLogo?.backgroundColor = UIColor.lightGrayColor()
self.contentView.addSubview(itemLogo!)
/*
progress = UIProgressView()
progress?.progressTintColor = UIColor.greenColor()
progress?.trackTintColor = UIColor.grayColor()
progress?.progress = 0.5
self.contentView.addSubview(progress!)
*/
progressLabel = UILabel()
progressLabel?.textAlignment = .Center
progressLabel?.textColor = UIColor.grayColor()
progressLabel?.font = UIFont.customFont(12.0)
self.contentView.addSubview(progressLabel!)
itemName = UILabel()
itemName?.textAlignment = .Center
itemName?.textColor = UIColor.grayColor()
self.contentView.addSubview(itemName!)
itemLogo?.autoPinEdgeToSuperviewEdge(.Left, withInset: 10)
itemLogo?.autoPinEdgeToSuperviewEdge(.Right, withInset: 10)
itemLogo?.autoPinEdgeToSuperviewEdge(.Top, withInset: 10)
itemLogo?.autoSetDimension(.Height, toSize: 60)
progressLabel?.autoPinEdge(.Top, toEdge: .Bottom, ofView: itemLogo!, withOffset: 10)
progressLabel?.autoPinEdgeToSuperviewEdge(.Left, withInset: 10)
progressLabel?.autoPinEdgeToSuperviewEdge(.Right, withInset: 10)
progressLabel?.autoSetDimension(.Height, toSize: 13)
itemName?.autoPinEdge(.Top, toEdge: .Bottom, ofView: progressLabel!)
itemName?.autoPinEdgeToSuperviewEdge(.Left, withInset: 10)
itemName?.autoPinEdgeToSuperviewEdge(.Right, withInset: 10)
itemName?.autoPinEdgeToSuperviewEdge(.Bottom)
}
}
| mit | 3050b915a6f56320bfd28c2d0f205469 | 33.318182 | 92 | 0.656512 | 5.27972 | false | false | false | false |
shijinliang/KSMoney | Sources/App/Category/JPushTool.swift | 1 | 6294 | //
// JPushTool.swift
// NHServer
//
// Created by niuhui on 2017/6/22.
//
//
import Vapor
import HTTP
import Foundation
import Crypto
let jUrl : String = "https://api.jpush.cn/v3/push"
let jHeader : [HeaderKey : String] = ["Authorization":"Basic NGExNGI4Mjc3OGM5YzVlMTlmYTllODFkOmRkYWJjZDQxMTc0YWNjN2I3ZmQzNTcwMA=="]
class JPushTool: NSObject {
private class func pushMsg(_ regus_ids: [String] , msg: String) {
background {
do {
let pushMsg : Node = try [
"platform":"ios",
"audience":[
"registration_id":regus_ids.makeNode(in: nil)
],
"notification":[
"ios":[
"alert":msg.makeNode(in: nil),
"sound":"default",
"badge":"1"
]
],
"options":[
"apns_production":false
]
]
let req = try drop.client.post(jUrl, jHeader , Body(JSON(pushMsg)))
print(req)
} catch {
}
}
}
// open class func sendAroundPush(_ user : User?,around: AroundMsg) {
// do {
// try background {
// do {
// if let user = user {
// if let friends = try? Friend.query().filter("m_uuid", user.uuid).filter("state", .notEquals, 0).all() {
// if friends.count == 0 {
// print("没有好友")
// }
// let uuids = friends.map{$0.f_uuid}
// if uuids.count == 0 {
// print("没有uuids")
// }
// let sessions = try Session.query().filter("expire_at",.notEquals,0).filter("jpush_id", .notEquals, "").filter("uuid", .in, uuids).all()
// var temp = ""
// if around.message.count <= 40 {
// temp = around.message
// } else {
// let index = around.message.index(around.message.startIndex, offsetBy: 40)
// temp = around.message.substring(to: index)
// }
// if around.message.isEmpty && !around.images.isEmpty {
// temp = "图片动态"
// }
// temp = "【\(user.name)的动态】\(temp)"
// let ids = sessions.map{$0.jpush_id}
// if ids.count == 0 {
// print("没有 jpush_ids")
// } else {
// pushMsg(ids, msg: temp)
// }
// } else {
// print("没有好友")
// }
// }
// } catch {
//
// }
// }
// } catch {
//
// }
// }
// open class func commentAroundPush(_ user: User, around: AroundMsg,commemt: AroundComment) {
// do {
// try background {
// do {
// if let session = try Session.query().filter("uuid", around.uuid).filter("expire_at",.notEquals,0).filter("jpush_id", .notEquals, "").first() {
// var temp = ""
// if commemt.message.count <= 40 {
// temp = commemt.message
// } else {
// let index = commemt.message.index(commemt.message.startIndex, offsetBy: 40)
// temp = commemt.message.substring(to: index)
// }
// temp = "【\(user.name)的评论】\(temp)"
// pushMsg([session.jpush_id], msg: temp)
// }
// } catch {
//
// }
//
// }
// } catch {
//
// }
// }
// open class func addFriendPush(_ user: User, f_user: User) {
// do {
// try background {
// do {
// if let session = try Session.query().filter("uuid", f_user.uuid).filter("expire_at",.notEquals,0).filter("jpush_id", .notEquals, "").first() {
// pushMsg([session.jpush_id], msg: "【\(user.name)】请求添加好友,快去看看吧!")
// }
// } catch {
//
// }
//
// }
// } catch {
//
// }
// }
// open class func refuseFriendPush(_ user: User, f_user: User) {
// do {
// try background {
// do {
// if let session = try Session.query().filter("uuid", f_user.uuid).filter("expire_at",.notEquals,0).filter("jpush_id", .notEquals, "").first() {
// pushMsg([session.jpush_id], msg: "【\(user.name)】拒绝了你的好友请求,快去看看吧!")
// }
// } catch {
//
// }
//
// }
// } catch {
//
// }
// }
// open class func agreeFriendPush(_ user: User, f_user: User) {
// do {
// try background {
// do {
// if let session = try Session.query().filter("uuid", f_user.uuid).filter("expire_at",.notEquals,0).filter("jpush_id", .notEquals, "").first() {
// pushMsg([session.jpush_id], msg: "【\(user.name)】同意你的好友请求,成为好友!")
// }
// } catch {
//
// }
//
// }
// } catch {
//
// }
// }
}
| mit | bee5a1ef77e5a6097c79854c2ce26937 | 37.4 | 165 | 0.35498 | 4.266667 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieMath/Accelerate/Wrapper.swift | 1 | 7637 | //
// Wrapper.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension UnsafePointer where Pointee == Complex {
@inlinable
@inline(__always)
func _reboundToDouble(capacity: Int, body: (UnsafePointer<Double>) -> Void) {
let raw_ptr = UnsafeRawPointer(self)
let bound_ptr = raw_ptr.bindMemory(to: Double.self, capacity: capacity << 1)
defer { _ = raw_ptr.bindMemory(to: Complex.self, capacity: capacity) }
return body(bound_ptr)
}
}
extension UnsafeMutablePointer where Pointee == Complex {
@inlinable
@inline(__always)
func _reboundToDouble(capacity: Int, body: (UnsafeMutablePointer<Double>) -> Void) {
let raw_ptr = UnsafeMutableRawPointer(self)
let bound_ptr = raw_ptr.bindMemory(to: Double.self, capacity: capacity << 1)
defer { _ = raw_ptr.bindMemory(to: Complex.self, capacity: capacity) }
return body(bound_ptr)
}
}
@inlinable
@inline(__always)
public func HalfRadix2CooleyTukey(_ log2n: Int, _ input: UnsafePointer<Double>, _ in_stride: Int, _ in_count: Int, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int) {
let length = 1 << log2n
let half = length >> 1
output._reboundToDouble(capacity: half) { HalfRadix2CooleyTukey(log2n, input, in_stride, in_count, $0, $0.successor(), out_stride << 1) }
}
@inlinable
@inline(__always)
public func HalfInverseRadix2CooleyTukey(_ log2n: Int, _ input: UnsafePointer<Complex>, _ in_stride: Int, _ output: UnsafeMutablePointer<Double>, _ out_stride: Int) {
let length = 1 << log2n
let half = length >> 1
input._reboundToDouble(capacity: half) { _input in HalfInverseRadix2CooleyTukey(log2n, _input, _input.successor(), in_stride << 1, output, out_stride) }
}
@inlinable
@inline(__always)
public func Radix2CooleyTukey(_ log2n: Int, _ input: UnsafePointer<Double>, _ in_stride: Int, _ in_count: Int, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int) {
let length = 1 << log2n
output._reboundToDouble(capacity: length) { Radix2CooleyTukey(log2n, input, in_stride, in_count, $0, $0.successor(), out_stride << 1) }
}
@inlinable
@inline(__always)
public func Radix2CooleyTukey(_ log2n: Int, _ input: UnsafePointer<Complex>, _ in_stride: Int, _ in_count: Int, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int) {
let length = 1 << log2n
input._reboundToDouble(capacity: in_count) { _input in output._reboundToDouble(capacity: length) { Radix2CooleyTukey(log2n, _input, _input.successor(), in_stride << 1, in_count, $0, $0.successor(), out_stride << 1) } }
}
@inlinable
@inline(__always)
public func InverseRadix2CooleyTukey(_ log2n: Int, _ input: UnsafePointer<Double>, _ in_stride: Int, _ in_count: Int, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int) {
let length = 1 << log2n
output._reboundToDouble(capacity: length) { InverseRadix2CooleyTukey(log2n, input, in_stride, in_count, $0, $0.successor(), out_stride << 1) }
}
@inlinable
@inline(__always)
public func InverseRadix2CooleyTukey(_ log2n: Int, _ input: UnsafePointer<Complex>, _ in_stride: Int, _ in_count: Int, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int) {
let length = 1 << log2n
input._reboundToDouble(capacity: in_count) { _input in output._reboundToDouble(capacity: length) { InverseRadix2CooleyTukey(log2n, _input, _input.successor(), in_stride << 1, in_count, $0, $0.successor(), out_stride << 1) } }
}
@inlinable
@inline(__always)
public func Radix2CooleyTukey(_ log2n: Int, _ buffer: UnsafeMutablePointer<Complex>, _ stride: Int) {
let length = 1 << log2n
buffer._reboundToDouble(capacity: length) { Radix2CooleyTukey(log2n, $0, $0.successor(), stride << 1) }
}
@inlinable
@inline(__always)
public func InverseRadix2CooleyTukey(_ log2n: Int, _ buffer: UnsafeMutablePointer<Complex>, _ stride: Int) {
let length = 1 << log2n
buffer._reboundToDouble(capacity: length) { InverseRadix2CooleyTukey(log2n, $0, $0.successor(), stride << 1) }
}
@inlinable
@inline(__always)
public func Radix2CircularConvolve(_ log2n: Int, _ signal: UnsafePointer<Complex>, _ signal_stride: Int, _ signal_count: Int, _ kernel: UnsafePointer<Complex>, _ kernel_stride: Int, _ kernel_count: Int, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int, _ temp: UnsafeMutablePointer<Complex>, _ temp_stride: Int) {
let length = 1 << log2n
signal._reboundToDouble(capacity: signal_count) { _signal in kernel._reboundToDouble(capacity: kernel_count) { _kernel in temp._reboundToDouble(capacity: length) { _temp in output._reboundToDouble(capacity: length) { Radix2CircularConvolve(log2n, _signal, _signal.successor(), signal_stride << 1, signal_count, _kernel, _kernel.successor(), kernel_stride << 1, kernel_count, $0, $0.successor(), out_stride << 1, _temp, _temp.successor(), temp_stride << 1) } } } }
}
@inlinable
@inline(__always)
public func Radix2PowerCircularConvolve(_ log2n: Int, _ input: UnsafePointer<Complex>, _ in_stride: Int, _ in_count: Int, _ n: Double, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int) {
let length = 1 << log2n
input._reboundToDouble(capacity: in_count) { _input in output._reboundToDouble(capacity: length) { Radix2PowerCircularConvolve(log2n, _input, _input.successor(), in_stride << 1, in_count, n, $0, $0.successor(), out_stride << 1) } }
}
@inlinable
@inline(__always)
public func Radix2FiniteImpulseFilter(_ log2n: Int, _ signal: UnsafePointer<Double>, _ signal_stride: Int, _ signal_count: Int, _ kernel: UnsafePointer<Complex>, _ kernel_stride: Int, _ output: UnsafeMutablePointer<Double>, _ out_stride: Int) {
let length = 1 << log2n
let half = length >> 1
kernel._reboundToDouble(capacity: half) { Radix2FiniteImpulseFilter(log2n, signal, signal_stride, signal_count, $0, $0.successor(), kernel_stride << 1, output, out_stride) }
}
@inlinable
@inline(__always)
public func Radix2FiniteImpulseFilter(_ log2n: Int, _ signal: UnsafePointer<Complex>, _ signal_stride: Int, _ signal_count: Int, _ kernel: UnsafePointer<Complex>, _ kernel_stride: Int, _ output: UnsafeMutablePointer<Complex>, _ out_stride: Int) {
let length = 1 << log2n
signal._reboundToDouble(capacity: signal_count) { _signal in kernel._reboundToDouble(capacity: length) { _kernel in output._reboundToDouble(capacity: length) { Radix2FiniteImpulseFilter(log2n, _signal, _signal.successor(), signal_stride << 1, signal_count, _kernel, _kernel.successor(), kernel_stride << 1, $0, $0.successor(), out_stride << 1) } } }
}
| mit | e769bc2460ea8f97185922846f8c493c | 59.133858 | 467 | 0.70656 | 3.509651 | false | false | false | false |
palle-k/Covfefe | Tests/CovfefeTests/UtilitiesTest.swift | 1 | 6115 | //
// UtilitiesTest.swift
// CovfefeTests
//
// Created by Palle Klewitz on 11.08.17.
// Copyright (c) 2017 Palle Klewitz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import XCTest
@testable import Covfefe
class StringUtilitiesTest: XCTestCase {
func testPrefix() {
let testedString = "hello, world"
XCTAssertEqual(testedString.rangeOfPrefix("world", from: testedString.startIndex), nil)
XCTAssertEqual(testedString.rangeOfPrefix("world", from: testedString.firstIndex(of: "w")!), testedString.range(of: "world"))
XCTAssertNotEqual(testedString.rangeOfPrefix("world", from: testedString.index(testedString.startIndex, offsetBy: 8)), testedString.range(of: "world"))
XCTAssertFalse(testedString.hasPrefix("world", from: testedString.startIndex))
XCTAssertTrue(testedString.hasPrefix("world", from: testedString.firstIndex(of: "w")!))
XCTAssertFalse(testedString.hasPrefix("world", from: testedString.index(testedString.startIndex, offsetBy: 8)))
}
func testRegularPrefix() {
let testedString = "1+2+3+4+5"
XCTAssertTrue(try testedString.hasRegularPrefix("1\\+2"))
XCTAssertTrue(try testedString.hasRegularPrefix("(\\d\\+)*\\d"))
XCTAssertFalse(try testedString.hasRegularPrefix("\\+"))
XCTAssertFalse(try testedString.hasRegularPrefix("\\d\\d"))
XCTAssertFalse(try testedString.hasRegularPrefix("5"))
XCTAssertNotNil(try testedString.rangeOfRegularPrefix("1\\+2"))
XCTAssertNotNil(try testedString.rangeOfRegularPrefix("(\\d\\+)*\\d"))
XCTAssertNil(try testedString.rangeOfRegularPrefix("\\+"))
XCTAssertNil(try testedString.rangeOfRegularPrefix("\\d\\d"))
XCTAssertNil(try testedString.rangeOfRegularPrefix("5"))
XCTAssertEqual(try testedString.rangeOfRegularPrefix("1\\+2"), try testedString.matches(for: "1\\+2").first(where: {$0.lowerBound == testedString.startIndex}))
XCTAssertEqual(try testedString.rangeOfRegularPrefix("(\\d\\+)*\\d"), try testedString.matches(for: "(\\d\\+)*\\d").first(where: {$0.lowerBound == testedString.startIndex}))
XCTAssertEqual(try testedString.rangeOfRegularPrefix("\\+"), try testedString.matches(for: "\\+").first(where: {$0.lowerBound == testedString.startIndex}))
XCTAssertEqual(try testedString.rangeOfRegularPrefix("\\d\\d"), try testedString.matches(for: "\\d\\d").first(where: {$0.lowerBound == testedString.startIndex}))
XCTAssertEqual(try testedString.rangeOfRegularPrefix("5"), try testedString.matches(for: "5").first(where: {$0.lowerBound == testedString.startIndex}))
let startIndex = testedString.index(testedString.startIndex, offsetBy: 2)
XCTAssertTrue(try testedString.hasRegularPrefix("2", from: startIndex))
XCTAssertTrue(try testedString.hasRegularPrefix("(\\d\\+)*\\d", from: startIndex))
XCTAssertFalse(try testedString.hasRegularPrefix("\\+3", from: startIndex))
XCTAssertFalse(try testedString.hasRegularPrefix("1", from: startIndex))
XCTAssertEqual(try testedString.rangeOfRegularPrefix("2", from: startIndex), testedString.range(of: "2"))
XCTAssertEqual(try testedString.rangeOfRegularPrefix("(\\d\\+)*\\d", from: startIndex), testedString.range(of: "2+3+4+5"))
}
func testCharacterRangePrefix() {
let testedString = "hello world"
XCTAssertTrue(testedString.hasPrefix(Terminal(range: "a" ... "z")))
XCTAssertTrue(testedString.hasPrefix(Terminal(range: "h" ... "h")))
XCTAssertTrue(testedString.hasPrefix(Terminal(range: "e" ... "e"), from: testedString.firstIndex(of: "e")!))
XCTAssertFalse(testedString.hasPrefix(Terminal(range: "i" ... "i")))
XCTAssertFalse(testedString.hasPrefix(Terminal(range: "A" ... "Z")))
XCTAssertFalse(testedString.hasPrefix(Terminal(range: "f" ... "g"), from: testedString.firstIndex(of: "e")!))
XCTAssertEqual(testedString.rangeOfPrefix(Terminal(range: "a" ... "z"), from: testedString.startIndex), testedString.startIndex ..< testedString.index(after: testedString.startIndex))
XCTAssertEqual(testedString.rangeOfPrefix(Terminal(range: "z" ... "z"), from: testedString.startIndex), nil)
XCTAssertEqual(testedString.rangeOfPrefix(Terminal(range: "e" ... "e"), from: testedString.index(after: testedString.startIndex)), testedString.index(after: testedString.startIndex) ..< testedString.index(testedString.startIndex, offsetBy: 2))
XCTAssertEqual(testedString.rangeOfPrefix(Terminal(range: "z" ... "z"), from: testedString.startIndex), nil)
}
func testUnique() {
let numbers = [1,2,2,1,5,6,7,1,1]
let uniqueNumbers = numbers.uniqueElements().collect(Array.init)
XCTAssertEqual(uniqueNumbers, [1,2,5,6,7])
}
func testCrossProduct() {
let a = 1...4
let b = 5...8
let axb = crossProduct(a, b)
let axbRef = [(1,5), (1,6), (1,7), (1,8), (2,5), (2,6), (2,7), (2,8), (3,5), (3,6), (3,7), (3,8), (4,5), (4,6), (4,7), (4,8)]
XCTAssertTrue(axb.allSatisfy{el in axbRef.contains(where: {$0 == el})})
}
func testUnzip() {
let aRef = Array(1...10)
let bRef = Array(10...19)
let (a, b): ([Int], [Int]) = unzip(zip(aRef,bRef))
XCTAssertEqual(aRef, a)
XCTAssertEqual(bRef, b)
}
}
| mit | eb8da38bff911a80176678eab3b9e38e | 52.173913 | 245 | 0.724121 | 3.635553 | false | true | false | false |
teroxik/open-muvr | ios/Lift/Predef/Dictionary.swift | 1 | 1325 | import Foundation
extension Dictionary {
///
/// Return the session stats as a list of tuples, ordered by the key
///
func toList() -> [(Key, Value)] {
var r: [(Key, Value)] = []
for (k, v) in self {
let tuple = [(k, v)]
r += tuple
}
return r
}
///
/// Updates this by looking up value under ``key``, applying ``update`` to it if it exists,
/// else setting ``key`` to be ``notFound``
///
mutating func updated(key: Key, notFound: Value, update: Value -> Value) -> Void {
if let x = self[key] {
self[key] = update(x)
} else {
self[key] = notFound
}
}
///
/// Updates this by looking up value under ``key`` and applying ``update`` to it.
///
mutating func updated(key: Key, update: Value -> Value) -> Void {
if let x = self[key] {
self[key] = update(x)
}
}
///
/// Returns a new dictionary created by mapping values with ``f``.
///
func flatMapValues<That>(f: Value -> That?) -> [Key : That] {
var r = [Key : That](minimumCapacity: self.count)
for (k, v) in self {
if let value = f(v) {
r[k] = f(v)
}
}
return r
}
}
| apache-2.0 | 2de097d2dd44d3d7920e316ce25acdda | 24.980392 | 95 | 0.472453 | 3.931751 | false | false | false | false |
PrestonV/ios-cannonball | Cannonball/TweetListViewController.swift | 1 | 5758 | //
// Copyright (C) 2014 Twitter, Inc. and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import TwitterKit
class TweetListViewController: UITableViewController, TWTRTweetViewDelegate {
var tweets: [TWTRTweet] = [] {
didSet {
tableView.reloadData()
}
}
var prototypeCell: TWTRTweetTableViewCell?
let tweetTableCellReuseIdentifier = "TweetCell"
var isLoadingTweets = false
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Setup the table view.
self.tableView.estimatedRowHeight = 150
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.allowsSelection = false
// Create a single prototype cell for height calculations.
self.prototypeCell = TWTRTweetTableViewCell(style: .Default, reuseIdentifier: tweetTableCellReuseIdentifier)
// Register the identifier for TWTRTweetTableViewCell.
self.tableView.registerClass(TWTRTweetTableViewCell.self, forCellReuseIdentifier: tweetTableCellReuseIdentifier)
// Setup the refresh control.
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: Selector("refreshInvoked"), forControlEvents: UIControlEvents.ValueChanged)
// Customize the navigation bar.
self.navigationController?.navigationBar.topItem?.title = ""
// Add a table header.
let headerHeight: CGFloat = 20
let contentHeight = self.view.frame.size.height - headerHeight
let navHeight = self.navigationController?.navigationBar.frame.height
let navYOrigin = self.navigationController?.navigationBar.frame.origin.y
self.tableView.tableHeaderView = UIView(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, headerHeight))
// Add an initial offset to the table view to show the animated refresh control.
let refreshControlOffset = self.refreshControl?.frame.size.height
self.tableView.frame.origin.y += refreshControlOffset!
self.refreshControl?.beginRefreshing()
// Trigger an initial Tweet load.
loadTweets()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Make sure the navigation bar is not translucent when scrolling the table view.
self.navigationController?.navigationBar.translucent = false
}
func loadTweets() {
// Do not trigger another request if one is already in progress.
if self.isLoadingTweets {
return
}
self.isLoadingTweets = true
// Search for poems on Twitter by performing an API request.
Twitter.sharedInstance().APIClient.searchPoemTweets() { poemSearchResult in
switch poemSearchResult {
case let .Tweets(tweets):
// Add Tweets objects from the JSON data.
self.tweets = tweets
case let .Error(error):
println("Error searching tweets: \(error)")
}
// End the refresh indicator.
self.refreshControl?.endRefreshing()
// Update the boolean since we are no longer loading Tweets.
self.isLoadingTweets = false
}
}
func refreshInvoked() {
// Trigger a load for the most recent Tweets.
loadTweets()
}
// MARK: TWTRTweetViewDelegate
func tweetView(tweetView: TWTRTweetView!, didSelectTweet tweet: TWTRTweet!) {
// Display a Web View when selecting the Tweet.
let webViewController = UIViewController()
let webView = UIWebView(frame: webViewController.view.bounds)
webView.loadRequest(NSURLRequest(URL: tweet.permalink))
webViewController.view = webView
self.navigationController?.pushViewController(webViewController, animated: true)
}
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of Tweets.
return tweets.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Retrieve the Tweet cell.
let cell = tableView.dequeueReusableCellWithIdentifier(tweetTableCellReuseIdentifier, forIndexPath: indexPath) as TWTRTweetTableViewCell
// Assign the delegate to control events on Tweets.
cell.tweetView.delegate = self
// Retrieve the Tweet model from loaded Tweets.
let tweet = tweets[indexPath.row]
// Configure the cell with the Tweet.
cell.configureWithTweet(tweet)
// Return the Tweet cell.
return cell
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let tweet = self.tweets[indexPath.row]
self.prototypeCell?.configureWithTweet(tweet)
if let height = self.prototypeCell?.calculatedHeightForWidth(self.view.bounds.width) {
return height
} else {
return self.tableView.estimatedRowHeight
}
}
}
| apache-2.0 | e85778a0722801f662d556ec58c17fb2 | 35.675159 | 144 | 0.683571 | 5.302026 | false | false | false | false |
justindarc/firefox-ios | Client/Frontend/Library/RecentlyClosedTabsPanel.swift | 1 | 5804 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import XCGLogger
private let log = Logger.browserLogger
private struct RecentlyClosedPanelUX {
static let IconSize = CGSize(width: 23, height: 23)
static let IconBorderColor = UIColor.Photon.Grey30
static let IconBorderWidth: CGFloat = 0.5
}
class RecentlyClosedTabsPanel: UIViewController, LibraryPanel {
weak var libraryPanelDelegate: LibraryPanelDelegate?
let profile: Profile
fileprivate lazy var tableViewController = RecentlyClosedTabsPanelSiteTableViewController(profile: profile)
init(profile: Profile) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.theme.tableView.headerBackground
tableViewController.libraryPanelDelegate = libraryPanelDelegate
tableViewController.recentlyClosedTabsPanel = self
self.addChild(tableViewController)
tableViewController.didMove(toParent: self)
self.view.addSubview(tableViewController.view)
tableViewController.view.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
}
}
class RecentlyClosedTabsPanelSiteTableViewController: SiteTableViewController {
weak var libraryPanelDelegate: LibraryPanelDelegate?
var recentlyClosedTabs: [ClosedTab] = []
weak var recentlyClosedTabsPanel: RecentlyClosedTabsPanel?
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(RecentlyClosedTabsPanelSiteTableViewController.longPress))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
tableView.accessibilityIdentifier = "Recently Closed Tabs List"
self.recentlyClosedTabs = profile.recentlyClosedTabs.tabs
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == .began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
presentContextMenu(for: indexPath)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
guard let twoLineCell = cell as? TwoLineTableViewCell else {
return cell
}
let tab = recentlyClosedTabs[indexPath.row]
let displayURL = tab.url.displayURL ?? tab.url
twoLineCell.setLines(tab.title, detailText: displayURL.absoluteDisplayString)
let site: Favicon? = (tab.faviconURL != nil) ? Favicon(url: tab.faviconURL!) : nil
cell.imageView!.layer.borderColor = RecentlyClosedPanelUX.IconBorderColor.cgColor
cell.imageView!.layer.borderWidth = RecentlyClosedPanelUX.IconBorderWidth
cell.imageView?.setIcon(site, forURL: displayURL, completed: { (color, url) in
if url == displayURL {
cell.imageView?.image = cell.imageView?.image?.createScaled(RecentlyClosedPanelUX.IconSize)
cell.imageView?.contentMode = .center
cell.imageView?.backgroundColor = color
}
})
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let libraryPanelDelegate = libraryPanelDelegate else {
log.warning("No site or no URL when selecting row.")
return
}
let visitType = VisitType.typed // Means History, too.
libraryPanelDelegate.libraryPanel(didSelectURL: recentlyClosedTabs[indexPath.row].url, visitType: visitType)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
// Functions that deal with showing header rows.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return profile.recentlyClosedTabs.tabs.count
}
}
extension RecentlyClosedTabsPanelSiteTableViewController: LibraryPanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
let closedTab = recentlyClosedTabs[indexPath.row]
let site: Site
if let title = closedTab.title {
site = Site(url: String(describing: closedTab.url), title: title)
} else {
site = Site(url: String(describing: closedTab.url), title: "")
}
return site
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
return getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate)
}
}
extension RecentlyClosedTabsPanel: Themeable {
func applyTheme() {
tableViewController.tableView.reloadData()
}
}
| mpl-2.0 | 0fb3c5ab21b6914a72a5fe8fdae2cd8c | 38.482993 | 134 | 0.706926 | 5.31989 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/General/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallBeat.swift | 66 | 2210 | //
// NVActivityIndicatorAnimationBallBeat.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/24/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationBallBeat: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - circleSize) / 2
let duration: CFTimeInterval = 0.7
let beginTime = CACurrentMediaTime()
let beginTimes = [0.35, 0, 0.35]
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.75, 1]
scaleAnimation.duration = duration
// Opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0, 0.5, 1]
opacityAnimation.values = [1, 0.2, 1]
opacityAnimation.duration = duration
// Aniamtion
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
// Draw circles
for var i = 0; i < 3; i++ {
let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
y: y,
width: circleSize,
height: circleSize)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
| apache-2.0 | 93b139507b5748719a56f3a1a5835401 | 36.457627 | 139 | 0.621267 | 5.045662 | false | false | false | false |
PANDA-Guide/PandaGuideApp | PandaGuide/CameraViewController.swift | 1 | 19043 | //
// CameraViewController.swift
// PandaGuide
//
// Created by Pierre Dulac on 31/05/2017.
// Copyright © 2017 ESTHESIX. All rights reserved.
//
import UIKit
import AVFoundation
protocol CameraViewControllerDelegate: class {
/**
@discussion called when the takePhoto() function is called.
*/
func camera(viewController: CameraViewController, didTake photo: UIImage)
/**
@discussion called when SwiftyCamViewController view is tapped and begins focusing at that point.
*/
func camera(viewController: CameraViewController, didFocusAtPoint point: CGPoint)
}
fileprivate class PreviewView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.black
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}
var session: AVCaptureSession? {
get {
return videoPreviewLayer.session
}
set {
videoPreviewLayer.session = newValue
}
}
// MARK: UIView
override class var layerClass : AnyClass {
return AVCaptureVideoPreviewLayer.self
}
}
class CameraViewController: UIViewController {
// MARK: Enumeration Declaration
public enum CameraSelection {
case rear
case front
}
/**
Result from the AVCaptureSession Setup
- success: success
- notAuthorized: User denied access to Camera of Microphone
- configurationFailed: Unknown error
*/
fileprivate enum SessionSetupResult {
case undetermined
case success
case notAuthorized
case configurationFailed
}
// MARK: Public Variable Declarations
weak var cameraDelegate: CameraViewControllerDelegate?
var flashEnabled = false
var tapToFocus = true
var lowLightBoost = true // NB: Only supported on iPhone 5 and 5C
var defaultCamera = CameraSelection.rear
var shouldUseDeviceOrientation = true
// MARK: Public Get-only Variable Declarations
private(set) public var isSessionRunning = false
private(set) public var currentCamera = CameraSelection.rear
// MARK: Private Properties
fileprivate let session = AVCaptureSession()
fileprivate let sessionQueue = DispatchQueue(label: "session queue", attributes: [])
fileprivate var setupResult: SessionSetupResult = .undetermined
fileprivate var videoDeviceInput: AVCaptureDeviceInput?
fileprivate let photoOutput = AVCapturePhotoOutput()
fileprivate let defaultPhotoSettings = AVCapturePhotoSettings()
fileprivate var videoDevice: AVCaptureDevice?
fileprivate let previewLayer = PreviewView(frame: .zero)
fileprivate var isCameraTorchOn = false
fileprivate var flashView: UIView?
fileprivate var previousPanTranslation: CGFloat = 0.0
fileprivate var deviceOrientation: UIDeviceOrientation?
// MARK: View life cycle
override var shouldAutorotate: Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
previewLayer.frame = view.bounds
addGestureRecognizersTo(view: previewLayer)
self.view.addSubview(previewLayer)
previewLayer.session = session
// Test authorization status for Camera
switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo){
case .authorized:
// already authorized
break
case .notDetermined:
// not yet determined
sessionQueue.suspend()
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self] granted in
if !granted {
self.setupResult = .notAuthorized
}
self.sessionQueue.resume()
})
default:
// already been asked. Denied access
setupResult = .notAuthorized
}
sessionQueue.async { [unowned self] in
self.configureSession()
}
}
override func viewDidLayoutSubviews() {
previewLayer.frame = view.bounds
super.viewDidLayoutSubviews()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if shouldUseDeviceOrientation {
subscribeToDeviceOrientationChangeNotifications()
}
sessionQueue.async {
switch self.setupResult {
case .undetermined:
NSLog("Should not happen, it means session configuration wasn't triggered yet")
return
case .success:
self.session.startRunning()
self.isSessionRunning = self.session.isRunning
// Preview layer video orientation can be set only after the connection is created
DispatchQueue.main.async {
self.previewLayer.videoPreviewLayer.connection?.videoOrientation = self.getPreviewLayerOrientation()
}
case .notAuthorized:
self.promptToAppSettings()
case .configurationFailed:
DispatchQueue.main.async(execute: { [unowned self] in
let message = NSLocalizedString("Unable to capture media", comment: "Alert message when something goes wrong during capture session configuration")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
})
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// If session is running, stop the session
if self.isSessionRunning == true {
self.session.stopRunning()
self.isSessionRunning = false
}
disableFlash()
if shouldUseDeviceOrientation {
unsubscribeFromDeviceOrientationChangeNotifications()
}
}
// MARK: Public Functions
/**
Capture photo from current session
*/
func takePhoto() {
guard let device = videoDevice else {
return
}
if device.hasFlash == true && flashEnabled == true /* TODO: Add Support for Retina Flash and add front flash */ {
changeFlashSettings(device: device, mode: .on)
capturePhoto()
} else {
if photoOutput.isFlashScene {
changeFlashSettings(device: device, mode: .off)
}
capturePhoto()
}
}
// MARK: Private Functions
fileprivate func configureSession() {
guard setupResult == .undetermined else {
return
}
// Set default camera
currentCamera = defaultCamera
// begin configuring session
session.beginConfiguration()
configureSessionPreset()
addVideoInput()
configurePhotoOutput()
session.commitConfiguration()
setupResult = .success
}
fileprivate func configureSessionPreset() {
session.sessionPreset = AVCaptureSessionPresetPhoto
}
fileprivate func addVideoInput() {
switch currentCamera {
case .front:
videoDevice = CameraViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .front)
case .rear:
videoDevice = CameraViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .back)
}
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusModeSupported(.continuousAutoFocus) {
device.focusMode = .continuousAutoFocus
if device.isSmoothAutoFocusSupported {
device.isSmoothAutoFocusEnabled = true
}
}
if device.isExposureModeSupported(.continuousAutoExposure) {
device.exposureMode = .continuousAutoExposure
}
if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) {
device.whiteBalanceMode = .continuousAutoWhiteBalance
}
// if device.isLowLightBoostSupported && lowLightBoost == true {
// device.automaticallyEnablesLowLightBoostWhenAvailable = true
// }
device.unlockForConfiguration()
} catch {
print("Error locking configuration")
}
}
do {
let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
if session.canAddInput(videoDeviceInput) {
session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
} else {
NSLog("Could not add video device input to the session")
setupResult = .configurationFailed
session.commitConfiguration()
return
}
} catch {
print("Could not create video device input: \(error)")
setupResult = .configurationFailed
return
}
}
fileprivate func configurePhotoOutput() {
if session.canAddOutput(photoOutput) {
session.addOutput(photoOutput)
// configure high res on the pipeline
photoOutput.isHighResolutionCaptureEnabled = true
if photoOutput.isHighResolutionCaptureEnabled {
defaultPhotoSettings.isHighResolutionPhotoEnabled = true
print("🌁 High resolution photo output")
} else {
print("🌁 Standard resolution photo output")
}
}
}
fileprivate func subscribeToDeviceOrientationChangeNotifications() {
self.deviceOrientation = UIDevice.current.orientation
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
fileprivate func unsubscribeFromDeviceOrientationChangeNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
self.deviceOrientation = nil
}
@objc fileprivate func deviceDidRotate() {
if !UIDevice.current.orientation.isFlat {
self.deviceOrientation = UIDevice.current.orientation
}
}
fileprivate func getPreviewLayerOrientation() -> AVCaptureVideoOrientation {
// Depends on layout orientation, not device orientation
switch UIApplication.shared.statusBarOrientation {
case .portrait, .unknown:
return AVCaptureVideoOrientation.portrait
case .landscapeLeft:
return AVCaptureVideoOrientation.landscapeLeft
case .landscapeRight:
return AVCaptureVideoOrientation.landscapeRight
case .portraitUpsideDown:
return AVCaptureVideoOrientation.portraitUpsideDown
}
}
fileprivate func getVideoOrientation() -> AVCaptureVideoOrientation {
guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return previewLayer.videoPreviewLayer.connection.videoOrientation }
switch deviceOrientation {
case .landscapeLeft:
return .landscapeRight
case .landscapeRight:
return .landscapeLeft
case .portraitUpsideDown:
return .portraitUpsideDown
default:
return .portrait
}
}
fileprivate func getImageOrientation(forCamera: CameraSelection) -> UIImageOrientation {
guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return forCamera == .rear ? .right : .leftMirrored }
switch deviceOrientation {
case .landscapeLeft:
return forCamera == .rear ? .up : .downMirrored
case .landscapeRight:
return forCamera == .rear ? .down : .upMirrored
case .portraitUpsideDown:
return forCamera == .rear ? .left : .rightMirrored
default:
return forCamera == .rear ? .right : .leftMirrored
}
}
fileprivate func capturePhoto() {
let photoSettings = AVCapturePhotoSettings(from: defaultPhotoSettings)
photoOutput.capturePhoto(with: photoSettings, delegate: self)
}
fileprivate func promptToAppSettings() {
// prompt User with UIAlertView
DispatchQueue.main.async(execute: { [unowned self] in
let message = NSLocalizedString("AVCam doesn't have permission to use the camera, please change privacy settings", comment: "Alert message when the user has denied access to the camera")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Settings", comment: "Alert button to open Settings"), style: .default, handler: { action in
if #available(iOS 10.0, *) {
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
} else {
if let appSettings = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(appSettings)
}
}
}))
self.present(alertController, animated: true, completion: nil)
})
}
fileprivate class func deviceWithMediaType(_ mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? {
if let devices = AVCaptureDevice.devices(withMediaType: mediaType) as? [AVCaptureDevice] {
return devices.filter({ $0.position == position }).first
}
return nil
}
fileprivate func changeFlashSettings(device: AVCaptureDevice, mode: AVCaptureFlashMode) {
do {
try device.lockForConfiguration()
device.flashMode = mode
device.unlockForConfiguration()
} catch {
print("\(error)")
}
}
fileprivate func enableFlash() {
if self.isCameraTorchOn == false {
toggleFlash()
}
}
fileprivate func disableFlash() {
if self.isCameraTorchOn == true {
toggleFlash()
}
}
fileprivate func toggleFlash() {
guard self.currentCamera == .rear else {
// Flash is not supported for front facing camera
return
}
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
// Check if device has a flash
if (device?.hasTorch)! {
do {
try device?.lockForConfiguration()
if (device?.torchMode == AVCaptureTorchMode.on) {
device?.torchMode = AVCaptureTorchMode.off
self.isCameraTorchOn = false
} else {
do {
try device?.setTorchModeOnWithLevel(1.0)
self.isCameraTorchOn = true
} catch {
print("\(error)")
}
}
device?.unlockForConfiguration()
} catch {
print("\(error)")
}
}
}
}
extension CameraViewController : CameraButtonDelegate {
func buttonWasTapped() {
takePhoto()
}
}
extension CameraViewController : AVCapturePhotoCaptureDelegate {
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
if let error = error {
NSLog(error.localizedDescription)
return
}
guard let sampleBuffer = photoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer) else {
NSLog("Failed to convert buffer into data representation")
return
}
guard let capturedImage = UIImage(data: dataImage) else {
NSLog("Failed to convert buffer into an UIImage instance")
return
}
cameraDelegate?.camera(viewController: self, didTake: capturedImage)
}
}
extension CameraViewController {
@objc fileprivate func singleTapGesture(tap: UITapGestureRecognizer) {
guard tapToFocus == true else {
// Ignore taps
return
}
let screenSize = previewLayer.bounds.size
let tapPoint = tap.location(in: previewLayer)
let x = tapPoint.y / screenSize.height
let y = 1.0 - tapPoint.x / screenSize.width
let focusPoint = CGPoint(x: x, y: y)
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusPointOfInterestSupported == true {
device.focusPointOfInterest = focusPoint
device.focusMode = .autoFocus
}
device.exposurePointOfInterest = focusPoint
device.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device.unlockForConfiguration()
//Call delegate function and pass in the location of the touch
DispatchQueue.main.async {
self.cameraDelegate?.camera(viewController: self, didFocusAtPoint: tapPoint)
}
}
catch {
// just ignore
}
}
}
fileprivate func addGestureRecognizersTo(view: UIView) {
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTapGesture(tap:)))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.delegate = self
view.addGestureRecognizer(singleTapGesture)
}
}
extension CameraViewController : UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| gpl-3.0 | bec740795e1d97c36636dfca041f6c8f | 32.632509 | 294 | 0.627338 | 6.045094 | false | false | false | false |
toshi0383/TVMLKitchen | MoviePlaybackSample/AppDelegate.swift | 1 | 2763 | //
// AppDelegate.swift
// MoviePlaybackSample
//
// Created by toshi0383 on 2017/01/05.
// Copyright © 2017 toshi0383. All rights reserved.
//
import AVKit
import UIKit
import TVMLKitchen
/// Custom Action struct
struct Action {
private let f: (()->())
func run() {
f()
}
/// Parse string to a function.
/// Returns nil if the parameter does not match expectation.
/// - parameter string: comma separated string
init?(string: String) {
let ss = string.components(separatedBy: ",")
guard ss.count == 2 else {
return nil
}
switch ss[0] {
case "playbackURL":
guard let url = URL(string: ss[1]) else {
return nil
}
self.f = {
startPlayback(url: url)
}
default:
return nil
}
}
}
func startPlayback(url: URL) {
DispatchQueue.global().async {
let vc = AVPlayerViewController()
/*
This is extremely expensive if url points at monolithic mp4.
So we're doing this in background.
You should do like this if you need to handle error case.
```
let asset = AVURLAsset(url: url)
asset.loadValuesAsynchronously(forKeys: [playableKey, statusKey]) {
// start playback
}
```
*/
vc.player = AVPlayer(url: url)
DispatchQueue.main.async {
// Navigation should be in main thread.
Kitchen.navigationController.pushViewController(vc, animated: true)
}
}
}
private func xmlString() -> String {
guard let url = Bundle.main.url(forResource: "sample", withExtension: "xml"),
let data = try? Data(contentsOf: url) else {
fatalError()
}
return String(data: data, encoding: .utf8)!
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let cookbook = Cookbook(launchOptions: launchOptions)
cookbook.actionIDHandler = {
actionID in
// actionID can be any string.
// In this sample, we're expecting comma separated string.
if let action = Action(string: actionID) {
action.run()
}
}
// This callback is triggered by `play/pause` button.
cookbook.playActionIDHandler = {
playActionID in
if let action = Action(string: playActionID) {
action.run()
}
}
Kitchen.prepare(cookbook)
Kitchen.serve(xmlString: xmlString())
return true
}
}
| mit | 53df9159e17e37e0d7db81b95bdab18e | 27.183673 | 144 | 0.57929 | 4.657673 | false | false | false | false |
Piwigo/Piwigo-Mobile | Supporting Targets/piwigoAppStore/piwigoAppStore.swift | 1 | 27902 | //
// piwigoUITests.swift
// piwigoUITests
//
// Created by Eddy Lelièvre-Berna on 25/08/2018.
// Copyright © 2018 Piwigo.org. All rights reserved.
//
import XCTest
public enum Model : String {
case simulator = "simulator/sandbox",
//iPod
iPod1 = "iPod 1",
iPod2 = "iPod 2",
iPod3 = "iPod 3",
iPod4 = "iPod 4",
iPod5 = "iPod 5",
iPod6 = "iPod 6",
iPod7 = "iPod touch (6th generation)",
iPod8 = "iPod touch (7th generation)",
//iPad
iPad2 = "iPad 2",
iPad3 = "iPad 3",
iPad4 = "iPad 4",
iPadAir = "iPad Air ",
iPadAir2 = "iPad Air 2",
iPad5 = "iPad 5", //aka iPad 2017
iPad6 = "iPad 6", //aka iPad 2018
iPad7 = "iPad 7", //aka iPad 2019
iPad8 = "iPad (8th generation)",
iPad9 = "iPad (9th generation)",
iPadAir4 = "iPad Air 4",
//iPad mini
iPadMini = "iPad Mini",
iPadMini2 = "iPad Mini 2",
iPadMini3 = "iPad Mini 3",
iPadMini4 = "iPad Mini 4",
iPadMini5 = "iPad mini (5th generation)",
iPadMini6 = "iPad mini (6th generation)",
//iPad pro
iPadPro9_7 = "iPad Pro 9.7\"",
iPadPro10_5 = "iPad Pro 10.5\"",
iPadPro11 = "iPad Pro 11\"",
iPadPro12_9 = "iPad Pro 12.9\"",
iPadPro2_12_9 = "iPad Pro 2 12.9\"",
iPadPro3_12_9 = "iPad Pro 3 12.9\"",
iPadPro2_11 = "iPad Pro 2 11\"",
iPadPro4_12_9 = "iPad Pro 4 12.9\"",
iPadPro3_11 = "iPad Pro 3 11\"",
iPadPro5_12_9 = "iPad Pro 5 12.9\"",
//iPhone
iPhone4 = "iPhone 4",
iPhone4S = "iPhone 4S",
iPhone5 = "iPhone 5",
iPhone5S = "iPhone 5S",
iPhone5C = "iPhone 5C",
iPhone6 = "iPhone 6",
iPhone6plus = "iPhone 6 Plus",
iPhone6S = "iPhone 6S",
iPhone6Splus = "iPhone 6S Plus",
iPhoneSE = "iPhone SE",
iPhone7 = "iPhone 7",
iPhone7plus = "iPhone 7 Plus",
iPhone8 = "iPhone 8",
iPhone8plus = "iPhone 8 Plus",
iPhoneX = "iPhone X",
iPhoneXs = "iPhone XS",
iPhoneXsMax = "iPhone XS Max",
iPhoneXr = "iPhone XR",
iPhone11 = "iPhone 11",
iPhone11Pro = "iPhone 11 Pro",
iPhone11ProMax = "iPhone 11 Pro Max",
iPhoneSE2 = "iPhone SE 2",
iPhone12mini = "iPhone 12 mini",
iPhone12 = "iPhone 12",
iPhone12Pro = "iPhone 12 Pro",
iPhone12ProMax = "iPhone 12 Pro Max",
iPhone13mini = "iPhone 13 mini",
iPhone13 = "iPhone 13",
iPhone13Pro = "iPhone 13 Pro",
iPhone13ProMax = "iPhone 13 Pro Max",
//Apple TV
AppleTV = "Apple TV",
AppleTV_4K = "Apple TV 4K",
unrecognized = "?unrecognized?"
}
// #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
// MARK: UIDevice extensions
// #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
public extension UIDevice {
var type: Model {
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafePointer(to: &systemInfo.machine) {
$0.withMemoryRebound(to: CChar.self, capacity: 1) {
ptr in String(validatingUTF8: ptr)
}
}
let modelMap : [ String : Model ] = [
"i386" : .simulator,
"x86_64" : .simulator,
//iPod
"iPod1,1" : .iPod1,
"iPod2,1" : .iPod2,
"iPod3,1" : .iPod3,
"iPod4,1" : .iPod4,
"iPod5,1" : .iPod5,
"iPod6,1" : .iPod6,
"iPod7,1" : .iPod7,
"iPod9,1" : .iPod8,
//iPad
"iPad2,1" : .iPad2,
"iPad2,2" : .iPad2,
"iPad2,3" : .iPad2,
"iPad2,4" : .iPad2,
"iPad3,1" : .iPad3,
"iPad3,2" : .iPad3,
"iPad3,3" : .iPad3,
"iPad3,4" : .iPad4,
"iPad3,5" : .iPad4,
"iPad3,6" : .iPad4,
"iPad6,11" : .iPad5, //aka iPad 2017
"iPad6,12" : .iPad5,
"iPad7,5" : .iPad6, //aka iPad 2018
"iPad7,6" : .iPad6,
"iPad7,11" : .iPad7, //aka iPad 2019
"iPad7,12" : .iPad7,
"iPad11,6" : .iPad8,
"iPad11,7" : .iPad8,
"iPad12,1" : .iPad9,
"iPad12,2" : .iPad9,
//iPad mini
"iPad2,5" : .iPadMini,
"iPad2,6" : .iPadMini,
"iPad2,7" : .iPadMini,
"iPad4,4" : .iPadMini2,
"iPad4,5" : .iPadMini2,
"iPad4,6" : .iPadMini2,
"iPad4,7" : .iPadMini3,
"iPad4,8" : .iPadMini3,
"iPad4,9" : .iPadMini3,
"iPad5,1" : .iPadMini4,
"iPad5,2" : .iPadMini4,
"iPad11,1" : .iPadMini5,
"iPad11,2" : .iPadMini5,
"iPad14,1" : .iPadMini6,
"iPad14,2" : .iPadMini6,
//iPad Air
"iPad4,1" : .iPadAir,
"iPad4,2" : .iPadAir,
"iPad4,3" : .iPadAir,
"iPad5,3" : .iPadAir2,
"iPad5,4" : .iPadAir2,
"iPad13,1" : .iPadAir4,
"iPad13,2" : .iPadAir4,
//iPad Pro
"iPad6,3" : .iPadPro9_7,
"iPad6,4" : .iPadPro9_7,
"iPad7,3" : .iPadPro10_5,
"iPad7,4" : .iPadPro10_5,
"iPad8,1" : .iPadPro11,
"iPad8,2" : .iPadPro11,
"iPad8,3" : .iPadPro11,
"iPad8,4" : .iPadPro11,
"iPad6,7" : .iPadPro12_9,
"iPad6,8" : .iPadPro12_9,
"iPad7,1" : .iPadPro2_12_9,
"iPad7,2" : .iPadPro2_12_9,
"iPad8,5" : .iPadPro3_12_9,
"iPad8,6" : .iPadPro3_12_9,
"iPad8,7" : .iPadPro3_12_9,
"iPad8,8" : .iPadPro3_12_9,
"iPad8,9" : .iPadPro2_11,
"iPad8,10" : .iPadPro2_11,
"iPad8,11" : .iPadPro4_12_9,
"iPad8,12" : .iPadPro4_12_9,
"iPad13,4" : .iPadPro3_11,
"iPad13,5" : .iPadPro3_11,
"iPad13,6" : .iPadPro3_11,
"iPad13,7" : .iPadPro3_11,
"iPad13,8" : .iPadPro5_12_9,
"iPad13,9" : .iPadPro5_12_9,
"iPad13,10" : .iPadPro5_12_9,
"iPad13,11" : .iPadPro5_12_9,
//iPhone
"iPhone3,1" : .iPhone4,
"iPhone3,2" : .iPhone4,
"iPhone3,3" : .iPhone4,
"iPhone4,1" : .iPhone4S,
"iPhone5,1" : .iPhone5,
"iPhone5,2" : .iPhone5,
"iPhone5,3" : .iPhone5C,
"iPhone5,4" : .iPhone5C,
"iPhone6,1" : .iPhone5S,
"iPhone6,2" : .iPhone5S,
"iPhone7,1" : .iPhone6plus,
"iPhone7,2" : .iPhone6,
"iPhone8,1" : .iPhone6S,
"iPhone8,2" : .iPhone6Splus,
"iPhone8,4" : .iPhoneSE,
"iPhone9,1" : .iPhone7,
"iPhone9,3" : .iPhone7,
"iPhone9,2" : .iPhone7plus,
"iPhone9,4" : .iPhone7plus,
"iPhone10,1" : .iPhone8,
"iPhone10,4" : .iPhone8,
"iPhone10,2" : .iPhone8plus,
"iPhone10,5" : .iPhone8plus,
"iPhone10,3" : .iPhoneX,
"iPhone10,6" : .iPhoneX,
"iPhone11,2" : .iPhoneXs,
"iPhone11,4" : .iPhoneXsMax,
"iPhone11,6" : .iPhoneXsMax,
"iPhone11,8" : .iPhoneXr,
"iPhone12,1" : .iPhone11,
"iPhone12,3" : .iPhone11Pro,
"iPhone12,5" : .iPhone11ProMax,
"iPhone12,8" : .iPhoneSE2,
"iPhone13,1" : .iPhone12mini,
"iPhone13,2" : .iPhone12,
"iPhone13,3" : .iPhone12Pro,
"iPhone13,4" : .iPhone12ProMax,
"iPhone14,2" : .iPhone13Pro,
"iPhone14,3" : .iPhone13ProMax,
"iPhone14,4" : .iPhone13mini,
"iPhone14,5" : .iPhone13,
//AppleTV
"AppleTV5,3" : .AppleTV,
"AppleTV6,2" : .AppleTV_4K
]
if let model = modelMap[String(validatingUTF8: modelCode!)!] {
if model == .simulator {
if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
if let simModel = modelMap[String(validatingUTF8: simModelCode)!] {
return simModel
}
}
}
return model
}
return Model.unrecognized
}
}
class piwigoAppStore: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
let app = XCUIApplication()
setupSnapshot(app)
app.launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
XCUIDevice.shared.orientation = UIDeviceOrientation.portrait
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// MARK: - Prepare Screenshots
func testScreenshots() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let app = XCUIApplication()
let deviceType = UIDevice().type.rawValue
sleep(5);
// Select Photos Title A->Z sort order
app.navigationBars.element(boundBy: 0).buttons["settings"].tap()
sleep(1);
app.tables["settings"].cells["defaultSort"].tap()
app.tables["sortSelect"].cells.element(boundBy: 0).tap()
app.navigationBars["CategorySortBar"].buttons.element(boundBy: 0).tap()
app.navigationBars.buttons["Done"].tap()
// Screenshot #1: swipe left and reveal album actions
var index = 1
if deviceType.hasPrefix("iPad") {
index = 7
}
let collectionCell = app.collectionViews.children(matching: .cell).element(boundBy: index)
let tableQuery = collectionCell.children(matching: .other).element.tables.element(boundBy: 0)
sleep(4);
tableQuery/*@START_MENU_TOKEN@*/.staticTexts["comment"]/*[[".cells[\"albumName, comment, nberImages\"].staticTexts[\"comment\"]",".staticTexts[\"comment\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.swipeLeft()
snapshot("Image01")
// Screenshot #2: collection of images with titles
app.collectionViews.children(matching: .cell).element(boundBy: 2).tap()
sleep(2);
if deviceType.hasPrefix("iPhone") {
app.collectionViews.children(matching: .cell).element(boundBy: 0).swipeUp()
sleep(2);
}
snapshot("Image02")
// Screenshot #3: collection with selected images
app.buttons["rootAlbum"].tap()
app.buttons["settings"].tap()
sleep(2);
app.tables["settings"].cells["server"].swipeUp()
sleep(2);
app.tables["settings"].cells["displayImageTitles"].switches["switchImageTitles"].tap()
app.navigationBars.buttons["Done"].tap()
sleep(1);
app.collectionViews.children(matching: .cell).element(boundBy: 2).tap()
sleep(1);
if deviceType.hasPrefix("iPhone") {
app.collectionViews.children(matching: .cell).element(boundBy: 0).swipeUp()
sleep(2);
}
for i in 1...6 {
app.collectionViews.children(matching: .cell).element(boundBy: i).swipeUp(velocity: 200)
sleep(1)
}
app.collectionViews.children(matching: .cell).element(boundBy: 6).swipeUp(velocity: 50)
sleep(3);
app.navigationBars.buttons["Select"].tap()
if deviceType.hasPrefix("iPhone") {
app.collectionViews.children(matching: .cell).element(boundBy: 16).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 21).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 20).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 19).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 17).tap()
} else {
if (deviceType == "iPad Pro 9.7\"") {
app.collectionViews.children(matching: .cell).element(boundBy: 16).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 24).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 23).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 22).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 21).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 20).tap()
} else {
app.collectionViews.children(matching: .cell).element(boundBy: 20).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 21).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 22).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 31).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 30).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 29).tap()
app.collectionViews.children(matching: .cell).element(boundBy: 28).tap()
}
}
snapshot("Image03")
// Screenshot #4: image previewed
app.navigationBars.buttons["Cancel"].tap()
sleep(1);
if deviceType.contains("iPhone SE") {
app.collectionViews.children(matching: .cell).element(boundBy: 19).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.1, velocity: 2.0)
app.images.element(boundBy: 0).pinch(withScale: 0.6, velocity: -2.0)
}
else if deviceType == "iPhone 8" {
app.collectionViews.children(matching: .cell).element(boundBy: 19).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.1, velocity: 2.0)
app.images.element(boundBy: 0).pinch(withScale: 0.52, velocity: -2.0)
}
else if deviceType == "iPhone 8 Plus" {
app.collectionViews.children(matching: .cell).element(boundBy: 19).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.1, velocity: 2.0)
app.images.element(boundBy: 0).pinch(withScale: 0.59, velocity: -2.0)
}
else if ["iPhone 11 Pro", "iPhone 13 Pro"].contains(deviceType) {
app.collectionViews.children(matching: .cell).element(boundBy: 19).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.1, velocity: 2.0)
app.images.element(boundBy: 0).pinch(withScale: 0.675, velocity: -2.0)
}
else if deviceType == "iPhone 11 Pro Max" {
app.collectionViews.children(matching: .cell).element(boundBy: 19).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.1, velocity: 2.0)
app.images.element(boundBy: 0).pinch(withScale: 0.675, velocity: -2.0)
}
else if deviceType == "iPad Pro 9.7\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 26).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 10.5\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 26).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 3 11\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 26).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 2 12.9\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 20).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 3 12.9\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 20).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
sleep(2) // Leave time for animation
app.buttons["actions"].tap()
snapshot("Image04")
// Screenshot #5: Edit parameters
app.collectionViews.buttons["Copy"].tap()
sleep(1) // Leave time for animation
app.navigationBars.buttons["CancelSelect"].tap()
app.navigationBars.buttons.element(boundBy: 0).tap()
sleep(2) // Leave time for animation
if deviceType.contains("iPhone SE") {
app.collectionViews.children(matching: .cell).element(boundBy: 6).tap()
}
else if deviceType == "iPhone 8" {
app.collectionViews.children(matching: .cell).element(boundBy: 6).tap()
}
else if deviceType == "iPhone 8 Plus" {
app.collectionViews.children(matching: .cell).element(boundBy: 6).tap()
}
else if ["iPhone 11 Pro", "iPhone 13 Pro"].contains(deviceType) {
app.collectionViews.children(matching: .cell).element(boundBy: 6).tap()
}
else if deviceType == "iPhone 11 Pro Max" {
app.collectionViews.children(matching: .cell).element(boundBy: 6).tap()
}
else if deviceType == "iPad Pro 9.7\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 12).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 10.5\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 12).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 3 11\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 12).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 2 12.9\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 6).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
else if deviceType == "iPad Pro 3 12.9\"" {
app.collectionViews.children(matching: .cell).element(boundBy: 6).tap()
sleep(2)
app.images.element(boundBy: 0).pinch(withScale: 1.17, velocity: 2.0)
}
sleep(1) // Leave time for animation
app.buttons["actions"].tap()
app.collectionViews.buttons["Edit Parameters"].tap()
sleep(2) // Leave time for animation
snapshot("Image05")
// Screenshot #6: create album & add image buttons
app.buttons["Cancel"].tap()
sleep(2) // Leave time for animation
app.navigationBars.buttons.element(boundBy: 0).tap()
sleep(2) // Leave time for animation
app.collectionViews.children(matching: .cell).element(boundBy: 10).swipeUp()
app.collectionViews.children(matching: .cell).element(boundBy: 10).swipeUp()
app.buttons["add"].tap()
sleep(2) // Leave time for animation
snapshot("Image06")
// app.navigationBars.buttons.element(boundBy: 0).tap()
// sleep(2) // Leave time for animation
// Screenshot #7: local images
app.buttons["addImages"].tap()
sleep(1) // Leave time for animation
app.tables.children(matching: .cell).matching(identifier: "Recent").element.tap()
sleep(1) // Leave time for animation
let images = app.collectionViews.matching(identifier: "CameraRoll").children(matching: .cell)
images.element(boundBy: 0).children(matching: .other).element.tap()
images.element(boundBy: 1).children(matching: .other).element.tap()
images.element(boundBy: 2).children(matching: .other).element.tap()
images.element(boundBy: 3).children(matching: .other).element.tap()
images.element(boundBy: 4).children(matching: .other).element.tap()
images.element(boundBy: 5).children(matching: .other).element.tap()
images.element(boundBy: 6).children(matching: .other).element.tap()
images.element(boundBy: 8).children(matching: .other).element.tap()
let moreButton = app.navigationBars["LocalImagesNav"].buttons["Action"]
moreButton.tap()
app.collectionViews.buttons["Days"].tap()
sleep(1) // Leave time for animation
moreButton.tap()
sleep(1) // Leave time for animation
snapshot("Image07")
// Screenshot #8: upload images, parameters
app.collectionViews.buttons["Days"].tap()
sleep(1) // Leave time for animation
if deviceType.contains("iPhone") {
app.toolbars.buttons["Upload"].tap()
} else {
app.navigationBars["LocalImagesNav"].buttons["Upload"].tap()
}
sleep(1)
snapshot("Image08")
// Screenshot #9: upload images, settings
app.navigationBars["UploadSwitchView"]/*@START_MENU_TOKEN@*/.buttons["settings"]/*[[".segmentedControls.buttons[\"settings\"]",".buttons[\"settings\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
sleep(1)
snapshot("Image09")
// Screenshot #10: settings
app.navigationBars["UploadSwitchView"].buttons["Cancel"].tap()
let localimagesnavNavigationBar = app.navigationBars["LocalImagesNav"]
localimagesnavNavigationBar.buttons.element(boundBy: 0).tap()
sleep(1) // Leave time for animation
localimagesnavNavigationBar.buttons.element(boundBy: 0).tap()
app.navigationBars["LocalAlbumsNav"].buttons["Cancel"].tap()
app.buttons["rootAlbum"].tap()
sleep(1) // Leave time for animation
app.buttons["settings"].tap()
sleep(1) // Leave time for animation
app.tables["settings"].cells["server"].swipeUp()
sleep(2) // Leave time for animation
app.tables["settings"].cells["displayImageTitles"].switches["switchImageTitles"].tap()
snapshot("Image10")
}
// MARK: - Prepare Video
func testVideoUpload() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let app = XCUIApplication()
let deviceType = UIDevice().type.rawValue
sleep(3);
// Create "Delft" album
app.buttons["add"].tap()
sleep(1) // Leave time for animation
app.typeText("Delft")
app.alerts["CreateAlbum"].scrollViews.otherElements.buttons["Add"].tap()
sleep(2) // Leave time for animation
// Open "Delft" album
app.collectionViews.children(matching: .cell).element(boundBy: 0).tap()
sleep(1);
// Start uploading photos
app.buttons["add"].tap()
app/*@START_MENU_TOKEN@*/.buttons["addImages"]/*[[".buttons[\"imageUpload\"]",".buttons[\"addImages\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
sleep(1) // Leave time for animation
// Select Recent album
app.tables.children(matching: .cell).matching(identifier: "Recent").element.tap()
sleep(1) // Leave time for animation
// Sort photos by days
let moreButton = app.navigationBars["LocalImagesNav"].buttons["Action"]
moreButton.tap()
sleep(1) // Leave time for animation
app.collectionViews.buttons["Days"].tap()
sleep(1) // Leave time for animation
// Select photos taken the first day
app.collectionViews["CameraRoll"].children(matching: .other).element(boundBy: 0).buttons["SelectAll"].tap()
// Display upload settings
if deviceType.contains("iPhone") {
app.toolbars.buttons["Upload"].tap()
} else {
app.navigationBars["LocalImagesNav"].buttons["Upload"].tap()
}
sleep(1) // Leave time for animation
// Select tag
app.tables["Parameters"].cells["setTags"].tap()
app.tables/*@START_MENU_TOKEN@*/.staticTexts["Cities"]/*[[".cells.staticTexts[\"Cities\"]",".staticTexts[\"Cities\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
app.navigationBars["UploadSwitchView"].buttons["Back"].tap()
sleep(1)
// Check upload settings
app.navigationBars["UploadSwitchView"]/*@START_MENU_TOKEN@*/.buttons["settings"]/*[[".segmentedControls.buttons[\"settings\"]",".buttons[\"settings\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
sleep(1)
// Upload photos
app.navigationBars["UploadSwitchView"].buttons["Upload"].tap()
sleep(3)
// Return to album
app.navigationBars["LocalImagesNav"].buttons["Photo Library"].tap()
app.navigationBars["LocalAlbumsNav"].buttons["Cancel"].tap()
sleep(2)
// Return to root
app.buttons["rootAlbum"].tap()
sleep(15) // Leave time for animation
// Delete temporary album
let collectionCell = app.collectionViews.children(matching: .cell).element(boundBy: 0)
let tableQuery = collectionCell.children(matching: .other).element.tables.element(boundBy: 0)
tableQuery/*@START_MENU_TOKEN@*/.staticTexts["comment"]/*[[".cells[\"albumName, comment, nberImages\"].staticTexts[\"comment\"]",".staticTexts[\"comment\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.swipeLeft()
tableQuery.buttons["swipeTrash"].tap()
sleep(1) // Leave time for animation
app.sheets["DeleteAlbum"].scrollViews.otherElements.buttons["DeleteAll"].tap()
let elementsQuery = app.alerts["Are you sure?"].scrollViews.otherElements
app.typeText("5")
elementsQuery.buttons["DeleteAll"].tap()
sleep(2) // Leave time for animation
}
}
| mit | 69a1831a89a178d1fdf2b6cbbab42115 | 43.6368 | 218 | 0.538103 | 3.939839 | false | false | false | false |
diegorv/iOS-Swift-TableView-CoreData-Example | iOS-Swift-TableView-CoreData-Example/Item.swift | 1 | 2694 | //
// Item.swift
// iOS-Swift-TableView-CoreData-Example
//
// Created by Diego Rossini Vieira on 9/7/15.
// https://github.com/diegorv/iOS-Swift-TableView-CoreData-Example
//
import Foundation
import CoreData
// MODEL
class Item: NSManagedObject {
@NSManaged var name: String
/// Function to initialize a new Item
convenience init(name: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext: managedObjectContext)!
self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext)
self.name = name
}
/// Function to get all CoreData values
///
/// - parameter managedObjectContext: CoreData Connection
///
class func fetchAll(managedObjectContext: NSManagedObjectContext) -> [Item] {
let listagemCoreData = NSFetchRequest(entityName: "Item")
// Sort alphabetical by field "name"
let orderByName = NSSortDescriptor(key: "name", ascending: true, selector: "caseInsensitiveCompare:")
listagemCoreData.sortDescriptors = [orderByName]
// Get items from CoreData
return (try? managedObjectContext.executeFetchRequest(listagemCoreData)) as? [Item] ?? []
}
/// Function to search item by name
///
/// - parameter name: Item name
/// - parameter managedObjectContext: CoreData Connection
///
class func search(name: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> Item? {
let fetchRequest = NSFetchRequest(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "name = %@", name)
let result = (try? managedObjectContext.executeFetchRequest(fetchRequest)) as? [Item]
return result?.first
}
/// Function to check duplicate item
///
/// - parameter name: Item name
/// - parameter managedObjectContext: CoreData Connection
///
class func checkDuplicate(name: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> Bool {
return search(name, inManagedObjectContext: managedObjectContext) != nil
}
/// Function to delete a item
///
/// - parameter managedObjectContext: CoreData Connection
///
func destroy(managedObjectContext: NSManagedObjectContext) {
managedObjectContext.deleteObject(self)
}
/// Function to save CoreData values
///
/// - parameter managedObjectContext: CoreData Connection
///
func save(managedObjectContext: NSManagedObjectContext) {
do {
try managedObjectContext.save()
}
catch {
let nserror = error as NSError
print("Error on save: \(nserror.debugDescription)")
}
}
}
| mit | f84215a30b2568b790839e7690a13581 | 31.853659 | 122 | 0.712324 | 5.121673 | false | false | false | false |
arkye-8th-semester-indiana-tech/dev_mob_apps | final/CourseTrack/CourseTrack/CourseStore.swift | 1 | 1598 | //
// CourseStore.swift
// CourseTrack
//
// Created by Maia de Moraes, Jonathan H - 01 on 4/21/16.
// Copyright © 2016 Jonathan Henrique Maia de Moraes. All rights reserved.
//
import UIKit
class CourseStore {
var allCourses = [Course]()
let courseArchiveURL: NSURL = {
let documentsDirectories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = documentsDirectories.first!
return documentDirectory.URLByAppendingPathComponent("items.archive")
}()
init() {
if let archivedCourses = NSKeyedUnarchiver.unarchiveObjectWithFile(courseArchiveURL.path!) as? [Course] {
allCourses += archivedCourses
}
}
func createCourse() -> Course {
let newCourse = Course(name: "Name", number: "Course Number", grade: "C")
allCourses.append(newCourse)
return newCourse
}
func removeCourse(course: Course) {
if let index = allCourses.indexOf(course) {
allCourses.removeAtIndex(index)
}
}
func moveCourseAtIndex(fromIndex: Int, toIndex: Int) {
if fromIndex != toIndex {
let movedCourse = allCourses[fromIndex]
allCourses.removeAtIndex(fromIndex)
allCourses.insert(movedCourse, atIndex: toIndex)
}
}
func saveChanges() -> Bool {
print("Saving items to: \(courseArchiveURL.path!)")
return NSKeyedArchiver.archiveRootObject(allCourses, toFile: courseArchiveURL.path!)
}
}
| gpl-3.0 | 11b33a0e9936eb5e439ee868fd1a7597 | 29.711538 | 130 | 0.640576 | 4.767164 | false | false | false | false |
nekrich/GlobalMessageService-iOS | Source/Core/GlobalMessageService+Localization.swift | 1 | 1975 | //
// GlobalMessageService+Localization.swift
// GlobalMessageService
//
// Created by Vitalii Budnik on 3/28/16.
// Copyright © 2016 Global Message Services Worldwide. All rights reserved.
//
import Foundation
public extension GlobalMessageService {
/// `GlobalMessageService.framework` bundle. (read-only)
public private (set) static var bundle = NSBundle(forClass: GlobalMessageService.self)
/**
Localizes `GlobalMessageService.bundle`
- parameter language: New language `String`
*/
static func localize(language: String) {
let localeComponents = NSLocale.componentsFromLocaleIdentifier(language)
let languageCode = localeComponents[NSLocaleLanguageCode] ?? language
/// list of possible .lproj folders names
let lprojFolderPatterns: [String?] = [
language, // en-GB.lproj
language.stringByReplacingOccurrencesOfString("-", withString: "_"), // en_GB.lproj
(languageCode != language) ? languageCode : nil, // en.lproj
NSLocale(localeIdentifier: "en").displayNameForKey(NSLocaleIdentifier, value: language) // English.lproj
]
/// Available folders in bundle
let lprojFoldersPaths: [String] = lprojFolderPatterns.flatMap {
if let folderName = $0,
path = GlobalMessageService.bundle.pathForResource(folderName, ofType: "lproj") {
return path
} else {
return nil
}
}
let localizedBundlePath = lprojFoldersPaths.first
// Getting localized bundle
let localizedBudnle: NSBundle
if let localizedBundlePath = localizedBundlePath,
let newBundle = NSBundle(path: localizedBundlePath) // swiftlint:disable:this opening_brace
{
localizedBudnle = newBundle
// if no localizedBundlePath found, or NSBundle(path: localizedBundlePath) not found, use english language
} else {
localize("en")
return
}
GlobalMessageService.bundle = localizedBudnle
}
}
| apache-2.0 | e1c2b8534f01fc71d7e87bbfbf41875d | 30.333333 | 110 | 0.691996 | 4.814634 | false | false | false | false |
jie-json/swift-corelibs-foundation-master | Foundation/NSDate.swift | 1 | 6257 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
public typealias NSTimeInterval = Double
public var NSTimeIntervalSince1970: Double {
get {
return 978307200.0
}
}
public class NSDate : NSObject, NSCopying, NSSecureCoding, NSCoding {
typealias CFType = CFDateRef
deinit {
_CFDeinit(self)
}
internal var _cfObject: CFType {
return unsafeBitCast(self, CFType.self)
}
internal let _base = _CFInfo(typeID: CFDateGetTypeID())
internal let _timeIntervalSinceReferenceDate: NSTimeInterval
public var timeIntervalSinceReferenceDate: NSTimeInterval {
get {
return _timeIntervalSinceReferenceDate
}
}
public convenience override init() {
var tv = timeval()
withUnsafeMutablePointer(&tv) { t in
gettimeofday(t, nil)
}
var timestamp = NSTimeInterval(tv.tv_sec) - NSTimeIntervalSince1970
timestamp += NSTimeInterval(tv.tv_usec) / 1000000.0
self.init(timeIntervalSinceReferenceDate: timestamp)
}
public required init(timeIntervalSinceReferenceDate ti: NSTimeInterval) {
_timeIntervalSinceReferenceDate = ti
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
public func copyWithZone(zone: NSZone) -> AnyObject {
return self
}
public static func supportsSecureCoding() -> Bool {
return true
}
public func encodeWithCoder(aCoder: NSCoder) {
}
public override var description: String {
get {
return CFCopyDescription(_cfObject)._swiftObject
}
}
public func descriptionWithLocale(locale: AnyObject?) -> String {
return description
}
override internal var _cfTypeID: CFTypeID {
return CFDateGetTypeID()
}
}
extension NSDate {
public func timeIntervalSinceDate(anotherDate: NSDate) -> NSTimeInterval {
return self.timeIntervalSinceReferenceDate - anotherDate.timeIntervalSinceReferenceDate
}
public var timeIntervalSinceNow: NSTimeInterval {
get {
return timeIntervalSinceDate(NSDate())
}
}
public var timeIntervalSince1970: NSTimeInterval {
get {
return timeIntervalSinceReferenceDate + NSTimeIntervalSince1970
}
}
public func dateByAddingTimeInterval(ti: NSTimeInterval) -> NSDate {
return NSDate(timeIntervalSinceReferenceDate:_timeIntervalSinceReferenceDate + ti)
}
public func earlierDate(anotherDate: NSDate) -> NSDate {
if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate {
return self
} else {
return anotherDate
}
}
public func laterDate(anotherDate: NSDate) -> NSDate {
if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate {
return anotherDate
} else {
return self
}
}
public func compare(other: NSDate) -> NSComparisonResult {
let t1 = self.timeIntervalSinceReferenceDate
let t2 = other.timeIntervalSinceReferenceDate
if t1 < t2 {
return .OrderedAscending
} else if t1 > t2 {
return .OrderedDescending
} else {
return .OrderedSame
}
}
public func isEqualToDate(otherDate: NSDate) -> Bool {
return timeIntervalSinceReferenceDate == otherDate.timeIntervalSinceReferenceDate
}
}
extension NSDate {
internal static let _distantFuture = NSDate(timeIntervalSinceReferenceDate: 63113904000.0)
public class func distantFuture() -> NSDate {
return _distantFuture
}
internal static let _distantPast = NSDate(timeIntervalSinceReferenceDate: -63113904000.0)
public class func distantPast() -> NSDate {
return _distantPast
}
public convenience init(timeIntervalSinceNow secs: NSTimeInterval) {
self.init(timeIntervalSinceReferenceDate: secs + NSDate().timeIntervalSinceReferenceDate)
}
public convenience init(timeIntervalSince1970 secs: NSTimeInterval) {
self.init(timeIntervalSinceReferenceDate: secs - NSTimeIntervalSince1970)
}
public convenience init(timeInterval secsToBeAdded: NSTimeInterval, sinceDate date: NSDate) {
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate + secsToBeAdded)
}
}
extension NSDate : _CFBridgable { }
extension CFDateRef : _NSBridgable {
typealias NSType = NSDate
internal var _nsObject: NSType { return unsafeBitCast(self, NSType.self) }
}
/// Alternative API for avoiding AutoreleasingUnsafeMutablePointer usage in NSCalendar and NSFormatter
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative to the AutoreleasingUnsafeMutablePointer usage case of returning a NSDate + NSTimeInterval or using a pair of dates representing a range
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
public class NSDateInterval : NSObject {
internal var _start: NSDate
public var start: NSDate {
return _start
}
internal var _end: NSDate
public var end: NSDate {
return _end
}
public var interval: NSTimeInterval {
return end.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate
}
public required init(start: NSDate, end: NSDate) {
_start = start
_end = end
}
public convenience init(start: NSDate, interval: NSTimeInterval) {
self.init(start: start, end: NSDate(timeInterval: interval, sinceDate: start))
}
}
| apache-2.0 | 7c3dbbee28ebebf7b4821419c96da98b | 29.671569 | 266 | 0.674604 | 5.556838 | false | false | false | false |
ello/ello-ios | Specs/Controllers/Stream/Presenters/StreamInviteFriendsCellPresenterSpec.swift | 1 | 2009 | ////
/// StreamInviteFriendsCellPresenterSpec.swift
//
@testable import Ello
import Quick
import Nimble
class StreamInviteFriendsCellPresenterSpec: QuickSpec {
override func spec() {
describe("StreamInviteFriendsCellPresenter") {
var cell: StreamInviteFriendsCell = StreamInviteFriendsCell.loadFromNib()
var person: LocalPerson = stub([:])
var item: StreamCellItem = stub([:])
beforeEach {
cell = StreamInviteFriendsCell.loadFromNib()
cell.inviteCache = InviteCache()
person = stub(["name": "The Devil", "id": 666, "emails": ["[email protected]"]])
item = StreamCellItem(jsonable: person, type: StreamCellType.inviteFriends)
}
it("sets the person and name label correctly") {
StreamInviteFriendsCellPresenter.configure(
cell,
streamCellItem: item,
streamKind: StreamKind.following,
indexPath: IndexPath(item: 0, section: 0),
currentUser: nil
)
expect(cell.nameLabel.text) == "The Devil"
expect(cell.person) == person
}
it("sets the button text to Invite if not in the cache") {
expect(cell.inviteButton.titleLabel?.text) == "Invite"
}
// not 100% sure why this isn't doing what I expect it to
it("sets the button text to Re-send if in the cache") {
cell.inviteCache?.saveInvite(person.identifier)
StreamInviteFriendsCellPresenter.configure(
cell,
streamCellItem: item,
streamKind: StreamKind.following,
indexPath: IndexPath(item: 0, section: 0),
currentUser: nil
)
expect(cell.inviteButton.titleLabel?.text) == "Re-send"
}
}
}
}
| mit | cfbb1e9298a331acc5830fcdea9f73d4 | 36.203704 | 92 | 0.543554 | 5.231771 | false | false | false | false |
jbruce2112/health-tracker | HealthTracker/Model/Nutrient.swift | 1 | 2681 | //
// Nutrient.swift
// HealthTracker
//
// Created by John on 7/25/17.
// Copyright © 2017 Bruce32. All rights reserved.
//
import Foundation
import HealthKit
struct Nutrient {
let name: String
let quantity: Double
let units: String
init(name: String, quantity: Double, units: String) {
self.name = name
self.quantity = quantity
self.units = units
}
init(type: HKQuantityType, quantity: HKQuantity) {
name = Nutrient.supportedTypeFormats[type]?.0 ?? ""
let hkUnit = Nutrient.supportedTypeFormats[type]?.1 ?? HKUnit.gram()
self.quantity = quantity.doubleValue(for: hkUnit)
self.units = hkUnit.unitString
}
// Expose the supported HealthKit nutrition types
static let supportedTypes = {
return Set(supportedTypeFormats.map { $0.key })
}()
// Create a mapping of supported nutrient HealthKit data types
// to their respective display string and units appropriate for rendering
private static let supportedTypeFormats = {
return [HKQuantityType.quantityType(forIdentifier: .dietaryCarbohydrates)!: ("Carbohydrates", HKUnit.gram()),
HKQuantityType.quantityType(forIdentifier: .dietaryCholesterol)!: ("Cholesterol", HKUnit.gramUnit(with: .milli)),
HKQuantityType.quantityType(forIdentifier: .dietaryEnergyConsumed)!: ("Calorie Intake", HKUnit.kilocalorie()),
HKQuantityType.quantityType(forIdentifier: .dietaryFatSaturated)!: ("Fat Saturated", HKUnit.gram()),
HKQuantityType.quantityType(forIdentifier: .dietaryFatTotal)!: ("Fat Total", HKUnit.gram()),
HKQuantityType.quantityType(forIdentifier: .dietaryFiber)!: ("Fiber", HKUnit.gram()),
HKQuantityType.quantityType(forIdentifier: .dietaryProtein)!: ("Protein", HKUnit.gram()),
HKQuantityType.quantityType(forIdentifier: .dietarySodium)!: ("Sodium", HKUnit.gramUnit(with: .milli)),
HKQuantityType.quantityType(forIdentifier: .dietarySugar)!: ("Sugar", HKUnit.gram()),
HKQuantityType.quantityType(forIdentifier: .dietaryVitaminA)!: ("Vitamin A", HKUnit.gramUnit(with: .milli)),
HKQuantityType.quantityType(forIdentifier: .dietaryVitaminB12)!: ("Vitamin B12", HKUnit.gramUnit(with: .milli)),
HKQuantityType.quantityType(forIdentifier: .dietaryVitaminB6)!: ("Vitamin B6", HKUnit.gramUnit(with: .milli)),
HKQuantityType.quantityType(forIdentifier: .dietaryVitaminC)!: ("Vitamin C", HKUnit.gramUnit(with: .milli)),
HKQuantityType.quantityType(forIdentifier: .dietaryVitaminD)!: ("Vitamin D", HKUnit.gramUnit(with: .milli)),
HKQuantityType.quantityType(forIdentifier: .dietaryVitaminE)!: ("Vitamin E", HKUnit.gramUnit(with: .milli))]
}()
}
| mit | 36c98127de8b85338ecb32d770c1717f | 44.423729 | 123 | 0.716045 | 4.142195 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetrySdk/Internal/Locks.swift | 2 | 6743 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Metrics API open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the Swift Metrics API project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift Metrics API project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#else
import Glibc
#endif
/// A threading lock based on `libpthread` instead of `libdispatch`.
///
/// This object provides a lock on top of a single `pthread_mutex_t`. This kind
/// of lock is safe to use with `libpthread`-based threading models, such as the
/// one used by NIO.
internal final class Lock {
fileprivate let mutex: UnsafeMutablePointer<pthread_mutex_t> = UnsafeMutablePointer.allocate(capacity: 1)
/// Create a new lock.
public init() {
let err = pthread_mutex_init(self.mutex, nil)
precondition(err == 0, "pthread_mutex_init failed with error \(err)")
}
deinit {
let err = pthread_mutex_destroy(self.mutex)
precondition(err == 0, "pthread_mutex_destroy failed with error \(err)")
self.mutex.deallocate()
}
/// Acquire the lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `unlock`, to simplify lock handling.
public func lock() {
let err = pthread_mutex_lock(self.mutex)
precondition(err == 0, "pthread_mutex_lock failed with error \(err)")
}
/// Release the lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `lock`, to simplify lock handling.
public func unlock() {
let err = pthread_mutex_unlock(self.mutex)
precondition(err == 0, "pthread_mutex_unlock failed with error \(err)")
}
}
extension Lock {
/// Acquire the lock for the duration of the given block.
///
/// This convenience method should be preferred to `lock` and `unlock` in
/// most situations, as it ensures that the lock will be released regardless
/// of how `body` exits.
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
internal func withLock<T>(_ body: () throws -> T) rethrows -> T {
self.lock()
defer {
self.unlock()
}
return try body()
}
// specialise Void return (for performance)
@inlinable
internal func withLockVoid(_ body: () throws -> Void) rethrows {
try self.withLock(body)
}
}
/// A threading lock based on `libpthread` instead of `libdispatch`.
///
/// This object provides a lock on top of a single `pthread_mutex_t`. This kind
/// of lock is safe to use with `libpthread`-based threading models, such as the
/// one used by NIO.
internal final class ReadWriteLock {
fileprivate let rwlock: UnsafeMutablePointer<pthread_rwlock_t> = UnsafeMutablePointer.allocate(capacity: 1)
/// Create a new lock.
public init() {
let err = pthread_rwlock_init(self.rwlock, nil)
precondition(err == 0, "pthread_rwlock_init failed with error \(err)")
}
deinit {
let err = pthread_rwlock_destroy(self.rwlock)
precondition(err == 0, "pthread_rwlock_destroy failed with error \(err)")
self.rwlock.deallocate()
}
/// Acquire a reader lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `unlock`, to simplify lock handling.
public func lockRead() {
let err = pthread_rwlock_rdlock(self.rwlock)
precondition(err == 0, "pthread_rwlock_rdlock failed with error \(err)")
}
/// Acquire a writer lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `unlock`, to simplify lock handling.
public func lockWrite() {
let err = pthread_rwlock_wrlock(self.rwlock)
precondition(err == 0, "pthread_rwlock_wrlock failed with error \(err)")
}
/// Release the lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `lock`, to simplify lock handling.
public func unlock() {
let err = pthread_rwlock_unlock(self.rwlock)
precondition(err == 0, "pthread_rwlock_unlock failed with error \(err)")
}
}
extension ReadWriteLock {
/// Acquire the reader lock for the duration of the given block.
///
/// This convenience method should be preferred to `lock` and `unlock` in
/// most situations, as it ensures that the lock will be released regardless
/// of how `body` exits.
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
internal func withReaderLock<T>(_ body: () throws -> T) rethrows -> T {
self.lockRead()
defer {
self.unlock()
}
return try body()
}
/// Acquire the writer lock for the duration of the given block.
///
/// This convenience method should be preferred to `lock` and `unlock` in
/// most situations, as it ensures that the lock will be released regardless
/// of how `body` exits.
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
internal func withWriterLock<T>(_ body: () throws -> T) rethrows -> T {
self.lockWrite()
defer {
self.unlock()
}
return try body()
}
// specialise Void return (for performance)
@inlinable
internal func withReaderLockVoid(_ body: () throws -> Void) rethrows {
try self.withReaderLock(body)
}
// specialise Void return (for performance)
@inlinable
internal func withWriterLockVoid(_ body: () throws -> Void) rethrows {
try self.withWriterLock(body)
}
}
| apache-2.0 | ec60f382906965d3bf5a9f75d9e25827 | 33.055556 | 111 | 0.613822 | 4.344716 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/Exporters/DatadogExporter/Files/Directory.swift | 1 | 2582 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
/// An abstraction over file system directory where SDK stores its files.
internal struct Directory {
let url: URL
/// Creates subdirectory with given path under system caches directory.
init(withSubdirectoryPath path: String) throws {
self.init(url: try createCachesSubdirectoryIfNotExists(subdirectoryPath: path))
}
init(url: URL) {
self.url = url
}
/// Creates file with given name.
func createFile(named fileName: String) throws -> File {
let fileURL = url.appendingPathComponent(fileName, isDirectory: false)
guard FileManager.default.createFile(atPath: fileURL.path, contents: nil, attributes: nil) == true else {
throw ExporterError(description: "Cannot create file at path: \(fileURL.path)")
}
return File(url: fileURL)
}
/// Returns file with given name.
func file(named fileName: String) -> File? {
let fileURL = url.appendingPathComponent(fileName, isDirectory: false)
if FileManager.default.fileExists(atPath: fileURL.path) {
return File(url: fileURL)
} else {
return nil
}
}
/// Returns all files of this directory.
func files() throws -> [File] {
return try FileManager.default
.contentsOfDirectory(at: url, includingPropertiesForKeys: [.isRegularFileKey, .canonicalPathKey])
.map { url in File(url: url) }
}
}
/// Creates subdirectory at given path in `/Library/Caches` if it does not exist. Might throw `ExporterError` when it's not possible.
/// * `/Library/Caches` is exclduded from iTunes and iCloud backups by default.
/// * System may delete data in `/Library/Cache` to free up disk space which reduces the impact on devices working under heavy space pressure.
private func createCachesSubdirectoryIfNotExists(subdirectoryPath: String) throws -> URL {
guard let cachesDirectoryURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
throw ExporterError(description: "Cannot obtain `/Library/Caches/` url.")
}
let subdirectoryURL = cachesDirectoryURL.appendingPathComponent(subdirectoryPath, isDirectory: true)
do {
try FileManager.default.createDirectory(at: subdirectoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
throw ExporterError(description: "Cannot create subdirectory in `/Library/Caches/` folder.")
}
return subdirectoryURL
}
| apache-2.0 | 4ed95c968b7d392ec181f2a74d58d683 | 40.645161 | 142 | 0.696359 | 4.711679 | false | false | false | false |
oasisweng/DWActionsMenu | DWActionsMenu/DWResizeControl.swift | 1 | 3052 | //
// ResizeControl.swift
// DWActionsMenu
//
// Created by Dingzhong Weng on 24/12/2014.
// Copyright (c) 2014 Dingzhong Weng. All rights reserved.
//
import UIKit
import Foundation
protocol DWResizeControlDelegate {
func resizeControlShouldSlide(translation:CGPoint) -> Bool
func resizeControlDidSlide(translation:CGPoint,resizeControl:DWResizeControl)
}
class DWResizeControl: UIView {
let kIndicatorSize = CGSizeMake(32, 2)
let C = Constants()
var delegate:DWResizeControlDelegate?
init(parentView: UIView) {
super.init(frame: CGRectMake(0, 0, parentView.frame.size.width, C.kRESIZECONTROLHEIGHT))
//handle dragging, but only move vertically
var panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.addGestureRecognizer(panGesture)
//initial background color
self.backgroundColor = UIColor(red: 149/255, green: 165/255, blue: 166/255, alpha: 0.75)
//add self to parent view
parentView.addSubview(self)
println("Resize Control init done")
}
convenience init(parentView: UIView, delegate:DWResizeControlDelegate) {
self.init(parentView:parentView)
//set delegate
self.delegate = delegate
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(dirtyRect: CGRect) {
super.drawRect(dirtyRect)
println("drawRect Resize Control bound \(bounds)")
var center = CGPointMake(bounds.size.width/2, bounds.size.height/2)
var origin = CGPointMake(center.x-kIndicatorSize.width/2, (C.kRESIZECONTROLHEIGHT-kIndicatorSize.height)/2)
var path = UIBezierPath()
path.moveToPoint(origin)
path.addLineToPoint(CGPointMake(origin.x+kIndicatorSize.width,origin.y))
path.addLineToPoint(CGPointMake(origin.x+kIndicatorSize.width,origin.y+kIndicatorSize.height))
path.addLineToPoint (CGPointMake(origin.x,origin.y+kIndicatorSize.height))
path.addLineToPoint(origin)
UIColor.whiteColor().setStroke()
UIColor.whiteColor().setFill()
path.stroke()
path.fill()
}
func handlePan(sender:UIPanGestureRecognizer){
var translation = sender.translationInView(self)
println("pan gesture recognized \(translation)")
if ((self.delegate?.resizeControlShouldSlide(translation)) == true){
self.delegate?.resizeControlDidSlide(translation,resizeControl: self)
}
//reset pan gesture recognizer
sender.setTranslation(CGPointZero, inView: self)
}
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
var hitBox = UIEdgeInsetsInsetRect(bounds,UIEdgeInsetsMake(-22, 0, -22, -22))
println("hitbox \(hitBox) vs original \(bounds) and point \(point)")
return CGRectContainsPoint(hitBox,point)
}
} | mit | 38c007e0d0d06ee89481848ae5489004 | 32.922222 | 115 | 0.662189 | 4.548435 | false | false | false | false |
Khan/Swiftx | Swiftx/Result.swift | 1 | 6982 | //
// Result.swift
// swiftz
//
// Created by Maxwell Swadling on 9/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
import class Foundation.NSError
import typealias Foundation.NSErrorPointer
/// Result is similar to an Either, except specialized to have an Error case that can
/// only contain an NSError.
public enum Result<V> {
case Error(NSError)
case Value(Box<V>)
public init(_ e: NSError?, _ v: V) {
if let ex = e {
self = Result.Error(ex)
} else {
self = Result.Value(Box(v))
}
}
/// Converts a Result to a more general Either type.
public func toEither() -> Either<NSError, V> {
switch self {
case let Error(e):
return .Left(Box(e))
case let Value(v):
return Either.Right(Box(v.value))
}
}
/// Much like the ?? operator for Optional types, takes a value and a function,
/// and if the Result is Error, returns the error, otherwise maps the function over
/// the value in Value and returns that value.
public func fold<B>(value: B, f: V -> B) -> B {
switch self {
case Error(_):
return value
case let Value(v):
return f(v.value)
}
}
/// Named function for `>>-`. If the Result is Error, simply returns
/// a New Error with the value of the receiver. If Value, applies the function `f`
/// and returns the result.
public func flatMap<S>(f: V -> Result<S>) -> Result<S> {
return self >>- f
}
/// Creates an Error with the given value.
public static func error(e: NSError) -> Result<V> {
return .Error(e)
}
/// Creates a Value with the given value.
public static func value(v: V) -> Result<V> {
return .Value(Box(v))
}
}
/// MARK: Function Constructors
/// Takes a function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A>(fn : (NSErrorPointer) -> A) -> Result<A> {
var err : NSError? = nil
let b = fn(&err)
return (err != nil) ? .Error(err!) : .Value(Box(b))
}
/// Takes a 1-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B>(fn : (A, NSErrorPointer) -> B) -> A -> Result<B> {
return { a in
var err : NSError? = nil
let b = fn(a, &err)
return (err != nil) ? .Error(err!) : .Value(Box(b))
}
}
/// Takes a 2-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C>(fn : (A, B, NSErrorPointer) -> C) -> A -> B -> Result<C> {
return { a in { b in
var err : NSError? = nil
let c = fn(a, b, &err)
return (err != nil) ? .Error(err!) : .Value(Box(c))
} }
}
/// Takes a 3-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C, D>(fn : (A, B, C, NSErrorPointer) -> D) -> A -> B -> C -> Result<D> {
return { a in { b in { c in
var err : NSError? = nil
let d = fn(a, b, c, &err)
return (err != nil) ? .Error(err!) : .Value(Box(d))
} } }
}
/// Takes a 4-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C, D, E>(fn : (A, B, C, D, NSErrorPointer) -> E) -> A -> B -> C -> D -> Result<E> {
return { a in { b in { c in { d in
var err : NSError? = nil
let e = fn(a, b, c, d, &err)
return (err != nil) ? .Error(err!) : .Value(Box(e))
} } } }
}
/// Takes a 5-ary function that can potentially raise an error and constructs a Result depending on
/// whether the error pointer has been set.
public func from<A, B, C, D, E, F>(fn : (A, B, C, D, E, NSErrorPointer) -> F) -> A -> B -> C -> D -> E -> Result<F> {
return { a in { b in { c in { d in { e in
var err : NSError? = nil
let f = fn(a, b, c, d, e, &err)
return (err != nil) ? .Error(err!) : .Value(Box(f))
} } } } }
}
/// Infix 1-ary from
public func !! <A, B>(fn : (A, NSErrorPointer) -> B, a : A) -> Result<B> {
var err : NSError? = nil
let b = fn(a, &err)
return (err != nil) ? .Error(err!) : .Value(Box(b))
}
/// Infix 2-ary from
public func !! <A, B, C>(fn : (A, B, NSErrorPointer) -> C, t : (A, B)) -> Result<C> {
var err : NSError? = nil
let c = fn(t.0, t.1, &err)
return (err != nil) ? .Error(err!) : .Value(Box(c))
}
/// Infix 3-ary from
public func !! <A, B, C, D>(fn : (A, B, C, NSErrorPointer) -> D, t : (A, B, C)) -> Result<D> {
var err : NSError? = nil
let d = fn(t.0, t.1, t.2, &err)
return (err != nil) ? .Error(err!) : .Value(Box(d))
}
/// Infix 4-ary from
public func !! <A, B, C, D, E>(fn : (A, B, C, D, NSErrorPointer) -> E, t : (A, B, C, D)) -> Result<E> {
var err : NSError? = nil
let e = fn(t.0, t.1, t.2, t.3, &err)
return (err != nil) ? .Error(err!) : .Value(Box(e))
}
/// Infix 5-ary from
public func !! <A, B, C, D, E, F>(fn : (A, B, C, D, E, NSErrorPointer) -> F, t : (A, B, C, D, E)) -> Result<F> {
var err : NSError? = nil
let f = fn(t.0, t.1, t.2, t.3, t.4, &err)
return (err != nil) ? .Error(err!) : .Value(Box(f))
}
/// MARK: Equatable
public func == <V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
switch (lhs, rhs) {
case let (.Error(l), .Error(r)) where l == r:
return true
case let (.Value(l), .Value(r)) where l.value == r.value:
return true
default:
return false
}
}
public func != <V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
return !(lhs == rhs)
}
/// MARK: Functor, Applicative, Monad
/// Applicative `pure` function, lifts a value into a Value.
public func pure<V>(a: V) -> Result<V> {
return .Value(Box(a))
}
/// Functor `fmap`. If the Result is Error, ignores the function and returns the Error.
/// If the Result is Value, applies the function to the Right value and returns the result
/// in a new Value.
public func <^> <VA, VB>(f: VA -> VB, a: Result<VA>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return Result.Value(Box(f(r.value)))
}
}
/// Applicative Functor `apply`. Given an Result<VA -> VB> and an Result<VA>,
/// returns a Result<VB>. If the `f` or `a' param is an Error, simply returns an Error with the
/// same value. Otherwise the function taken from Value(f) is applied to the value from Value(a)
/// And a Value is returned.
public func <*> <VA, VB>(f: Result<VA -> VB>, a: Result<VA>) -> Result<VB> {
switch (a, f) {
case let (.Error(l), _):
return .Error(l)
case let (.Value(r), .Error(m)):
return .Error(m)
case let (.Value(r), .Value(g)):
return Result<VB>.Value(Box(g.value(r.value)))
}
}
/// Monadic `bind`. Given an Result<VA>, and a function from VA -> Result<VB>,
/// applies the function `f` if `a` is Value, otherwise the function is ignored and an Error
/// with the Error value from `a` is returned.
public func >>- <VA, VB>(a: Result<VA>, f: VA -> Result<VB>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return f(r.value)
}
}
| bsd-3-clause | aced2a18a4608b0c83eb45c0117f9fb0 | 30.45045 | 117 | 0.608851 | 2.833604 | false | false | false | false |
sonsongithub/reddift | application/TabViewCell.swift | 1 | 1521 | //
// TabViewCell.swift
// reddift
//
// Created by sonson on 2015/10/28.
// Copyright © 2015年 sonson. All rights reserved.
//
import UIKit
extension NSLayoutConstraint {
func setMultiplier(multiplier: CGFloat) {
let newConstraint = NSLayoutConstraint(
item: firstItem as Any,
attribute: firstAttribute,
relatedBy: relation,
toItem: secondItem,
attribute: secondAttribute,
multiplier: multiplier,
constant: constant)
newConstraint.priority = priority
newConstraint.shouldBeArchived = self.shouldBeArchived
newConstraint.identifier = self.identifier
newConstraint.isActive = self.isActive
NSLayoutConstraint.deactivate([self])
NSLayoutConstraint.activate([newConstraint])
}
}
class TabViewCell: UICollectionViewCell {
@IBOutlet var screenImageView: UIImageView?
@IBOutlet var numberLabel: UILabel?
@IBOutlet var widthRatio: NSLayoutConstraint?
@IBOutlet var aspectRatio: NSLayoutConstraint?
override func awakeFromNib() {
super.awakeFromNib()
if let size = UIApplication.shared.keyWindow?.rootViewController?.view.frame.size {
let ratio = size.width / (size.height)
widthRatio?.setMultiplier(multiplier: 0.95)
aspectRatio?.setMultiplier(multiplier: ratio)
}
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
| mit | 3aa4562b5adedb6b9711ed0b127fa17f | 28.192308 | 91 | 0.647563 | 5.402135 | false | false | false | false |
danwallacenz/CafeHunter | CafeHunter/CafeViewController.swift | 1 | 4130 | //
// CafeViewController.swift
// CafeHunter
//
// Created by Daniel Wallace on 11/12/14.
// Copyright (c) 2014 Razeware. All rights reserved.
//
import UIKit
// This defines a protocol to which objects can conform to be told when the user is finished with the café detail view and it should be dismissed.
// The optional tells the compiler that the method doesn’t have to be defined, leaving it up to the implementation class to decide whether it needs the method or not.
// If you want optional methods in your protocol, you have to declare the protocol as @objc.
// Marking the protocol as @objc enables Swift to put various runtime checks in place to check for conformance to the protocol and to check that various methods exist to support optional functionality.
@objc protocol CafeViewControllerDelegate {
optional func cafeViewControllerDidFinish(
viewController: CafeViewController)
}
class CafeViewController: UIViewController {
// This defines a variable of type optional-Cafe.
// It will hold the café that the view controller is currently set up to display.
var cafe: Cafe? {
// Sets up a listener for when the variable changes.
// Variables can have willSet and didSet closures defined.
// The former is called just before the variable is set to a new value and the latter just after.
didSet {
self.setupWithCafe()
}
}
// Marked as weak, which is standard practice for delegate properties to avoid retain cycles.
weak var delegate: CafeViewControllerDelegate?
@IBOutlet var imageView: UIImageView!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var streetLabel: UILabel!
@IBOutlet var cityLabel: UILabel!
@IBOutlet var zipLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupWithCafe()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
private func setupWithCafe() {
// This method is going to use properties that are IB outlets.
// Recall that these are implicitly unwrapped optionals.
// They only contain values once the view is loaded, so if this method is called before then, variables such as nameLabel and streetLabel won’t yet be set up.
// You could check for the existence of each outlet directly, but that would be a lot of superfluous code.
// In this case, it’s simpler to check if the view is loaded.
if !self.isViewLoaded() {
return
}
// If there’s no café, then there’s nothing to set on the views. Only if there’s a café do you want to proceed.
if let cafe = self.cafe {
self.title = cafe.name
self.nameLabel.text = cafe.name
self.streetLabel.text = cafe.street
self.cityLabel.text = cafe.city
self.zipLabel.text = cafe.zip
// Load the picture for the cafe by using an NSURLConnection.
let request = NSURLRequest(URL: cafe.pictureURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue())
{
(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
let image = UIImage(data: data)
self.imageView.image = image
}
}
}
@IBAction private func back(sender: AnyObject) {
self.delegate?.cafeViewControllerDidFinish?(self)
}
}
| apache-2.0 | 1e8cbd85b726eddca93fbd3a00f2427b | 38.557692 | 205 | 0.657511 | 4.992718 | false | false | false | false |
proversity-org/edx-app-ios | Source/DiscussionCommentsViewController.swift | 1 | 26137 | //
// DiscussionCommentsViewController.swift
// edX
//
// Created by Tang, Jeff on 5/28/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
private var commentTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color : OEXStyles.shared().neutralDark())
}
private var smallTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color : OEXStyles.shared().neutralDark())
}
private var smallIconStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralDark())
}
private let smallIconSelectedStyle = smallIconStyle.withColor(OEXStyles.shared().primaryBaseColor())
private let UserProfileImageSize = CGSize(width: 40, height: 40)
class DiscussionCommentCell: UITableViewCell {
private let bodyTextView = UITextView()
private let authorButton = UIButton(type: .system)
private let commentCountOrReportIconButton = UIButton(type: .system)
private let divider = UIView()
private let containerView = UIView()
fileprivate let endorsedLabel = UILabel()
private let authorProfileImage = UIImageView()
private let authorNameLabel = UILabel()
private let dateLabel = UILabel()
fileprivate var endorsedTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .small, color: OEXStyles.shared().utilitySuccessBase())
}
private func setEndorsed(endorsed : Bool) {
endorsedLabel.isHidden = !endorsed
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
applyStandardSeparatorInsets()
addSubViews()
setConstraints()
bodyTextView.isEditable = false
bodyTextView.dataDetectorTypes = UIDataDetectorTypes.all
bodyTextView.isScrollEnabled = false
bodyTextView.backgroundColor = UIColor.clear
containerView.isUserInteractionEnabled = true
commentCountOrReportIconButton.localizedHorizontalContentAlignment = .Trailing
contentView.backgroundColor = OEXStyles.shared().discussionsBackgroundColor
divider.backgroundColor = OEXStyles.shared().discussionsBackgroundColor
containerView.backgroundColor = OEXStyles.shared().neutralWhiteT()
containerView.applyBorderStyle(style: BorderStyle())
accessibilityTraits = UIAccessibilityTraits.header
bodyTextView.isAccessibilityElement = false
}
private func addSubViews() {
contentView.addSubview(containerView)
containerView.addSubview(bodyTextView)
containerView.addSubview(authorButton)
containerView.addSubview(endorsedLabel)
containerView.addSubview(commentCountOrReportIconButton)
containerView.addSubview(divider)
containerView.addSubview(authorProfileImage)
containerView.addSubview(authorNameLabel)
containerView.addSubview(dateLabel)
}
private func setConstraints() {
containerView.snp.makeConstraints { make in
make.edges.equalTo(contentView).inset(UIEdgeInsets.init(top: 0, left: StandardHorizontalMargin, bottom: 0, right: StandardHorizontalMargin))
}
authorProfileImage.snp.makeConstraints { make in
make.leading.equalTo(containerView).offset(StandardHorizontalMargin)
make.top.equalTo(containerView).offset(StandardVerticalMargin)
make.width.equalTo(UserProfileImageSize.width)
make.height.equalTo(UserProfileImageSize.height)
}
authorNameLabel.snp.makeConstraints { make in
make.top.equalTo(authorProfileImage)
make.leading.equalTo(authorProfileImage.snp.trailing).offset(StandardHorizontalMargin)
}
dateLabel.snp.makeConstraints { make in
make.top.equalTo(authorNameLabel.snp.bottom)
make.leading.equalTo(authorNameLabel)
}
authorButton.snp.makeConstraints { make in
make.top.equalTo(authorProfileImage)
make.leading.equalTo(contentView)
make.bottom.equalTo(authorProfileImage)
make.trailing.equalTo(dateLabel)
make.trailing.equalTo(authorNameLabel)
}
endorsedLabel.snp.makeConstraints { make in
make.leading.equalTo(dateLabel)
make.top.equalTo(dateLabel.snp.bottom)
}
bodyTextView.snp.makeConstraints { make in
make.top.equalTo(authorProfileImage.snp.bottom).offset(StandardVerticalMargin)
make.leading.equalTo(authorProfileImage)
make.trailing.equalTo(containerView).offset(-StandardHorizontalMargin)
}
commentCountOrReportIconButton.snp.makeConstraints { make in
make.trailing.equalTo(containerView).offset(-OEXStyles.shared().standardHorizontalMargin())
make.top.equalTo(authorNameLabel)
}
divider.snp.makeConstraints { make in
make.top.equalTo(bodyTextView.snp.bottom).offset(StandardVerticalMargin)
make.leading.equalTo(containerView)
make.trailing.equalTo(containerView)
make.height.equalTo(StandardVerticalMargin)
make.bottom.equalTo(containerView)
}
}
func useResponse(response : DiscussionComment, viewController : DiscussionCommentsViewController) {
divider.snp.updateConstraints { make in
make.height.equalTo(StandardVerticalMargin)
}
bodyTextView.attributedText = commentTextStyle.markdownString(withText: response.renderedBody)
DiscussionHelper.styleAuthorDetails(author: response.author, authorLabel: response.authorLabel, createdAt: response.createdAt, hasProfileImage: response.hasProfileImage, imageURL: response.imageURL, authoNameLabel: authorNameLabel, dateLabel: dateLabel, authorButton: authorButton, imageView: authorProfileImage, viewController: viewController, router: viewController.environment.router)
let message = Strings.comment(count: response.childCount)
let buttonTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [
Icon.Comment.attributedTextWithStyle(style: smallIconStyle),
smallTextStyle.attributedString(withText: message)])
commentCountOrReportIconButton.setAttributedTitle(buttonTitle, for: .normal)
setEndorsed(endorsed: response.endorsed)
setNeedsLayout()
layoutIfNeeded()
DiscussionHelper.styleAuthorProfileImageView(imageView: authorProfileImage)
setAccessiblity(commentCount: commentCountOrReportIconButton.currentAttributedTitle?.string)
}
func useComment(comment : DiscussionComment, inViewController viewController : DiscussionCommentsViewController, index: NSInteger) {
divider.snp.updateConstraints { make in
make.height.equalTo(2)
}
bodyTextView.attributedText = commentTextStyle.markdownString(withText: comment.renderedBody)
updateReportText(button: commentCountOrReportIconButton, report: comment.abuseFlagged)
DiscussionHelper.styleAuthorDetails(author: comment.author, authorLabel: comment.authorLabel, createdAt: comment.createdAt, hasProfileImage: comment.hasProfileImage, imageURL: comment.imageURL, authoNameLabel: authorNameLabel, dateLabel: dateLabel, authorButton: authorButton, imageView: authorProfileImage, viewController: viewController, router: viewController.environment.router)
commentCountOrReportIconButton.oex_removeAllActions()
commentCountOrReportIconButton.oex_addAction({[weak viewController] _ -> Void in
let apiRequest = DiscussionAPI.flagComment(abuseFlagged: !comment.abuseFlagged, commentID: comment.commentID)
viewController?.environment.networkManager.taskForRequest(apiRequest) { result in
if let response = result.data {
if (viewController?.comments.count)! > index && viewController?.comments[index].commentID == response.commentID {
let patchedComment = self.patchComment(oldComment: viewController?.comments[index], newComment: response)
viewController?.comments[index] = patchedComment
self.updateReportText(button: self.commentCountOrReportIconButton, report: response.abuseFlagged)
viewController?.tableView.reloadData()
}
}
else {
viewController?.showOverlay(withMessage: DiscussionHelper.messageForError(error: result.error))
}
}
}, for: UIControl.Event.touchUpInside)
setEndorsed(endorsed: false)
setNeedsLayout()
layoutIfNeeded()
DiscussionHelper.styleAuthorProfileImageView(imageView: authorProfileImage)
setAccessiblity(commentCount: nil)
}
private func patchComment(oldComment: DiscussionComment?, newComment: DiscussionComment)-> DiscussionComment {
var patchComment = newComment
patchComment.hasProfileImage = oldComment?.hasProfileImage ?? false
patchComment.imageURL = oldComment?.imageURL ?? ""
return patchComment
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateReportText(button: UIButton, report: Bool) {
let iconStyle = report ? smallIconSelectedStyle : smallIconStyle
let reportIcon = Icon.ReportFlag.attributedTextWithStyle(style: iconStyle)
let reportTitle = smallTextStyle.attributedString(withText: (report ? Strings.discussionUnreport : Strings.discussionReport ))
let buttonTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [reportIcon, reportTitle])
button.setAttributedTitle(buttonTitle, for: .normal)
button.snp.remakeConstraints { make in
make.top.equalTo(contentView).offset(StandardVerticalMargin)
make.width.equalTo(buttonTitle.singleLineWidth() + StandardHorizontalMargin)
make.trailing.equalTo(contentView).offset(-2*StandardHorizontalMargin)
}
button.accessibilityHint = report ? Strings.Accessibility.discussionUnreportHint : Strings.Accessibility.discussionReportHint
}
func setAccessiblity(commentCount : String?) {
var accessibilityString = ""
let sentenceSeparator = ", "
let body = bodyTextView.attributedText.string
accessibilityString.append(body + sentenceSeparator)
if let date = dateLabel.text {
accessibilityString.append(Strings.Accessibility.discussionPostedOn(date: date) + sentenceSeparator)
}
if let author = authorNameLabel.text {
accessibilityString.append(Strings.accessibilityBy + " " + author + sentenceSeparator)
}
if let endorsed = endorsedLabel.text, !endorsedLabel.isHidden {
accessibilityString.append(endorsed + sentenceSeparator)
}
if let comments = commentCount {
accessibilityString.append(comments)
commentCountOrReportIconButton.isAccessibilityElement = false
}
accessibilityLabel = accessibilityString
if let authorName = authorNameLabel.text {
self.authorButton.accessibilityLabel = authorName
self.authorButton.accessibilityHint = Strings.accessibilityShowUserProfileHint
}
}
}
protocol DiscussionCommentsViewControllerDelegate: class {
func discussionCommentsView(controller : DiscussionCommentsViewController, updatedComment comment: DiscussionComment)
}
class DiscussionCommentsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DiscussionNewCommentViewControllerDelegate, InterfaceOrientationOverriding {
typealias Environment = DataManagerProvider & NetworkManagerProvider & OEXRouterProvider & OEXAnalyticsProvider & OEXStylesProvider & OEXConfigProvider
private enum TableSection : Int {
case Response = 0
case Comments = 1
}
private let identifierCommentCell = "CommentCell"
fileprivate let environment: Environment
private let courseID: String
private let discussionManager : DiscussionDataManager
private var loadController : LoadStateViewController
private let contentView = UIView()
private let addCommentButton = UIButton(type: .system)
fileprivate var tableView: UITableView!
fileprivate var comments : [DiscussionComment] = []
private var responseItem: DiscussionComment?
weak var delegate: DiscussionCommentsViewControllerDelegate?
var profileFeed: Feed<UserProfile>?
var tempComment: DiscussionComment? // This will be used for injecting user info to added comment
//Since didSet doesn't get called from within initialization context, we need to set it with another variable.
private var commentsClosed : Bool = false {
didSet {
let styles = OEXStyles.shared()
addCommentButton.backgroundColor = commentsClosed ? styles.neutralBase() : styles.primaryXDarkColor()
let textStyle = OEXTextStyle(weight : .normal, size: .base, color: OEXStyles.shared().neutralWhite())
let icon = commentsClosed ? Icon.Closed : Icon.Create
let buttonText = commentsClosed ? Strings.commentsClosed : Strings.addAComment
let buttonTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon.attributedTextWithStyle(style: textStyle.withSize(.xSmall)), textStyle.attributedString(withText: buttonText)])
addCommentButton.setAttributedTitle(buttonTitle, for: .normal)
addCommentButton.isEnabled = !commentsClosed
if (!commentsClosed) {
addCommentButton.oex_addAction({[weak self] (action : AnyObject!) -> Void in
if let owner = self {
guard let thread = owner.thread, let responseItem = owner.responseItem else { return }
owner.environment.router?.showDiscussionNewCommentFromController(controller: owner, courseID: owner.courseID, thread: thread, context: .Comment(responseItem))
}
}, for: UIControl.Event.touchUpInside)
}
}
}
var paginationController : PaginationController<DiscussionComment>?
//Only used to set commentsClosed out of initialization context
//TODO: Get rid of this variable when Swift improves
private var closed : Bool = false
private var thread: DiscussionThread?
private var isDiscussionBlackedOut: Bool
private var threadID: String?
var commentID: String?
init(environment: Environment, courseID : String, isDiscussionBlackedOut: Bool = false) {
self.courseID = courseID
self.environment = environment
self.discussionManager = self.environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID: self.courseID)
self.isDiscussionBlackedOut = isDiscussionBlackedOut
self.loadController = LoadStateViewController()
super.init(nibName: nil, bundle: nil)
}
convenience init(environment: Environment, courseID : String, responseItem: DiscussionComment, closed : Bool, thread: DiscussionThread?, isDiscussionBlackedOut: Bool = false) {
self.init(environment: environment, courseID: courseID, isDiscussionBlackedOut: isDiscussionBlackedOut)
self.responseItem = responseItem
self.thread = thread
self.closed = closed
}
convenience init(environment: Environment, courseID : String, commentID: String, threadID: String) {
self.init(environment: environment, courseID: courseID)
self.commentID = commentID
self.threadID = threadID
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.register(DiscussionCommentCell.classForCoder(), forCellReuseIdentifier: identifierCommentCell)
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableView.automaticDimension
addSubviews()
setStyles()
setConstraints()
loadController.setupInController(controller: self, contentView: self.contentView)
self.commentsClosed = self.closed
if responseItem != nil {
initializeViewContent()
}
else if thread == nil {
// In deep linking, we need to load thread and responseItem with their Ids.
loadThread()
}
else {
loadDiscussionResponse()
}
}
private func initializeViewContent() {
initializePaginator()
loadContent()
setupProfileLoader()
}
private func loadThread() {
guard let threadID = threadID else { return }
let apiRequest = DiscussionAPI.readThread(read: true, threadID: threadID)
environment.networkManager.taskForRequest(apiRequest) {[weak self] result in
if result.response?.httpStatusCode.is2xx ?? false {
if let thread = result.data {
self?.thread = thread
self?.loadDiscussionResponse()
}
}
else {
self?.loadController.state = LoadState.failed(error: result.error)
}
}
}
private func loadDiscussionResponse() {
guard let commentID = commentID else { return }
let apiRequest = DiscussionAPI.getResponse(responseID: commentID)
environment.networkManager.taskForRequest(apiRequest) {[weak self] result in
if result.response?.httpStatusCode.is2xx ?? false {
if let response = result.data {
self?.responseItem = response
self?.initializeViewContent()
}
}
else {
self?.loadController.state = LoadState.failed(error: result.error)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
logScreenEvent()
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func logScreenEvent() {
environment.analytics.trackDiscussionScreen(withName: AnalyticsScreenName.ViewResponseComments, courseId: courseID, value: thread?.title, threadId: responseItem?.threadID, topicId: nil, responseID: responseItem?.commentID, author: responseItem?.author)
}
func addSubviews() {
view.addSubview(contentView)
contentView.addSubview(tableView)
view.addSubview(addCommentButton)
}
func setStyles() {
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
tableView.applyStandardSeparatorInsets()
tableView.backgroundColor = OEXStyles.shared().neutralXLight()
tableView.contentInset = UIEdgeInsets.init(top: 10.0, left: 0, bottom: 0, right: 0)
tableView.clipsToBounds = true
self.navigationItem.title = Strings.comments
view.backgroundColor = OEXStyles.shared().neutralXLight()
self.contentView.backgroundColor = OEXStyles.shared().neutralXLight()
addCommentButton.contentVerticalAlignment = .center
addCommentButton.backgroundColor = isDiscussionBlackedOut || commentsClosed ? environment.styles.neutralBase() : environment.styles.primaryXDarkColor()
addCommentButton.isEnabled = !(isDiscussionBlackedOut || commentsClosed)
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
}
func toggleAddCommentButton(enabled: Bool){
addCommentButton.backgroundColor = enabled ? environment.styles.primaryXDarkColor() : environment.styles.neutralBase()
addCommentButton.isEnabled = enabled
}
func setConstraints() {
contentView.snp.makeConstraints { make in
make.leading.equalTo(safeLeading)
make.top.equalTo(safeTop)
make.trailing.equalTo(safeTrailing)
make.bottom.equalTo(addCommentButton.snp.top)
}
addCommentButton.snp.makeConstraints{ make in
make.leading.equalTo(contentView)
make.trailing.equalTo(contentView)
make.height.equalTo(OEXStyles.shared().standardFooterHeight)
make.bottom.equalTo(safeBottom)
}
tableView.snp.makeConstraints { make in
make.leading.equalTo(contentView)
make.top.equalTo(contentView)
make.trailing.equalTo(contentView)
make.bottom.equalTo(contentView)
}
}
private func initializePaginator() {
guard let responseItem = responseItem else { return }
precondition(!responseItem.commentID.isEmpty, "Shouldn't be showing comments for empty commentID")
let paginator = WrappedPaginator(networkManager: self.environment.networkManager) {[weak self] page in
return DiscussionAPI.getComments(environment: self?.environment.router?.environment, commentID: responseItem.commentID, pageNumber: page)
}
paginationController = PaginationController(paginator: paginator, tableView: self.tableView)
}
private func loadContent() {
paginationController?.stream.listen(self, success:
{ [weak self] comments in
self?.loadController.state = .Loaded
self?.comments = comments
self?.tableView.reloadData()
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
}, failure: { [weak self] (error) -> Void in
self?.loadController.state = LoadState.failed(error: error)
})
paginationController?.loadMore()
}
private func showAddedComment(comment: DiscussionComment) {
comments.append(comment)
tableView.reloadData()
let indexPath = IndexPath(row: comments.count - 1, section: TableSection.Comments.rawValue)
tableView.scrollToRow(at: indexPath, at: .top, animated: false)
}
private func setupProfileLoader() {
guard environment.config.profilesEnabled else { return }
profileFeed = self.environment.dataManager.userProfileManager.feedForCurrentUser()
profileFeed?.output.listen(self, success: { [weak self] profile in
if var comment = self?.tempComment {
comment.hasProfileImage = !((profile.imageURL?.isEmpty) ?? true )
comment.imageURL = profile.imageURL ?? ""
self?.showAddedComment(comment: comment)
self?.tempComment = nil
}
}, failure : { _ in
Logger.logError("Profiles", "Unable to fetch profile")
})
}
// MARK - tableview delegate methods
public func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch TableSection(rawValue:section) {
case .some(.Response): return 1
case .some(.Comments): return comments.count
case .none:
assert(true, "Unexepcted table section")
return 0
}
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifierCommentCell, for: indexPath) as! DiscussionCommentCell
switch TableSection(rawValue: indexPath.section) {
case .some(.Response):
guard let responseItem = responseItem, let thread = thread else { return UITableViewCell() }
cell.useResponse(response: responseItem, viewController: self)
DiscussionHelper.updateEndorsedTitle(thread: thread, label: cell.endorsedLabel, textStyle: cell.endorsedTextStyle)
return cell
case .some(.Comments):
cell.useComment(comment: comments[indexPath.row], inViewController: self, index: indexPath.row)
return cell
case .none:
assert(false, "Unknown table section")
return UITableViewCell()
}
}
// MARK- DiscussionNewCommentViewControllerDelegate method
func newCommentController(controller: DiscussionNewCommentViewController, addedComment comment: DiscussionComment) {
responseItem?.childCount += 1
if !(paginationController?.hasNext ?? false) {
tempComment = comment
profileFeed?.refresh()
}
if let responseItem = responseItem {
delegate?.discussionCommentsView(controller: self, updatedComment: responseItem)
}
showOverlay(withMessage: Strings.discussionCommentPosted)
}
}
// Testing only
extension DiscussionCommentsViewController {
var t_loaded : OEXStream<()> {
return self.paginationController!.stream.map {_ in
return
}
}
}
| apache-2.0 | 3436cca9e1c5e9635043c0324f11eef9 | 42.707358 | 395 | 0.672265 | 5.710509 | false | false | false | false |
aslanyanhaik/Quick-Chat | QuickChat/Presenter/Messages/MessagesViewController.swift | 1 | 8392 | // MIT License
// Copyright (c) 2019 Haik Aslanyan
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class MessagesViewController: UIViewController, KeyboardHandler {
//MARK: IBOutlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var expandButton: UIButton!
@IBOutlet weak var barBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var stackViewWidthConstraint: NSLayoutConstraint!
@IBOutlet var actionButtons: [UIButton]!
//MARK: Private properties
private let manager = MessageManager()
private let imageService = ImagePickerService()
private let locationService = LocationService()
private var messages = [ObjectMessage]()
//MARK: Public properties
var conversation = ObjectConversation()
var bottomInset: CGFloat {
return view.safeAreaInsets.bottom + 50
}
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
addKeyboardObservers() {[weak self] state in
guard state else { return }
self?.tableView.scroll(to: .bottom, animated: true)
}
fetchMessages()
fetchUserName()
}
}
//MARK: Private methods
extension MessagesViewController {
private func fetchMessages() {
manager.messages(for: conversation) {[weak self] messages in
self?.messages = messages.sorted(by: {$0.timestamp < $1.timestamp})
self?.tableView.reloadData()
self?.tableView.scroll(to: .bottom, animated: true)
}
}
private func send(_ message: ObjectMessage) {
manager.create(message, conversation: conversation) {[weak self] response in
guard let weakSelf = self else { return }
if response == .failure {
weakSelf.showAlert()
return
}
weakSelf.conversation.timestamp = Int(Date().timeIntervalSince1970)
switch message.contentType {
case .none: weakSelf.conversation.lastMessage = message.message
case .photo: weakSelf.conversation.lastMessage = "Attachment"
case .location: weakSelf.conversation.lastMessage = "Location"
default: break
}
if let currentUserID = UserManager().currentUserID() {
weakSelf.conversation.isRead[currentUserID] = true
}
ConversationManager().create(weakSelf.conversation)
}
}
private func fetchUserName() {
guard let currentUserID = UserManager().currentUserID() else { return }
guard let userID = conversation.userIDs.filter({$0 != currentUserID}).first else { return }
UserManager().userData(for: userID) {[weak self] user in
guard let name = user?.name else { return }
self?.navigationItem.title = name
}
}
private func showActionButtons(_ status: Bool) {
guard !status else {
stackViewWidthConstraint.constant = 112
UIView.animate(withDuration: 0.3) {
self.expandButton.isHidden = true
self.expandButton.alpha = 0
self.actionButtons.forEach({$0.isHidden = false})
self.view.layoutIfNeeded()
}
return
}
guard stackViewWidthConstraint.constant != 32 else { return }
stackViewWidthConstraint.constant = 32
UIView.animate(withDuration: 0.3) {
self.expandButton.isHidden = false
self.expandButton.alpha = 1
self.actionButtons.forEach({$0.isHidden = true})
self.view.layoutIfNeeded()
}
}
}
//MARK: IBActions
extension MessagesViewController {
@IBAction func sendMessagePressed(_ sender: Any) {
guard let text = inputTextField.text, !text.isEmpty else { return }
let message = ObjectMessage()
message.message = text
message.ownerID = UserManager().currentUserID()
inputTextField.text = nil
showActionButtons(false)
send(message)
}
@IBAction func sendImagePressed(_ sender: UIButton) {
imageService.pickImage(from: self, allowEditing: false, source: sender.tag == 0 ? .photoLibrary : .camera) {[weak self] image in
let message = ObjectMessage()
message.contentType = .photo
message.profilePic = image
message.ownerID = UserManager().currentUserID()
self?.send(message)
self?.inputTextField.text = nil
self?.showActionButtons(false)
}
}
@IBAction func sendLocationPressed(_ sender: UIButton) {
locationService.getLocation {[weak self] response in
switch response {
case .denied:
self?.showAlert(title: "Error", message: "Please enable locattion services")
case .location(let location):
let message = ObjectMessage()
message.ownerID = UserManager().currentUserID()
message.content = location.string
message.contentType = .location
self?.send(message)
self?.inputTextField.text = nil
self?.showActionButtons(false)
}
}
}
@IBAction func expandItemsPressed(_ sender: UIButton) {
showActionButtons(true)
}
}
//MARK: UITableView Delegate & DataSource
extension MessagesViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messages[indexPath.row]
if message.contentType == .none {
let cell = tableView.dequeueReusableCell(withIdentifier: message.ownerID == UserManager().currentUserID() ? "MessageTableViewCell" : "UserMessageTableViewCell") as! MessageTableViewCell
cell.set(message)
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: message.ownerID == UserManager().currentUserID() ? "MessageAttachmentTableViewCell" : "UserMessageAttachmentTableViewCell") as! MessageAttachmentTableViewCell
cell.delegate = self
cell.set(message)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard tableView.isDragging else { return }
cell.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.3, animations: {
cell.transform = CGAffineTransform.identity
})
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = messages[indexPath.row]
switch message.contentType {
case .location:
let vc: MapPreviewController = UIStoryboard.controller(storyboard: .previews)
vc.locationString = message.content
navigationController?.present(vc, animated: true)
case .photo:
let vc: ImagePreviewController = UIStoryboard.controller(storyboard: .previews)
vc.imageURLString = message.profilePicLink
navigationController?.present(vc, animated: true)
default: break
}
}
}
//MARK: UItextField Delegate
extension MessagesViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
showActionButtons(false)
return true
}
}
//MARK: MessageTableViewCellDelegate Delegate
extension MessagesViewController: MessageTableViewCellDelegate {
func messageTableViewCellUpdate() {
tableView.beginUpdates()
tableView.endUpdates()
}
}
| mit | 46af1d6964d7558fbfec7320a1a0cd38 | 34.863248 | 219 | 0.712464 | 4.806415 | false | false | false | false |
wokalski/Diff.swift | Examples/TableViewExample/TableViewExample/TableViewController.swift | 5 | 1735 |
import UIKit
import Diff
class TableViewController: UITableViewController {
var objects = [
[
"🌞",
"🐩",
"👌🏽",
"🦄",
"👋🏻",
"🙇🏽♀️",
"🔥",
],
[
"🐩",
"🌞",
"👌🏽",
"🙇🏽♀️",
"🔥",
"👋🏻",
]
]
var currentObjects = 0 {
didSet {
tableView.animateRowChanges(
oldData: objects[oldValue],
newData: objects[currentObjects],
deletionAnimation: .right,
insertionAnimation: .right)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let addButton = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh(_:)))
self.navigationItem.rightBarButtonItem = addButton
}
func refresh(_ sender: Any) {
currentObjects = currentObjects == 0 ? 1 : 0;
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects[currentObjects].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = objects[currentObjects][indexPath.row]
return cell
}
}
| mit | 9c4e83ca5aec4066988d7bce2229b9a5 | 24.630769 | 116 | 0.532413 | 5.018072 | false | false | false | false |
kaltura/playkit-ios | Classes/Events/PlayerEvent.swift | 1 | 8664 | // ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
import AVFoundation
/// PlayerEvent is a class used to reflect player events.
@objc public class PlayerEvent: PKEvent {
@objc public static let allEventTypes: [PlayerEvent.Type] = [
canPlay, durationChanged, stopped, ended, loadedMetadata, play, pause, playing, seeking, seeked, replay,
tracksAvailable, textTrackChanged, audioTrackChanged, videoTrackChanged, playbackInfo, stateChanged,
timedMetadata, sourceSelected, loadedTimeRanges, playheadUpdate, error, errorLog, playbackStalled, playbackRate
]
// MARK: - Player Events Static Reference
/// Sent when enough data is available that the media can be played, at least for a couple of frames.
@objc public static let canPlay: PlayerEvent.Type = CanPlay.self
/// The metadata has loaded or changed, indicating a change in duration of the media. This is sent, for example, when the media has loaded enough that the duration is known.
@objc public static let durationChanged: PlayerEvent.Type = DurationChanged.self
/// Sent when playback stopped.
@objc public static let stopped: PlayerEvent.Type = Stopped.self
/// Sent when playback completes.
@objc public static let ended: PlayerEvent.Type = Ended.self
/// The media's metadata has finished loading; all attributes now contain as much useful information as they're going to.
@objc public static let loadedMetadata: PlayerEvent.Type = LoadedMetadata.self
/// Sent when playback of the media starts after having been paused; that is, when playback is resumed after a prior pause event.
@objc public static let play: PlayerEvent.Type = Play.self
/// Sent when playback is paused.
@objc public static let pause: PlayerEvent.Type = Pause.self
/// Sent when the media begins to play (either for the first time, after having been paused, or after ending and then restarting).
@objc public static let playing: PlayerEvent.Type = Playing.self
/// Sent when a seek operation begins.
@objc public static let seeking: PlayerEvent.Type = Seeking.self
/// Sent when a seek operation completes.
@objc public static let seeked: PlayerEvent.Type = Seeked.self
/// Sent when a replay operation is performed.
@objc public static let replay: PlayerEvent.Type = Replay.self
/// Sent when tracks available.
@objc public static let tracksAvailable: PlayerEvent.Type = TracksAvailable.self
/// Sent when text track has been changed.
@objc public static let textTrackChanged: PlayerEvent.Type = TextTrackChanged.self
/// Sent when audio track has been changed.
@objc public static let audioTrackChanged: PlayerEvent.Type = AudioTrackChanged.self
/// Sent when video track has been changed.
@objc public static let videoTrackChanged: PlayerEvent.Type = VideoTrackChanged.self
/// Sent when Playback Params Updated.
@objc public static let playbackInfo: PlayerEvent.Type = PlaybackInfo.self
/// Sent when player state is changed.
@objc public static let stateChanged: PlayerEvent.Type = StateChanged.self
/// Sent when timed metadata is available.
@objc public static let timedMetadata: PlayerEvent.Type = TimedMetadata.self
/// Sent when source was selected.
@objc public static let sourceSelected: PlayerEvent.Type = SourceSelected.self
/// Sent when loaded time ranges was changed, loaded time ranges represent the buffered content.
/// Could be used to show amount buffered on the playhead UI.
@objc public static let loadedTimeRanges: PlayerEvent.Type = LoadedTimeRanges.self
/// Sent when the playhead (current time) has moved.
@objc public static let playheadUpdate: PlayerEvent.Type = PlayheadUpdate.self
/// Sent when an error occurs in the player that the playback can recover from.
@objc public static let error: PlayerEvent.Type = Error.self
/// Sent when an error log event received from player (non fatal errors).
@objc public static let errorLog: PlayerEvent.Type = ErrorLog.self
/// Sent when the player has stalled. Buffering with no available data to play.
@objc public static let playbackStalled: PlayerEvent.Type = PlaybackStalled.self
/// Sent when playback rate changed and rate >= 0
@objc public static let playbackRate: PlayerEvent.Type = PlaybackRate.self
// MARK: - Player Basic Events
public class CanPlay: PlayerEvent {}
public class DurationChanged: PlayerEvent {
convenience init(duration: TimeInterval) {
self.init([EventDataKeys.duration: NSNumber(value: duration)])
}
}
public class Stopped: PlayerEvent {}
public class Ended: PlayerEvent {}
public class LoadedMetadata: PlayerEvent {}
public class Play: PlayerEvent {}
public class Pause: PlayerEvent {}
public class Playing: PlayerEvent {}
public class PlaybackRate: PlayerEvent {
convenience init(rate: Float) {
self.init([EventDataKeys.rate: NSNumber(value: rate)])
}
}
public class Seeking: PlayerEvent {
convenience init(targetSeekPosition: TimeInterval) {
self.init([EventDataKeys.targetSeekPosition: NSNumber(value: targetSeekPosition)])
}
}
public class Seeked: PlayerEvent {}
public class Replay: PlayerEvent {}
public class SourceSelected: PlayerEvent {
convenience init(mediaSource: PKMediaSource) {
self.init([EventDataKeys.mediaSource: mediaSource])
}
}
public class Error: PlayerEvent {
convenience init(nsError: NSError) {
self.init([EventDataKeys.error: nsError])
}
convenience init(error: PKError) {
self.init([EventDataKeys.error: error.asNSError])
}
}
public class ErrorLog: PlayerEvent {
convenience init(nsError: NSError) {
self.init([EventDataKeys.error: nsError])
}
convenience init(error: PKError) {
self.init([EventDataKeys.error: error.asNSError])
}
}
public class TimedMetadata: PlayerEvent {
convenience init(metadata: [AVMetadataItem]) {
self.init([EventDataKeys.metadata: metadata])
}
}
public class TracksAvailable: PlayerEvent {
convenience init(tracks: PKTracks) {
self.init([EventDataKeys.tracks: tracks])
}
}
public class TextTrackChanged: PlayerEvent {
convenience init(track: Track) {
self.init([EventDataKeys.selectedTrack: track])
}
}
public class AudioTrackChanged: PlayerEvent {
convenience init(track: Track) {
self.init([EventDataKeys.selectedTrack: track])
}
convenience init(codecDescription: String) {
self.init([EventDataKeys.codec: codecDescription.replacingOccurrences(of: "\'", with: "")])
}
}
public class VideoTrackChanged: PlayerEvent {
convenience init(bitrate: Double) {
self.init([EventDataKeys.bitrate: bitrate])
}
convenience init(codecDescription: String) {
self.init([EventDataKeys.codec: codecDescription.replacingOccurrences(of: "\'", with: "")])
}
}
public class PlaybackInfo: PlayerEvent {
convenience init(playbackInfo: PKPlaybackInfo) {
self.init([EventDataKeys.playbackInfo: playbackInfo])
}
}
public class StateChanged: PlayerEvent {
convenience init(newState: PlayerState, oldState: PlayerState) {
self.init([EventDataKeys.newState: newState as AnyObject,
EventDataKeys.oldState: oldState as AnyObject])
}
}
public class LoadedTimeRanges: PlayerEvent {
convenience init(timeRanges: [PKTimeRange]) {
self.init([EventDataKeys.timeRanges: timeRanges])
}
}
public class PlayheadUpdate: PlayerEvent {
convenience init(currentTime: TimeInterval) {
self.init([EventDataKeys.currentTime: currentTime])
}
}
public class PlaybackStalled: PlayerEvent {}
}
| agpl-3.0 | ea5197731f6e995be4863a2d221d39c9 | 42.757576 | 177 | 0.668398 | 4.821369 | false | false | false | false |
gpbl/SwiftChart | Example/SwiftChart/StockChartViewController.swift | 1 | 4912 | //
// StockChartViewController.swift
// SwiftChart
//
// Created by Giampaolo Bellavite on 07/11/14.
// Copyright (c) 2014 Giampaolo Bellavite. All rights reserved.
//
import UIKit
import SwiftChart
class StockChartViewController: UIViewController, ChartDelegate {
var selectedChart = 0
@IBOutlet weak var labelLeadingMarginConstraint: NSLayoutConstraint!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var chart: Chart!
fileprivate var labelLeadingMarginInitialConstant: CGFloat!
override func viewDidLoad() {
labelLeadingMarginInitialConstant = labelLeadingMarginConstraint.constant
initializeChart()
}
func initializeChart() {
chart.delegate = self
// Initialize data series and labels
let stockValues = getStockValues()
var serieData: [Double] = []
var labels: [Double] = []
var labelsAsString: Array<String> = []
// Date formatter to retrieve the month names
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM"
for (i, value) in stockValues.enumerated() {
serieData.append(value["close"] as! Double)
// Use only one label for each month
let month = Int(dateFormatter.string(from: value["date"] as! Date))!
let monthAsString:String = dateFormatter.monthSymbols[month - 1]
if (labels.count == 0 || labelsAsString.last != monthAsString) {
labels.append(Double(i))
labelsAsString.append(monthAsString)
}
}
let series = ChartSeries(serieData)
series.area = true
// Configure chart layout
chart.lineWidth = 0.5
chart.labelFont = UIFont.systemFont(ofSize: 12)
chart.xLabels = labels
chart.xLabelsFormatter = { (labelIndex: Int, labelValue: Double) -> String in
return labelsAsString[labelIndex]
}
chart.xLabelsTextAlignment = .center
chart.yLabelsOnRightSide = true
// Add some padding above the x-axis
chart.minY = serieData.min()! - 5
chart.add(series)
}
// Chart delegate
func didTouchChart(_ chart: Chart, indexes: Array<Int?>, x: Double, left: CGFloat) {
if let value = chart.valueForSeries(0, atIndex: indexes[0]) {
let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
label.text = numberFormatter.string(from: NSNumber(value: value))
// Align the label to the touch left position, centered
var constant = labelLeadingMarginInitialConstant + left - (label.frame.width / 2)
// Avoid placing the label on the left of the chart
if constant < labelLeadingMarginInitialConstant {
constant = labelLeadingMarginInitialConstant
}
// Avoid placing the label on the right of the chart
let rightMargin = chart.frame.width - label.frame.width
if constant > rightMargin {
constant = rightMargin
}
labelLeadingMarginConstraint.constant = constant
}
}
func didFinishTouchingChart(_ chart: Chart) {
label.text = ""
labelLeadingMarginConstraint.constant = labelLeadingMarginInitialConstant
}
func didEndTouchingChart(_ chart: Chart) {
}
func getStockValues() -> Array<Dictionary<String, Any>> {
// Read the JSON file
let filePath = Bundle.main.path(forResource: "AAPL", ofType: "json")!
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: filePath))
let json: NSDictionary = (try! JSONSerialization.jsonObject(with: jsonData!, options: [])) as! NSDictionary
let jsonValues = json["quotes"] as! Array<NSDictionary>
// Parse data
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let values = jsonValues.map { (value: NSDictionary) -> Dictionary<String, Any> in
let date = dateFormatter.date(from: value["date"]! as! String)
let close = (value["close"]! as! NSNumber).doubleValue
return ["date": date!, "close": close]
}
return values
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Redraw chart on rotation
chart.setNeedsDisplay()
}
}
| mit | 5335ee8a042c2185fda10bb5e8968e07 | 32.414966 | 115 | 0.593037 | 5.264737 | false | false | false | false |
hooman/swift | test/Constraints/closures.swift | 3 | 41298 | // RUN: %target-typecheck-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
_ = myMap(intArray, { String($0) })
_ = myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
foo({ [intArray] in $0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
_ = mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
_ = f0(X2(), {$0.g()})
// Closures with inout arguments and '__shared' conversions.
func inoutToSharedConversions() {
func fooOW<T, U>(_ f : (__owned T) -> U) {}
fooOW({ (x : Int) in return Int(5) }) // defaut-to-'__owned' allowed
fooOW({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__owned' allowed
fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed
fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__owned Int) -> Int'}}
func fooIO<T, U>(_ f : (inout T) -> U) {}
fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed
fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(inout Int) -> Int'}}
fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout Int) -> Int'}}
fooIO({ (x : __owned Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__owned Int) -> Int' to expected argument type '(inout Int) -> Int'}}
func fooSH<T, U>(_ f : (__shared T) -> U) {}
fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed
fooSH({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__shared' allowed
fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared Int) -> Int'}}
fooSH({ (x : Int) in return Int(5) }) // default-to-'__shared' allowed
}
// Autoclosure
func f1(f: @autoclosure () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{add () to forward @autoclosure parameter}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{cannot find 'not_declared' in scope}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
// <https://bugs.swift.org/browse/SR-3671>
func r21544303() {
var inSubcall = true
{
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true {
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
var v2 : Bool = false
v2 = inSubcall // expected-error {{cannot call value of non-function type 'Bool'}}
{
}
}
// <https://bugs.swift.org/browse/SR-3671>
func SR3671() {
let n = 42
func consume(_ x: Int) {}
{ consume($0) }(42)
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
({ $0(42) } { consume($0) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// This is technically a valid call, so nothing goes wrong until (42)
{ $0(3) } // expected-error {{cannot call value of non-function type '()'}}
{ consume($0) }(42)
;
({ $0(42) }) // expected-error {{cannot call value of non-function type '()'}}
{ consume($0) }(42)
;
{ $0(3) } // expected-error {{cannot call value of non-function type '()'}}
{ [n] in consume($0) }(42)
;
({ $0(42) }) // expected-error {{cannot call value of non-function type '()'}}
{ [n] in consume($0) }(42)
;
// Equivalent but more obviously unintended.
{ $0(3) } // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ consume($0) }(42)
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
({ $0(3) }) // expected-error {{cannot call value of non-function type '()'}} expected-note {{callee is here}}
{ consume($0) }(42)
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// Also a valid call (!!)
{ $0 { $0 } } { $0 { 1 } } // expected-error {{function is unused}}
consume(111)
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{cannot convert value of type 'Int' to expected element type 'Double'}}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{missing argument for parameter #1 in call}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
func callCC<U>(_ f: (CC) -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{cannot infer return type for closure with multiple statements; add explicit type to disambiguate}} {{none}}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: ((String) -> String)?,
bar: @escaping (String) -> String) {
let _: (String) -> String = foo != nil ? foo! : bar
let _: (String) -> String = foo ?? bar
}
func verify_NotAC_to_AC_failure(_ arg: () -> ()) {
func takesAC(_ arg: @autoclosure () -> ()) {}
takesAC(arg) // expected-error {{add () to forward @autoclosure parameter}} {{14-14=()}}
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable {
let wrappedMethod = { (object: AnyObject, value: T) in }
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
// expected-error@-1 {{value of optional type 'Object?' must be unwrapped to a value of type 'Object'}}
// expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
}
// Similar to SR1069 but with multiple generic arguments
func simplified1069() {
class C {}
struct S {
func genericallyNonOptional<T: AnyObject>(_ a: T, _ b: T, _ c: T) { }
// expected-note@-1 {{where 'T' = 'Optional<C>'}}
func f(_ a: C?, _ b: C?, _ c: C) {
genericallyNonOptional(a, b, c) // expected-error {{instance method 'genericallyNonOptional' requires that 'Optional<C>' be a class type}}
// expected-note @-1 {{wrapped type 'C' satisfies this requirement}}
}
}
}
// Make sure we cannot infer an () argument from an empty parameter list.
func acceptNothingToInt (_: () -> Int) {}
func testAcceptNothingToInt(ac1: @autoclosure () -> Int) {
acceptNothingToInt({ac1($0)}) // expected-error@:27 {{argument passed to call that takes no arguments}}
// expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}}
}
// <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
struct Thing {
init?() {}
}
// This throws a compiler error
let things = Thing().map { thing in // expected-error {{cannot infer return type for closure with multiple statements; add explicit type to disambiguate}} {{34-34=-> <#Result#> }}
// Commenting out this makes it compile
_ = thing
return thing
}
// <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches
func r21675896(file : String) {
let x: String = { // expected-error {{cannot infer return type for closure with multiple statements; add explicit type to disambiguate}} {{20-20= () -> <#Result#> in }}
if true {
return "foo"
}
else {
return file
}
}().pathExtension
}
// <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
func ident<T>(_ t: T) -> T {}
var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}}
// <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block
var afterMessageCount : Int?
func uintFunc() -> UInt {}
func takeVoidVoidFn(_ a : () -> ()) {}
takeVoidVoidFn { () -> Void in
afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} {{23-23=Int(}} {{33-33=)}}
}
// <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure
func f19997471(_ x: String) {} // expected-note {{candidate expects value of type 'String' for parameter #1 (got 'T')}}
func f19997471(_ x: Int) {} // expected-note {{candidate expects value of type 'Int' for parameter #1 (got 'T')}}
func someGeneric19997471<T>(_ x: T) {
takeVoidVoidFn {
f19997471(x) // expected-error {{no exact matches in call to global function 'f19997471'}}
}
}
// <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r }
[0].map { // expected-error {{cannot infer return type for closure with multiple statements; add explicit type to disambiguate}} {{5-5=-> <#Result#> }}
_ in
let r = (1,2).0
return r
}
// <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type
func rdar21078316() {
var foo : [String : String]?
var bar : [(String, String)]?
bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) throws -> [(String, String)]' expects 1 argument, but 2 were used in closure body}}
}
// <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure
var numbers = [1, 2, 3]
zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Array<Int>.Element, Array<Int>.Element)' has no member '2'}}
// <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type'
func foo20868864(_ callback: ([String]) -> ()) { }
func rdar20868864(_ s: String) {
var s = s
foo20868864 { (strings: [String]) in
s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}}
}
}
// <rdar://problem/22058555> crash in cs diags in withCString
func r22058555() {
var firstChar: UInt8 = 0
"abc".withCString { chars in
firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} {{17-17=UInt8(}} {{25-25=)}}
}
}
// <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type
func r20789423() {
class C {
func f(_ value: Int) { }
}
let p: C
print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}}
// expected-error@-1:11 {{cannot call value of non-function type '()'}}
let _f = { (v: Int) in // expected-error {{cannot infer return type for closure with multiple statements; add explicit type to disambiguate}} {{23-23=-> <#Result#> }}
print("a")
return "hi"
}
}
// In the example below, SR-2505 started preferring C_SR_2505.test(_:) over
// test(it:). Prior to Swift 5.1, we emulated the old behavior. However,
// that behavior is inconsistent with the typical approach of preferring
// overloads from the concrete type over one from a protocol, so we removed
// the hack.
protocol SR_2505_Initable { init() }
struct SR_2505_II : SR_2505_Initable {}
protocol P_SR_2505 {
associatedtype T: SR_2505_Initable
}
extension P_SR_2505 {
func test(it o: (T) -> Bool) -> Bool {
return o(T.self())
}
}
class C_SR_2505 : P_SR_2505 {
typealias T = SR_2505_II
func test(_ o: Any) -> Bool {
return false
}
func call(_ c: C_SR_2505) -> Bool {
// Note: the diagnostic about capturing 'self', indicates that we have
// selected test(_) rather than test(it:)
return c.test { o in test(o) } // expected-error{{call to method 'test' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} expected-note{{reference 'self.' explicitly}}
}
}
let _ = C_SR_2505().call(C_SR_2505())
// <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic
extension Collection {
func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index {
return startIndex
}
}
func fn_r28909024(n: Int) {
return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}} // expected-note {{did you mean to add a return type?}}
_ in true
}
}
// SR-2994: Unexpected ambiguous expression in closure with generics
struct S_2994 {
var dataOffset: Int
}
class C_2994<R> {
init(arg: (R) -> Void) {}
}
func f_2994(arg: String) {}
func g_2994(arg: Int) -> Double {
return 2
}
C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}}
let _ = { $0[$1] }(1, 1) // expected-error {{value of type 'Int' has no subscripts}}
// FIXME: Better diagnostic here would be `assigning a variable to itself` but binding ordering change exposed a but in diagnostics
let _ = { $0 = ($0 = {}) } // expected-error {{function produces expected type '()'; did you mean to call it with '()'?}}
let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}}
// https://bugs.swift.org/browse/SR-403
// The () -> T => () -> () implicit conversion was kicking in anywhere
// inside a closure result, not just at the top-level.
let mismatchInClosureResultType : (String) -> ((Int) -> Void) = {
(String) -> ((Int) -> Void) in
return { }
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{13-13= _ in}}
}
// SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS
func sr3520_1<T>(_ g: (inout T) -> Int) {}
sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
// This test makes sure that having closure with inout argument doesn't crash with member lookup
struct S_3520 {
var number1: Int
}
func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} // expected-note {{in call to function 'sr3520_set_via_closure'}}
sr3520_set_via_closure({ $0.number1 = $1 })
// expected-error@-1 {{generic parameter 'S' could not be inferred}}
// expected-error@-2 {{unable to infer type of a closure parameter '$1' in the current context}}
// SR-3073: UnresolvedDotExpr in single expression closure
struct SR3073Lense<Whole, Part> {
let set: (inout Whole, Part) -> ()
}
struct SR3073 {
var number1: Int
func lenses() {
let _: SR3073Lense<SR3073, Int> = SR3073Lense(
set: { $0.number1 = $1 } // ok
)
}
}
// SR-3479: Segmentation fault and other error for closure with inout parameter
func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {}
func sr3497() {
let _ = sr3497_unfold((0, 0)) { s in 0 } // ok
}
// SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs
let _: ((Any?) -> Void) = { (arg: Any!) in }
// This example was rejected in 3.0 as well, but accepting it is correct.
let _: ((Int?) -> Void) = { (arg: Int!) in }
// rdar://30429709 - We should not attempt an implicit conversion from
// () -> T to () -> Optional<()>.
func returnsArray() -> [Int] { return [] }
returnsArray().compactMap { $0 }.compactMap { }
// expected-warning@-1 {{expression of type 'Int' is unused}}
// expected-warning@-2 {{result of call to 'compactMap' is unused}}
// rdar://problem/30271695
_ = ["hi"].compactMap { $0.isEmpty ? nil : $0 }
// rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
func r32432145(_ a: () -> ()) {}
r32432145 { _ in let _ = 42 }
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
r32432145 { _ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}}
print("answer is 42")
}
r32432145 { _,_ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}}
print("answer is 42")
}
// rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller
[1, 2].first { $0.foo = 3 }
// expected-error@-1 {{value of type 'Int' has no member 'foo'}}
// rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem
protocol A_SR_5030 {
associatedtype Value
func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U>
}
struct B_SR_5030<T> : A_SR_5030 {
typealias Value = T
func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() }
}
func sr5030_exFalso<T>() -> T {
fatalError()
}
extension A_SR_5030 {
func foo() -> B_SR_5030<Int> {
let tt : B_SR_5030<Int> = sr5030_exFalso()
return tt.map { x in (idx: x) }
// expected-error@-1 {{cannot convert value of type '(idx: Int)' to closure result type 'Int'}}
}
}
// rdar://problem/33296619
let u = rdar33296619().element //expected-error {{cannot find 'rdar33296619' in scope}}
[1].forEach { _ in
_ = "\(u)"
_ = 1 + "hi" // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
class SR5666 {
var property: String?
}
func testSR5666(cs: [SR5666?]) -> [String?] {
return cs.map({ c in
let a = c.propertyWithTypo ?? "default"
// expected-error@-1 {{value of type 'SR5666?' has no member 'propertyWithTypo'}}
let b = "\(a)"
return b
})
}
// Ensure that we still do the appropriate pointer conversion here.
_ = "".withCString { UnsafeMutableRawPointer(mutating: $0) }
// rdar://problem/34077439 - Crash when pre-checking bails out and
// leaves us with unfolded SequenceExprs inside closure body.
_ = { (offset) -> T in // expected-error {{cannot find type 'T' in scope}}
return offset ? 0 : 0
}
struct SR5202<T> {
func map<R>(fn: (T) -> R) {}
}
SR5202<()>().map{ return 0 }
SR5202<()>().map{ _ in return 0 }
SR5202<Void>().map{ return 0 }
SR5202<Void>().map{ _ in return 0 }
func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) {
var x = item
update(&x)
}
var sr3250_arg = 42
sr3520_2(sr3250_arg) { $0 += 3 } // ok
// SR-1976/SR-3073: Inference of inout
func sr1976<T>(_ closure: (inout T) -> Void) {}
sr1976({ $0 += 2 }) // ok
// rdar://problem/33429010
struct I_33429010 : IteratorProtocol {
func next() -> Int? {
fatalError()
}
}
extension Sequence {
public func rdar33429010<Result>(into initialResult: Result,
_ nextPartialResult: (_ partialResult: inout Result, Iterator.Element) throws -> ()
) rethrows -> Result {
return initialResult
}
}
extension Int {
public mutating func rdar33429010_incr(_ inc: Int) {
self += inc
}
}
func rdar33429010_2() {
let iter = I_33429010()
var acc: Int = 0 // expected-warning {{}}
let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0 + $1 })
// expected-warning@-1 {{result of operator '+' is unused}}
let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0.rdar33429010_incr($1) })
}
class P_33429010 {
var name: String = "foo"
}
class C_33429010 : P_33429010 {
}
func rdar33429010_3() {
let arr = [C_33429010()]
let _ = arr.map({ ($0.name, $0 as P_33429010) }) // Ok
}
func rdar36054961() {
func bar(dict: [String: (inout String, Range<String.Index>, String) -> Void]) {}
bar(dict: ["abc": { str, range, _ in
str.replaceSubrange(range, with: str[range].reversed())
}])
}
protocol P_37790062 {
associatedtype T
var elt: T { get }
}
func rdar37790062() {
struct S<T> {
init(_ a: () -> T, _ b: () -> T) {}
}
class C1 : P_37790062 {
typealias T = Int
var elt: T { return 42 }
}
class C2 : P_37790062 {
typealias T = (String, Int, Void)
var elt: T { return ("question", 42, ()) }
}
func foo() -> Int { return 42 }
func bar() -> Void {}
func baz() -> (String, Int) { return ("question", 42) }
func bzz<T>(_ a: T) -> T { return a }
func faz<T: P_37790062>(_ a: T) -> T.T { return a.elt }
_ = S({ foo() }, { bar() }) // expected-warning {{result of call to 'foo()' is unused}}
_ = S({ baz() }, { bar() }) // expected-warning {{result of call to 'baz()' is unused}}
_ = S({ bzz(("question", 42)) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(String.self) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(((), (()))) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ bzz(C1()) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
_ = S({ faz(C2()) }, { bar() }) // expected-warning {{result of call to 'faz' is unused}}
}
// <rdar://problem/39489003>
typealias KeyedItem<K, T> = (key: K, value: T)
protocol Node {
associatedtype T
associatedtype E
associatedtype K
var item: E {get set}
var children: [(key: K, value: T)] {get set}
}
extension Node {
func getChild(for key:K)->(key: K, value: T) {
return children.first(where: { (item:KeyedItem) -> Bool in
return item.key == key
// expected-error@-1 {{binary operator '==' cannot be applied to two 'Self.K' operands}}
})!
}
}
// Make sure we don't allow this anymore
func takesTwo(_: (Int, Int) -> ()) {}
func takesTwoInOut(_: (Int, inout Int) -> ()) {}
takesTwo { _ in } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
takesTwoInOut { _ in } // expected-error {{contextual closure type '(Int, inout Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
_ = x.filter { ($0 + y) > 42 } // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
}
// rdar://problem/42337247
func overloaded(_ handler: () -> Int) {} // expected-note {{found this candidate}}
func overloaded(_ handler: () -> Void) {} // expected-note {{found this candidate}}
overloaded { } // empty body => inferred as returning ()
overloaded { print("hi") } // single-expression closure => typechecked with body
overloaded { print("hi"); print("bye") } // multiple expression closure without explicit returns; can default to any return type
// expected-error@-1 {{ambiguous use of 'overloaded'}}
func not_overloaded(_ handler: () -> Int) {}
// expected-note@-1 {{'not_overloaded' declared here}}
not_overloaded { } // empty body
// expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}}
not_overloaded { print("hi") } // single-expression closure
// expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}}
// no error in -typecheck, but dataflow diagnostics will complain about missing return
not_overloaded { print("hi"); print("bye") } // multiple expression closure
func apply(_ fn: (Int) throws -> Int) rethrows -> Int {
return try fn(0)
}
enum E : Error {
case E
}
func test() -> Int? {
return try? apply({ _ in throw E.E })
}
var fn: () -> [Int] = {}
// expected-error@-1 {{cannot convert value of type '[Int]' to closure result type '()'}}
fn = {}
// expected-error@-1 {{cannot assign value of type '() -> ()' to type '() -> [Int]'}}
func test<Instances : Collection>(
_ instances: Instances,
_ fn: (Instances.Index, Instances.Index) -> Bool
) { fatalError() }
test([1]) { _, _ in fatalError(); () }
// rdar://problem/40537960 - Misleading diagnostic when using closure with wrong type
protocol P_40537960 {}
func rdar_40537960() {
struct S {
var v: String
}
struct L : P_40537960 {
init(_: String) {}
}
struct R<T : P_40537960> {
init(_: P_40537960) {}
}
struct A<T: Collection, P: P_40537960> { // expected-note {{'P' declared as parameter to type 'A'}}
typealias Data = T.Element
init(_: T, fn: (Data) -> R<P>) {}
}
var arr: [S] = []
_ = A(arr, fn: { L($0.v) })
// expected-error@-1 {{generic parameter 'P' could not be inferred}}
// expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<[S], <#P: P_40537960#>>}}
}
// rdar://problem/45659733
func rdar_45659733() {
func foo<T : BinaryInteger>(_: AnyHashable, _: T) {}
func bar(_ a: Int, _ b: Int) {
_ = (a ..< b).map { i in foo(i, i) } // Ok
}
struct S<V> {
func map<T>(
get: @escaping (V) -> T,
set: @escaping (inout V, T) -> Void
) -> S<T> {
fatalError()
}
subscript<T>(
keyPath: WritableKeyPath<V, T?>,
default defaultValue: T
) -> S<T> {
return map(
get: { $0[keyPath: keyPath] ?? defaultValue },
set: { $0[keyPath: keyPath] = $1 }
) // Ok, make sure that we deduce result to be S<T>
}
}
}
func rdar45771997() {
struct S {
mutating func foo() {}
}
let _: Int = { (s: inout S) in s.foo() }
// expected-error@-1 {{cannot convert value of type '(inout S) -> ()' to specified type 'Int'}}
}
struct rdar30347997 {
func withUnsafeMutableBufferPointer(body : (inout Int) -> ()) {}
func foo() {
withUnsafeMutableBufferPointer { // expected-error {{cannot convert value of type '(Int) -> ()' to expected argument type '(inout Int) -> ()'}}
(b : Int) in
}
}
}
struct rdar43866352<Options> {
func foo() {
let callback: (inout Options) -> Void
callback = { (options: Options) in } // expected-error {{cannot assign value of type '(Options) -> ()' to type '(inout Options) -> Void'}}
}
}
extension Hashable {
var self_: Self {
return self
}
}
do {
struct S<
C : Collection,
I : Hashable,
R : Numeric
> {
init(_ arr: C,
id: KeyPath<C.Element, I>,
content: @escaping (C.Element) -> R) {}
}
func foo(_ arr: [Int]) {
_ = S(arr, id: \.self_) {
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{30-30=_ in }}
return 42
}
}
}
// Don't allow result type of a closure to end up as a noescape type
// The funny error is because we infer the type of badResult as () -> ()
// via the 'T -> U => T -> ()' implicit conversion.
let badResult = { (fn: () -> ()) in fn }
// expected-error@-1 {{function is unused}}
// rdar://problem/55102498 - closure's result type can't be inferred if the last parameter has a default value
func test_trailing_closure_with_defaulted_last() {
func foo<T>(fn: () -> T, value: Int = 0) {}
foo { 42 } // Ok
foo(fn: { 42 }) // Ok
}
// Test that even in multi-statement closure case we still pick up `(Action) -> Void` over `Optional<(Action) -> Void>`.
// Such behavior used to rely on ranking of partial solutions but with delayed constraint generation of closure bodies
// it's no longer the case, so we need to make sure that even in case of complete solutions we still pick the right type.
protocol Action { }
protocol StateType { }
typealias Fn = (Action) -> Void
typealias Middleware<State> = (@escaping Fn, @escaping () -> State?) -> (@escaping Fn) -> Fn
class Foo<State: StateType> {
var state: State!
var fn: Fn!
init(middleware: [Middleware<State>]) {
self.fn = middleware
.reversed()
.reduce({ action in },
{ (fun, middleware) in // Ok, to type-check result type has to be `(Action) -> Void`
let dispatch: (Action) -> Void = { _ in }
let getState = { [weak self] in self?.state }
return middleware(dispatch, getState)(fun)
})
}
}
// Make sure that `String...` is translated into `[String]` in the body
func test_explicit_variadic_is_interpreted_correctly() {
_ = { (T: String...) -> String in T[0] + "" } // Ok
}
// rdar://problem/59208419 - closure result type is incorrectly inferred to be a supertype
func test_correct_inference_of_closure_result_in_presence_of_optionals() {
class A {}
class B : A {}
func foo(_: B) -> Int? { return 42 }
func bar<T: A>(_: (A) -> T?) -> T? {
return .none
}
guard let v = bar({ $0 as? B }),
let _ = foo(v) // Ok, v is inferred as `B`
else {
return;
}
}
// rdar://problem/59741308 - inference fails with tuple element has to joined to supertype
func rdar_59741308() {
class Base {
func foo(_: Int) {}
}
class A : Base {}
class B : Base {}
func test() {
// Note that `0`, and `1` here are going to be type variables
// which makes join impossible until it's already to late for
// it to be useful.
[(A(), 0), (B(), 1)].forEach { base, value in
base.foo(value) // Ok
}
}
}
func r60074136() {
func takesClosure(_ closure: ((Int) -> Void) -> Void) {}
takesClosure { ((Int) -> Void) -> Void in // expected-warning {{unnamed parameters must be written with the empty name '_'}}
}
}
func rdar52204414() {
let _: () -> Void = { return 42 }
// expected-error@-1 {{cannot convert value of type 'Int' to closure result type 'Void'}}
let _ = { () -> Void in return 42 }
// expected-error@-1 {{declared closure result 'Int' is incompatible with contextual type 'Void'}}
}
// SR-12291 - trailing closure is used as an argument to the last (positionally) parameter.
// Note that this was accepted prior to Swift 5.3. SE-0286 changed the
// order of argument resolution and made it ambiguous.
func overloaded_with_default(a: () -> Int, b: Int = 0, c: Int = 0) {} // expected-note{{found this candidate}}
func overloaded_with_default(b: Int = 0, c: Int = 0, a: () -> Int) {} // expected-note{{found this candidate}}
overloaded_with_default { 0 } // expected-error{{ambiguous use of 'overloaded_with_default'}}
func overloaded_with_default_and_autoclosure<T>(_ a: @autoclosure () -> T, b: Int = 0) {}
func overloaded_with_default_and_autoclosure<T>(b: Int = 0, c: @escaping () -> T?) {}
overloaded_with_default_and_autoclosure { 42 } // Ok
overloaded_with_default_and_autoclosure(42) // Ok
// SR-12815 - `error: type of expression is ambiguous without more context` in many cases where methods are missing
func sr12815() {
let _ = { a, b in }
// expected-error@-1 {{unable to infer type of a closure parameter 'a' in the current context}}
// expected-error@-2 {{unable to infer type of a closure parameter 'b' in the current context}}
_ = .a { b in } // expected-error {{cannot infer contextual base in reference to member 'a'}}
struct S {}
func test(s: S) {
S.doesntExist { b in } // expected-error {{type 'S' has no member 'doesntExist'}}
s.doesntExist { b in } // expected-error {{value of type 'S' has no member 'doesntExist'}}
s.doesntExist1 { v in } // expected-error {{value of type 'S' has no member 'doesntExist1'}}
.doesntExist2() { $0 }
}
}
// Make sure we can infer generic arguments in an explicit result type.
let explicitUnboundResult1 = { () -> Array in [0] }
let explicitUnboundResult2: (Array<Bool>) -> Array<Int> = {
(arr: Array) -> Array in [0]
}
// FIXME: Should we prioritize the contextual result type and infer Array<Int>
// rather than using a type variable in these cases?
// expected-error@+1 {{unable to infer closure type in the current context}}
let explicitUnboundResult3: (Array<Bool>) -> Array<Int> = {
(arr: Array) -> Array in [true]
}
// rdar://problem/71525503 - Assertion failed: (!shouldHaveDirectCalleeOverload(call) && "Should we have resolved a callee for this?")
func test_inout_with_invalid_member_ref() {
struct S {
static func createS(_ arg: inout Int) -> S { S() }
}
class C {
static subscript(s: (Int) -> Void) -> Bool { get { return false } }
}
let _: Bool = C[{ .createS(&$0) }]
// expected-error@-1 {{value of tuple type 'Void' has no member 'createS'}}
// expected-error@-2 {{cannot pass immutable value as inout argument: '$0' is immutable}}
}
// rdar://problem/74435602 - failure to infer a type for @autoclosure parameter.
func rdar_74435602(error: Error?) {
func accepts_autoclosure<T>(_ expression: @autoclosure () throws -> T) {}
accepts_autoclosure({
if let failure = error {
throw failure
}
})
}
// SR-14280
let _: (@convention(block) () -> Void)? = Bool.random() ? nil : {} // OK
let _: (@convention(thin) () -> Void)? = Bool.random() ? nil : {} // OK
let _: (@convention(c) () -> Void)? = Bool.random() ? nil : {} // OK on type checking, diagnostics are deffered to SIL
let _: (@convention(block) () -> Void)? = Bool.random() ? {} : {} // OK
let _: (@convention(thin) () -> Void)? = Bool.random() ? {} : {} // OK
let _: (@convention(c) () -> Void)? = Bool.random() ? {} : {} // OK on type checking, diagnostics are deffered to SIL
// Make sure that diagnostic is attached to the closure even when body is empty (implicitly returns `Void`)
var emptyBodyMismatch: () -> Int {
return { // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
return
}
}
// rdar://76250381 - crash when passing an argument to a closure that takes no arguments
struct R_76250381<Result, Failure: Error> {
func test(operation: @escaping () -> Result) -> Bool {
return try self.crash { group in // expected-error {{contextual closure type '() -> Result' expects 0 arguments, but 1 was used in closure body}}
operation(&group) // expected-error {{argument passed to call that takes no arguments}}
}
}
func crash(_: @escaping () -> Result) -> Bool {
return false
}
}
// SR-13483
(0..<10).map { x, y in }
// expected-error@-1 {{contextual closure type '(Range<Int>.Element) throws -> ()' (aka '(Int) throws -> ()') expects 1 argument, but 2 were used in closure body}}
(0..<10).map { x, y, z in }
// expected-error@-1 {{contextual closure type '(Range<Int>.Element) throws -> ()' (aka '(Int) throws -> ()') expects 1 argument, but 3 were used in closure body}}
(0..<10).map { x, y, z, w in }
// expected-error@-1 {{contextual closure type '(Range<Int>.Element) throws -> ()' (aka '(Int) throws -> ()') expects 1 argument, but 4 were used in closure body}}
// rdar://77022842 - crash due to a missing argument to a ternary operator
func rdar77022842(argA: Bool? = nil, argB: Bool? = nil) {
if let a = argA ?? false, if let b = argB ?? {
// expected-error@-1 {{initializer for conditional binding must have Optional type, not 'Bool'}}
// expected-error@-2 {{cannot convert value of type '() -> ()' to expected argument type 'Bool?'}}
// expected-error@-3 {{expected expression in conditional}}
} // expected-error {{expected '{' after 'if' condition}}
}
// rdar://76058892 - spurious ambiguity diagnostic
func rdar76058892() {
struct S {
var test: Int = 0
}
func test(_: Int) {}
func test(_: () -> String) {}
func experiment(arr: [S]?) {
test { // expected-error {{contextual closure type '() -> String' expects 0 arguments, but 1 was used in closure body}}
if let arr = arr {
arr.map($0.test) // expected-note {{anonymous closure parameter '$0' is used here}}
}
}
}
}
// rdar://78917861 - Invalid generic type parameter inference
func rdar78917861() {
class Cell {}
class MyCell : Cell {}
class DataCollection<D, C: Cell> {
}
class MyCollection {
typealias DataType = String
typealias CellType = MyCell
var data: DataCollection<DataType, CellType>
init() {
self.data = DataCollection<DataType, CellType>()
}
}
class Test {
let collection = MyCollection()
lazy var prop: DataCollection = {
collection.data // Ok
// Since contextual type `DataCollection` doesn't specify generic parameters they have to be inferred
// but that has to wait until the closure is resolved because types can flow both ways
}()
}
}
| apache-2.0 | b8cbb5e02f2a5543e169aad8e6fff945 | 34.448927 | 286 | 0.628699 | 3.433203 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.