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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dehesa/Metal | books/07 - Mipmapping/Sources/Common/Generator.swift | 1 | 13455 | import Foundation
import CoreGraphics
import Metal
import simd
/// List the generators provided by this binary.
enum Generator {
/// Cube vertices/indices generator.
enum Cube {
/// Cube's point
struct Vertex {
var position: SIMD4<Float>
var normal: SIMD4<Float>
var texCoords: SIMD2<Float>
}
/// Index to a cube's point.
typealias Index = UInt16
/// Possible errors throwable by the cube generator.
enum Error: Swift.Error {
case failedToCreateVertexBuffer(vertices: [Cube.Vertex])
case failedToCreateIndexBuffer(indices: [Cube.Index])
}
/// Makes a Metal buffer given a specific cube size (in model view units).
/// - parameter device: Metal device where the buffers will be stored.
/// - parameter size: Side square size.
/// - Vertex & Index buffer for a perfect square.
static func makeBuffers(device: MTLDevice, size: Float) throws -> (vertices: MTLBuffer, indices: MTLBuffer) {
/// Half side and normal to be used as coordinates.
let (s, n): (Float, Float) = (0.5*size, 1)
// Points
let lbf = SIMD4<Float>(x: -s, y: -s, z: -s, w: 1) // x: left, y: bottom, z: front
let lbb = SIMD4<Float>(x: -s, y: -s, z: s, w: 1) // x: right, y: bottom, z: back
let ltf = SIMD4<Float>(x: -s, y: s, z: -s, w: 1)
let ltb = SIMD4<Float>(x: -s, y: s, z: s, w: 1)
let rbf = SIMD4<Float>(x: s, y: -s, z: -s, w: 1)
let rbb = SIMD4<Float>(x: s, y: -s, z: s, w: 1)
let rtf = SIMD4<Float>(x: s, y: s, z: -s, w: 1)
let rtb = SIMD4<Float>(x: s, y: s, z: s, w: 1)
// Normals
let nx = SIMD4<Float>(x: -n, y: 0, z: 0, w: 0)
let px = SIMD4<Float>(x: n, y: 0, z: 0, w: 0)
let ny = SIMD4<Float>(x: 0, y: -n, z: 0, w: 0)
let py = SIMD4<Float>(x: 0, y: n, z: 0, w: 0)
let nz = SIMD4<Float>(x: 0, y: 0, z: -n, w: 0)
let pz = SIMD4<Float>(x: 0, y: 0, z: n, w: 0)
// Textures
let lt = SIMD2<Float>(x: 0, y: 0) // u: left, v: top
let lb = SIMD2<Float>(x: 0, y: 1) // u: left, v: bottom
let rt = SIMD2<Float>(x: 1, y: 0) // u: right, v: top
let rb = SIMD2<Float>(x: 1, y: 1) // u: right, v: bottom
let vertices: [Vertex] = [
// -X
Vertex(position: lbf, normal: nx, texCoords: lt),
Vertex(position: lbb, normal: nx, texCoords: lb),
Vertex(position: ltb, normal: nx, texCoords: rb),
Vertex(position: ltf, normal: nx, texCoords: rt),
// +X
Vertex(position: rbb, normal: px, texCoords: lt),
Vertex(position: rbf, normal: px, texCoords: lb),
Vertex(position: rtf, normal: px, texCoords: rb),
Vertex(position: rtb, normal: px, texCoords: rt),
// -Y
Vertex(position: lbf, normal: ny, texCoords: lt),
Vertex(position: rbf, normal: ny, texCoords: lb),
Vertex(position: rbb, normal: ny, texCoords: rb),
Vertex(position: lbb, normal: ny, texCoords: rt),
// +Y
Vertex(position: ltb, normal: py, texCoords: lt),
Vertex(position: rtb, normal: py, texCoords: lb),
Vertex(position: rtf, normal: py, texCoords: rb),
Vertex(position: ltf, normal: py, texCoords: rt),
// -Z
Vertex(position: rbf, normal: nz, texCoords: lt),
Vertex(position: lbf, normal: nz, texCoords: lb),
Vertex(position: ltf, normal: nz, texCoords: rb),
Vertex(position: rtf, normal: nz, texCoords: rt),
// +Z
Vertex(position: lbb, normal: pz, texCoords: lt),
Vertex(position: rbb, normal: pz, texCoords: lb),
Vertex(position: rtb, normal: pz, texCoords: rb),
Vertex(position: ltb, normal: pz, texCoords: rt)
]
guard let vertexBuffer = device.makeBuffer(bytes: vertices, length: vertices.count * MemoryLayout<Vertex>.stride) else {
throw Error.failedToCreateVertexBuffer(vertices: vertices)
}
let indices: [Index] = [
3, 1, 2, 0, 1, 3,
7, 5, 6, 4, 5, 7,
11, 9, 10, 8, 9, 11,
15, 13, 14, 12, 13, 15,
19, 17, 18, 16, 17, 19,
23, 21, 22, 20, 21, 23,
]
guard let indexBuffer = device.makeBuffer(bytes: indices, length: indices.count * MemoryLayout<Index>.stride) else {
throw Error.failedToCreateIndexBuffer(indices: indices)
}
vertexBuffer.label = "io.dehesa.metal.buffers.vertices"
indexBuffer.label = "io.dehesa.metal.buffers.indices"
return (vertexBuffer, indexBuffer)
}
}
/// Checkboard texture generators.
enum Texture {
private static let bytesPerPixel = 4
/// List possible errors when generating textures
enum Error: Swift.Error {
case failedToCreateTexture(device: MTLDevice)
case failedToCreateSampler(device: MTLDevice)
case failedToCreateCheckerboard(size: CGSize, tileCount: Int)
case failedtoCreateResizedCheckboard(size: CGSize)
}
/// Generates the black & white checkboard texture.
static func makeSimpleCheckerboard(size: CGSize, tileCount: Int, pixelFormat: MTLPixelFormat, with metal: (device: MTLDevice, queue: MTLCommandQueue)) throws -> MTLTexture {
let bytesPerRow = bytesPerPixel * Int(size.width)
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: Int(size.width), height: Int(size.height), mipmapped: true)
guard let texture = metal.device.makeTexture(descriptor: descriptor) else { throw Error.failedToCreateTexture(device: metal.device) }
(try _makeCheckerboardImage(size: size, tileCount: tileCount)).data.withUnsafeBytes { (ptr) in
let region = MTLRegionMake2D(0, 0, Int(size.width), Int(size.height))
texture.replace(region: region, mipmapLevel: 0, withBytes: ptr.baseAddress!, bytesPerRow: bytesPerRow)
}
guard let buffer = metal.queue.makeCommandBuffer(),
let encoder = buffer.makeBlitCommandEncoder() else { throw Error.failedToCreateTexture(device: metal.device) }
encoder.generateMipmaps(for: texture)
encoder.endEncoding()
return texture
}
/// Generates the tinted checkboard texture.
static func makeTintedCheckerboard(size: CGSize, tileCount: Int, pixelFormat: MTLPixelFormat, with device: MTLDevice) throws -> MTLTexture {
let bytesPerRow = bytesPerPixel * Int(size.width)
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: Int(size.width), height: Int(size.height), mipmapped: true)
guard let texture = device.makeTexture(descriptor: descriptor) else { throw Error.failedToCreateTexture(device: device) }
let (data, image) = try _makeCheckerboardImage(size: size, tileCount: tileCount)
data.withUnsafeBytes { (ptr) in
let region = MTLRegionMake2D(0, 0, Int(size.width), Int(size.height))
texture.replace(region: region, mipmapLevel: 0, withBytes: ptr.baseAddress!, bytesPerRow: bytesPerRow)
}
var (level, mipWidth, mipHeight, levelImage) = (1, texture.width/2, texture.height/2, image)
while mipWidth > 1 && mipHeight > 1 {
let mipBytesPerRow = bytesPerPixel * mipWidth
let tintColor = _makeTintColor(level: level - 1)
let scaled = try _makeResizeImage(image: levelImage, size: CGSize(width: mipWidth, height: mipHeight), tintColor: tintColor)
levelImage = scaled.image
scaled.data.withUnsafeBytes { (ptr) in
let region = MTLRegionMake2D(0, 0, mipWidth, mipHeight)
texture.replace(region: region, mipmapLevel: level, withBytes: ptr.baseAddress!, bytesPerRow: mipBytesPerRow)
}
mipWidth /= 2
mipHeight /= 2
level += 1
}
return texture
}
/// Generates the depth texture for a cube
static func makeDepth(size: CGSize, pixelFormat: MTLPixelFormat, with device: MTLDevice) throws -> MTLTexture {
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: Int(size.width), height: Int(size.height), mipmapped: false).set {
$0.usage = .renderTarget
$0.storageMode = .`private`
}
guard let depthTexture = device.makeTexture(descriptor: descriptor) else { throw Error.failedToCreateTexture(device: device) }
return depthTexture
}
/// Generates the samplers for the textures.
static func makeSamplers(with device: MTLDevice) throws -> (notMip: MTLSamplerState, nearestMip: MTLSamplerState, linearMip: MTLSamplerState) {
let descriptor = MTLSamplerDescriptor().set {
($0.minFilter, $0.magFilter) = (.linear, .linear)
($0.sAddressMode, $0.tAddressMode) = (.clampToEdge, .clampToEdge)
}
descriptor.mipFilter = .notMipmapped
guard let notMip = device.makeSamplerState(descriptor: descriptor) else { throw Error.failedToCreateSampler(device: device) }
descriptor.mipFilter = .nearest
guard let nearest = device.makeSamplerState(descriptor: descriptor) else { throw Error.failedToCreateSampler(device: device) }
descriptor.mipFilter = .linear
guard let linear = device.makeSamplerState(descriptor: descriptor) else { throw Error.failedToCreateSampler(device: device) }
return (notMip, nearest, linear)
}
}
}
private extension Generator.Texture {
/// Returns a tintColor depending on the mip level.
static func _makeTintColor(level: Int) -> CGColor {
switch level {
case 0: return CGColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1) // red
case 1: return CGColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 1) // orange
case 2: return CGColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 1) // yellow
case 3: return CGColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1) // green
case 4: return CGColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1) // blue
case 5: return CGColor(red: 0.5, green: 0.0, blue: 1.0, alpha: 1) // indigo
default: return CGColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 1) // purple
}
}
/// Returns an array of bytes with the data of the checkboard image (and as a convenience a `CGImage` of that bytes array.
static func _makeCheckerboardImage(size: CGSize, tileCount: Int) throws -> (data: Data, image: CGImage) {
let (width, height) = (Int(size.width), Int(size.height))
guard width % tileCount == 0,
height % tileCount == 0 else { throw Error.failedToCreateCheckerboard(size: size, tileCount: tileCount) }
let bytes: (count: Int, alignment: Int) = (bytesPerPixel * width * height, MemoryLayout<UInt8>.alignment)
let ptr = UnsafeMutableRawPointer.allocate(byteCount: bytes.count, alignment: bytes.alignment)
let (colorSpace, bitmapInfo) = (CGColorSpaceCreateDeviceRGB(), CGImageAlphaInfo.premultipliedLast.rawValue | CGImageByteOrderInfo.order32Big.rawValue)
guard let context = CGContext(data: ptr, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerPixel*width, space: colorSpace, bitmapInfo: bitmapInfo) else { throw Error.failedToCreateCheckerboard(size: size, tileCount: tileCount) }
let values: (light: CGFloat, dark: CGFloat) = (0.95, 0.15)
let tile: (width: Int, height: Int) = (width / tileCount, height / tileCount)
for row in 0..<tileCount {
var useLightColor = (row % 2) == 0
for column in 0..<tileCount {
let value = (useLightColor) ? values.light : values.dark
context.setFillColor(red: value, green: value, blue: value, alpha: 1)
context.fill( CGRect(x: row*tile.height, y: column*tile.width, width: tile.width, height: tile.height) )
useLightColor = !useLightColor
}
}
guard let image = context.makeImage() else { throw Error.failedToCreateCheckerboard(size: size, tileCount: tileCount) }
let data = Data(bytesNoCopy: ptr, count: bytes.count, deallocator: .custom { (p, _) in p.deallocate() })
return (data, image)
}
/// Resizes an image and blends the tint color on the blackened squares.
static func _makeResizeImage(image: CGImage, size: CGSize, tintColor: CGColor) throws -> (data: Data, image: CGImage) {
let (width, height) = (Int(size.width), Int(size.height))
let bytes: (count: Int, alignment: Int) = (bytesPerPixel * width * height, MemoryLayout<UInt8>.alignment)
let ptr = UnsafeMutableRawPointer.allocate(byteCount: bytes.count, alignment: bytes.alignment)
let (colorSpace, bitmapInfo) = (CGColorSpaceCreateDeviceRGB(), CGImageAlphaInfo.premultipliedLast.rawValue | CGImageByteOrderInfo.order32Big.rawValue)
guard let context = CGContext(data: ptr, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerPixel*width, space: colorSpace, bitmapInfo: bitmapInfo) else { throw Error.failedtoCreateResizedCheckboard(size: size) }
let rect = CGRect(x: 0, y: 0, width: width, height: height)
context.interpolationQuality = .high
context.draw(image, in: rect)
guard let image = context.makeImage() else { throw Error.failedtoCreateResizedCheckboard(size: size) }
guard let components = tintColor.components else { throw Error.failedtoCreateResizedCheckboard(size: size) }
context.setFillColor(red: components[0], green: components[1], blue: components[2], alpha: components[3])
context.setBlendMode(.multiply)
context.fill(rect)
let data = Data(bytesNoCopy: ptr, count: bytes.count, deallocator: .custom { (p, _) in p.deallocate() })
return (data, image)
}
}
| mit | 4d493443bb17704bede7259698220792 | 47.927273 | 254 | 0.659383 | 3.698461 | false | false | false | false |
kperryua/swift | test/Prototypes/property_behaviors/lazy.swift | 1 | 1588 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-build-swift -Xfrontend -enable-experimental-property-behaviors %s -o %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
import StdlibUnittest
/// A lazily-initialized, mutable, unsynchronized property. The property's
/// parameter closure is evaluated the first time the property is read, if
/// it has not been written to beforehand. No synchronization is provided
/// for the lazy initialization.
protocol lazy {
associatedtype Value
var storage: Value? { get set }
func parameter() -> Value
}
extension lazy {
var value: Value {
mutating get {
if let existing = storage {
return existing
}
let value = parameter()
storage = value
return value
}
set {
storage = newValue
}
}
static func initStorage() -> Value? {
return nil
}
}
var lazyEvaluated = false
func evaluateLazy() -> Int {
lazyEvaluated = true
return 1738
}
class Foo {
var y: Int __behavior lazy { evaluateLazy() }
}
var Lazy = TestSuite("Lazy")
Lazy.test("usage") {
let foo = Foo()
expectFalse(lazyEvaluated)
expectEqual(foo.y, 1738)
expectTrue(lazyEvaluated)
lazyEvaluated = false
expectEqual(foo.y, 1738)
expectFalse(lazyEvaluated)
foo.y = 36
expectEqual(foo.y, 36)
expectFalse(lazyEvaluated)
let foo2 = Foo()
expectFalse(lazyEvaluated)
foo2.y = 36
expectEqual(foo2.y, 36)
expectFalse(lazyEvaluated)
let foo3 = Foo()
expectFalse(lazyEvaluated)
expectEqual(foo3.y, 1738)
expectTrue(lazyEvaluated)
}
runAllTests()
| apache-2.0 | 9a8d7feca1649d700881f2ef2973ff0b | 19.358974 | 93 | 0.675693 | 3.771971 | false | true | false | false |
Acidburn0zzz/firefox-ios | Client/Frontend/InternalSchemeHandler/InternalSchemeHandler.swift | 10 | 3484 | /* 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 WebKit
import Shared
enum InternalPageSchemeHandlerError: Error {
case badURL
case noResponder
case responderUnableToHandle
case notAuthorized
}
protocol InternalSchemeResponse {
func response(forRequest: URLRequest) -> (URLResponse, Data)?
}
class InternalSchemeHandler: NSObject, WKURLSchemeHandler {
static func response(forUrl url: URL) -> URLResponse {
return URLResponse(url: url, mimeType: "text/html", expectedContentLength: -1, textEncodingName: "utf-8")
}
// Responders are looked up based on the path component, for instance responder["about/license"] is used for 'internal://local/about/license'
static var responders = [String: InternalSchemeResponse]()
// Unprivileged internal:// urls might be internal resources in the app bundle ( i.e. <link href="errorpage-resource/NetError.css"> )
func downloadResource(urlSchemeTask: WKURLSchemeTask) -> Bool {
guard let url = urlSchemeTask.request.url else { return false }
let allowedInternalResources = [
"/errorpage-resource/NetError.css",
"/errorpage-resource/CertError.css",
// "/reader-mode/..."
]
// Handle resources from internal pages. For example 'internal://local/errorpage-resource/CertError.css'.
if allowedInternalResources.contains(where: { url.path == $0 }) {
let path = url.lastPathComponent
if let res = Bundle.main.path(forResource: path, ofType: nil), let str = try? String(contentsOfFile: res, encoding: .utf8), let data = str.data(using: .utf8) {
urlSchemeTask.didReceive(URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil))
urlSchemeTask.didReceive(data)
urlSchemeTask.didFinish()
return true
}
}
return false
}
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
guard let url = urlSchemeTask.request.url else {
urlSchemeTask.didFailWithError(InternalPageSchemeHandlerError.badURL)
return
}
let path = url.path.starts(with: "/") ? String(url.path.dropFirst()) : url.path
// For non-main doc URL, try load it as a resource
if !urlSchemeTask.request.isPrivileged, urlSchemeTask.request.mainDocumentURL != urlSchemeTask.request.url, downloadResource(urlSchemeTask: urlSchemeTask) {
return
}
if !urlSchemeTask.request.isPrivileged {
urlSchemeTask.didFailWithError(InternalPageSchemeHandlerError.notAuthorized)
return
}
guard let responder = InternalSchemeHandler.responders[path] else {
urlSchemeTask.didFailWithError(InternalPageSchemeHandlerError.noResponder)
return
}
guard let (urlResponse, data) = responder.response(forRequest: urlSchemeTask.request) else {
urlSchemeTask.didFailWithError(InternalPageSchemeHandlerError.responderUnableToHandle)
return
}
urlSchemeTask.didReceive(urlResponse)
urlSchemeTask.didReceive(data)
urlSchemeTask.didFinish()
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {}
}
| mpl-2.0 | 78e501e60db3265247eeca399fb53187 | 39.511628 | 171 | 0.677095 | 4.727273 | false | false | false | false |
hatjs880328/DZHTTPRequest | HTTPRequest/HTTPRequestResponseProgress.swift | 1 | 3494 | //
// HTTPRequestResponseProgress.swift
// FSZCItem
//
// Created by MrShan on 16/6/23.
// Copyright © 2016年 Mrshan. All rights reserved.
//
import Foundation
import UIKit
public class NETWORKErrorProgress: NSObject {
/**
异常错误处理方法
- parameter type: 错误类型
- parameter ifcanshow: 是否可以提示错误
- parameter errormsg: 错误信息
*/
func errorMsgProgress(type:ERRORMsgType,ifcanshow:HTTPERRORInfoShow,errormsg:String,errorAction:(errorType:ERRORMsgType)->Void){
if type == ERRORMsgType.jumpLogin {
self.moreThanoneUserLoginwithsameoneAPPID()
}else{
if type == ERRORMsgType.networkCannotuse && ifcanshow == HTTPERRORInfoShow.shouldShow {
//MyAlertView.sharedInstance.show(MyAlertViewType.blackViewAndClickDisappear, contentType: MyAlertContentViewType.warning, message: ["没有网络连接,请检查您的网络"])
errorAction(errorType:ERRORMsgType.networkCannotuse)
}
if type == ERRORMsgType.responseError && ifcanshow == HTTPERRORInfoShow.shouldShow {
//MyAlertView.sharedInstance.show(MyAlertViewType.blackViewAndClickDisappear, contentType: MyAlertContentViewType.warning, message: ["网络通讯异常,请重试。"])
errorAction(errorType:ERRORMsgType.responseError)
}
if type == ERRORMsgType.progressError && ifcanshow == HTTPERRORInfoShow.shouldShow {
//MyAlertView.sharedInstance.show(MyAlertViewType.blackViewAndClickDisappear, contentType: MyAlertContentViewType.warning, message: ["\(errormsg)解析数据错误"])
errorAction(errorType:ERRORMsgType.progressError)
}
if type == ERRORMsgType.returnerrormsg && ifcanshow == HTTPERRORInfoShow.shouldShow {
//MyAlertView.sharedInstance.show(MyAlertViewType.blackViewAndClickDisappear, contentType: MyAlertContentViewType.warning, message: ["\(errormsg)"])
errorAction(errorType:ERRORMsgType.returnerrormsg)
}
}
}
/**
多账户登录的时候,接口返回999数据的时候需要跳转到登录页面
*/
func moreThanoneUserLoginwithsameoneAPPID() {
//跳到登录页面
// MyAlertView.sharedInstance.hiden()
// let drawCon = UIApplication.sharedApplication().keyWindow?.rootViewController as! MMDrawerController
// let navCon = drawCon.centerViewController as! MMNavigationController
// if(isLeftPersonalCenter){
// isLeftPersonalCenter = false
// is999Login = false
//
// let leftCon = drawCon.leftDrawerViewController as! PersonalCenterViewController
// leftCon.delay(0.5, closure: { () -> () in
// leftCon.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: { (bo) -> Void in
// navCon.viewControllers.last!.navigationController!.pushViewController(QuickLoginViewController(nibName: "QuickLoginViewController", bundle: nil), animated: true)
// })
// return
// })
// }
// if(is999Login){
// is999Login = false
// navCon.viewControllers.last!.navigationController!.pushViewController(QuickLoginViewController(nibName: "QuickLoginViewController", bundle: nil), animated: true)
// }else{
// }
}
} | mit | 7a394175555150ffb56a7f614d9fb6a4 | 43.810811 | 183 | 0.663047 | 4.578729 | false | false | false | false |
dn-m/PitchSpellingTools | PitchSpellingTools/SpelledPitchClassSet.swift | 1 | 1083 | //
// SpelledPitchClassSet.swift
// PitchSpellingTools
//
// Created by James Bean on 8/25/16.
//
//
import Pitch
/// Unordered set of `SpelledPitchClass` values.
///
/// - TODO: Conform to `AnySequenceWrapping`.
public struct SpelledPitchClassSet {
fileprivate let pitches: Set<SpelledPitchClass>
public init<S: Sequence>(_ pitches: S) where S.Iterator.Element == SpelledPitchClass {
self.pitches = Set(pitches)
}
}
extension SpelledPitchClassSet: ExpressibleByArrayLiteral {
public typealias Element = SpelledPitchClass
public init(arrayLiteral elements: Element...) {
self.pitches = Set(elements)
}
}
extension SpelledPitchClassSet: Sequence {
public func makeIterator() -> AnyIterator<SpelledPitchClass> {
var generator = pitches.makeIterator()
return AnyIterator { return generator.next() }
}
}
extension SpelledPitchClassSet: Equatable {
public static func == (lhs: SpelledPitchClassSet, rhs: SpelledPitchClassSet) -> Bool {
return lhs.pitches == rhs.pitches
}
}
| mit | 5af2f06736f264635d6d69c7a5dadb42 | 23.066667 | 90 | 0.686057 | 4.297619 | false | false | false | false |
Harry-L/5-3-1 | ios-charts-master/Charts/Classes/Data/Implementations/Standard/PieChartData.swift | 7 | 3138 | //
// PieData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/2/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
public class PieChartData: ChartData
{
public override init()
{
super.init()
}
public override init(xVals: [String?]?, dataSets: [IChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [IChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
var dataSet: PieChartDataSet?
{
get
{
return dataSets.count > 0 ? dataSets[0] as? PieChartDataSet : nil
}
set
{
if (newValue != nil)
{
dataSets = [newValue!]
}
else
{
dataSets = []
}
}
}
public override func getDataSetByIndex(index: Int) -> IChartDataSet?
{
if (index != 0)
{
return nil
}
return super.getDataSetByIndex(index)
}
public override func getDataSetByLabel(label: String, ignorecase: Bool) -> IChartDataSet?
{
if (dataSets.count == 0 || dataSets[0].label == nil)
{
return nil
}
if (ignorecase)
{
if (label.caseInsensitiveCompare(dataSets[0].label!) == NSComparisonResult.OrderedSame)
{
return dataSets[0]
}
}
else
{
if (label == dataSets[0].label)
{
return dataSets[0]
}
}
return nil
}
public override func addDataSet(d: IChartDataSet!)
{
if (_dataSets == nil)
{
return
}
super.addDataSet(d)
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
public override func removeDataSetByIndex(index: Int) -> Bool
{
if (_dataSets == nil || index >= _dataSets.count || index < 0)
{
return false
}
return false
}
/// - returns: the total y-value sum across all DataSet objects the this object represents.
public var yValueSum: Double
{
var yValueSum: Double = 0.0
if (_dataSets == nil)
{
return yValueSum
}
for dataSet in _dataSets
{
yValueSum += fabs((dataSet as! IPieChartDataSet).yValueSum)
}
return yValueSum
}
/// - returns: the average value across all entries in this Data object (all entries from the DataSets this data object holds)
public var average: Double
{
return yValueSum / Double(yValCount)
}
}
| mit | fd316aed6a8bdfce99c9f2b8799acc2e | 22.772727 | 130 | 0.524857 | 4.850077 | false | false | false | false |
shelleyweiss/softsurvey | SoftSurvey/AppDelegate.swift | 1 | 6161 | //
// AppDelegate.swift
// SoftSurvey
//
// Created by shelley weiss on 3/4/15.
// Copyright (c) 2015 shelley weiss. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "shelley.weiss.SoftSurvey" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SoftSurvey", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SoftSurvey.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| artistic-2.0 | 4a4334c94496022fd30e2d898784eb3b | 54.504505 | 290 | 0.716604 | 5.731163 | false | false | false | false |
yhyuan/WeatherMap | WeatherAroundUs/WeatherAroundUs/DetailWeatherView.swift | 5 | 7147 | //
// DetailWeatherView.swift
// WeatherAroundUs
//
// Created by Wang Yu on 4/25/15.
// Copyright (c) 2015 Kedan Li. All rights reserved.
//
import UIKit
class DetailWeatherView: UIView {
var parentController: CityDetailViewController!
@IBOutlet var line: UIImageView!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var unit: String {
return parentController.unit.stringValue
}
func setup(forecastInfos: [[String: AnyObject]]) {
var beginY = line.frame.origin.y + line.frame.height + 5
let blockHeight: CGFloat = 18
let spaceHeight: CGFloat = 8
let windSpeed = (forecastInfos[0] as [String: AnyObject])["speed"] as! Int
let windDirection = (forecastInfos[0] as [String: AnyObject])["deg"] as! Int
var windDirectionStr: String = ""
if windDirection < 90 {
windDirectionStr = "\(windDirection)° NE"
} else if windDirection < 180 {
windDirectionStr = "\(windDirection-90)° NW"
} else if windDirection < 270 {
windDirectionStr = "\(windDirection-180)° SW"
} else {
windDirectionStr = "\(windDirection-270)° SE"
}
if UserLocation.inChina{
createTwoUILabelInMiddle("风速:", secondString: "\(windSpeed) mps", yPosition: beginY)
beginY += blockHeight
createTwoUILabelInMiddle("风向:", secondString: windDirectionStr, yPosition: beginY)
beginY += blockHeight + spaceHeight
let clouds = (forecastInfos[0] as [String: AnyObject])["speed"] as! Int
createTwoUILabelInMiddle("云量:", secondString: "\(clouds) %", yPosition: beginY)
beginY += blockHeight
let humanity = (forecastInfos[0] as [String: AnyObject])["humidity"] as! Int
createTwoUILabelInMiddle("湿度:", secondString: "\(humanity) %", yPosition: beginY)
beginY += blockHeight + spaceHeight
let precipitation = (forecastInfos[0] as [String: AnyObject])["rain"] as? Double
var precipitationStr = "TBA"
if precipitation != nil {
precipitationStr = "\(precipitation! * 100) mm"
}
createTwoUILabelInMiddle("降雨量:", secondString: precipitationStr, yPosition: beginY)
beginY += blockHeight
let pressure = (forecastInfos[0] as [String: AnyObject])["pressure"] as! Int
createTwoUILabelInMiddle("气压:", secondString: "\(pressure) hPa", yPosition: beginY)
beginY += blockHeight + spaceHeight
let mornTemperature = (forecastInfos[0]["temp"] as! [String: AnyObject])["morn"]!.doubleValue
createTwoUILabelInMiddle("早晨气温:", secondString: "\(WeatherMapCalculations.kelvinConvert(mornTemperature, unit: parentController.unit)) °" + unit, yPosition: beginY)
beginY += blockHeight
let nightTemperature = (forecastInfos[0]["temp"] as! [String: AnyObject])["night"]!.doubleValue
createTwoUILabelInMiddle("夜晚气温:", secondString: "\(WeatherMapCalculations.kelvinConvert(nightTemperature, unit: parentController.unit)) °" + unit, yPosition: beginY)
}else{
createTwoUILabelInMiddle("Wind Speed:", secondString: "\(windSpeed) mps", yPosition: beginY)
beginY += blockHeight
createTwoUILabelInMiddle("Wind Direction:", secondString: windDirectionStr, yPosition: beginY)
beginY += blockHeight + spaceHeight
let clouds = (forecastInfos[0] as [String: AnyObject])["speed"] as! Int
createTwoUILabelInMiddle("Cloudiness:", secondString: "\(clouds) %", yPosition: beginY)
beginY += blockHeight
let humanity = (forecastInfos[0] as [String: AnyObject])["humidity"] as! Int
createTwoUILabelInMiddle("Humidity:", secondString: "\(humanity) %", yPosition: beginY)
beginY += blockHeight + spaceHeight
let precipitation = (forecastInfos[0] as [String: AnyObject])["rain"] as? Double
var precipitationStr = "TBA"
if precipitation != nil {
precipitationStr = "\(precipitation! * 100) mm"
}
createTwoUILabelInMiddle("Precipitation:", secondString: precipitationStr, yPosition: beginY)
beginY += blockHeight
let pressure = (forecastInfos[0] as [String: AnyObject])["pressure"] as! Int
createTwoUILabelInMiddle("Pressure:", secondString: "\(pressure) hPa", yPosition: beginY)
beginY += blockHeight + spaceHeight
let mornTemperature = (forecastInfos[0]["temp"] as! [String: AnyObject])["morn"]!.doubleValue
createTwoUILabelInMiddle("Morning Temp:", secondString: "\(WeatherMapCalculations.kelvinConvert(mornTemperature, unit: parentController.unit)) °" + unit, yPosition: beginY)
beginY += blockHeight
let nightTemperature = (forecastInfos[0]["temp"] as! [String: AnyObject])["night"]!.doubleValue
createTwoUILabelInMiddle("Night Temp:", secondString: "\(WeatherMapCalculations.kelvinConvert(nightTemperature, unit: parentController.unit)) °" + unit, yPosition: beginY)
}
}
var TempLabelArray = [UILabel]()
func createTwoUILabelInMiddle(firstStirng: String, secondString: String, yPosition: CGFloat) {
let labelHeight: CGFloat = 20
let xPostion = line.frame.origin.x
var leftLabel = UILabel(frame: CGRectMake(xPostion, yPosition, line.frame.width / 2, labelHeight))
var rightLabel = UILabel(frame: CGRectMake(xPostion + line.frame.width / 2 + 20, yPosition, line.frame.width / 2, labelHeight))
leftLabel.font = UIFont(name: "AvenirNext-Regular", size: 14)
rightLabel.font = leftLabel.font
leftLabel.textColor = UIColor.whiteColor()
rightLabel.textColor = leftLabel.textColor
leftLabel.textAlignment = .Right
rightLabel.textAlignment = .Left
leftLabel.text = firstStirng
rightLabel.text = secondString
self.addSubview(leftLabel)
self.addSubview(rightLabel)
TempLabelArray.append(rightLabel)
}
func reloadTempatureContent(forecastInfos: [[String: AnyObject]]) {
let lastFirst = TempLabelArray[TempLabelArray.count - 1]
let lastSecond = TempLabelArray[TempLabelArray.count - 2]
let nightTemperature = (forecastInfos[0]["temp"] as! [String: AnyObject])["night"]!.doubleValue
lastFirst.text = "\(WeatherMapCalculations.kelvinConvert(nightTemperature, unit: parentController.unit)) °" + unit
let mornTemperature = (forecastInfos[0]["temp"] as! [String: AnyObject])["morn"]!.doubleValue
lastSecond.text = "\(WeatherMapCalculations.kelvinConvert(mornTemperature, unit: parentController.unit)) °" + unit
}
}
| apache-2.0 | f2a6f5cebab7ae60dcf0ce978a67b183 | 48.270833 | 184 | 0.626216 | 4.768145 | false | false | false | false |
iAugux/Zoom-Contacts | Phonetic/ViewController+Popover.swift | 1 | 6023 | //
// ViewController+Popover.swift
// Phonetic
//
// Created by Augus on 1/30/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import UIKit
import SnapKit
// MARK: - Popover view controller even on iPhones
extension ViewController: UIPopoverPresentationControllerDelegate {
internal func popoverInfoViewController() {
popoverPresentViewController(PopoverButton.Info)
hideLabels(true)
}
internal func popoverSettingViewController() {
popoverPresentViewController(PopoverButton.Setting)
hideLabels(true)
}
internal func showLabels() {
hideLabels(false)
}
private func hideLabels(hidden: Bool) {
if let label1 = view.viewWithTag(998), label2 = view.viewWithTag(999) {
UIView.animateWithDuration(0.6, delay: 0.1, options: .CurveEaseInOut, animations: { () -> Void in
label1.alpha = hidden ? 0 : 1
label2.alpha = hidden ? 0 : 1
}, completion: nil)
}
}
private enum PopoverButton {
case Info
case Setting
}
private struct Popover {
static var popoverContent: UIViewController?
static var popover: UIPopoverPresentationController?
static var currentButton: PopoverButton?
static let preferredContentWith: CGFloat = 220 //min(300, UIScreen.screenWidth() * 0.6)
private static let preferredContentHeight: CGFloat = 260
private static let preferredMutableContentHeight = min(500, UIScreen.screenHeight() * 0.8)
static let preferredContentSize = CGSizeMake(preferredContentWith, preferredContentHeight)
static let preferredMutableContentSize = CGSizeMake(278, preferredMutableContentHeight)
}
// MARK: - fix size of popover view
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
if Popover.currentButton == .Info {
// fix popoverContent's size
Popover.popoverContent?.preferredContentSize = Popover.preferredContentSize
// fix popover's source location
Popover.popover?.sourceRect = infoButton.frame
} else {
Popover.popoverContent?.preferredContentSize = Popover.preferredMutableContentSize
Popover.popover?.sourceRect = settingButton.frame
}
Popover.popover?.sourceRect.origin.y += 5
}
// MARK: - configure popover controller
private func popoverPresentViewController(button: PopoverButton) {
var rect: CGRect
var title: String
switch button {
case .Info:
guard let infoVC = UIStoryboard.Main.instantiateViewControllerWithIdentifier(String(InfoViewController)) as? InfoViewController else { return }
Popover.popoverContent = infoVC
Popover.popoverContent!.preferredContentSize = Popover.preferredContentSize
Popover.currentButton = .Info
title = NSLocalizedString("About", comment: "navigation item title - About")
rect = infoButton.frame
case .Setting:
guard let settingVC = UIStoryboard.Main.instantiateViewControllerWithIdentifier(String(AdditionalSettingsViewController)) as? AdditionalSettingsViewController else { return }
Popover.popoverContent = settingVC
Popover.popoverContent!.preferredContentSize = Popover.preferredMutableContentSize
Popover.currentButton = .Setting
title = NSLocalizedString("Settings", comment: "navigation item title - Settings")
rect = settingButton.frame
}
if let popoverContent = Popover.popoverContent {
let nav = UINavigationController(rootViewController: popoverContent)
nav.completelyTransparentBar()
button == .Setting ? nav.navigationBar.backgroundColor = kNavigationBarBackgroundColor : ()
nav.modalPresentationStyle = .Popover
Popover.popover = nav.popoverPresentationController
Popover.popover?.backgroundColor = kNavigationBarBackgroundColor
Popover.popover?.delegate = self
Popover.popover?.sourceView = view
configureCustomNavigationTitle(nav, title: title)
rect.origin.y += 5
Popover.popover?.sourceRect = rect
presentViewController(nav, animated: true, completion: nil)
}
}
private func configureCustomNavigationTitle(nav: UINavigationController, title: String?) {
guard title != nil else { return }
let titleLabel = UILabel()
titleLabel.text = title
titleLabel.textAlignment = .Center
titleLabel.font = UIFont.boldSystemFontOfSize(16.0)
titleLabel.textColor = UIColor.whiteColor()
titleLabel.sizeToFit()
nav.navigationBar.addSubview(titleLabel)
titleLabel.snp_makeConstraints { (make) in
make.center.equalTo(nav.navigationBar)
}
}
// MARK: - UIAdaptivePresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
// MARK: - for iPhone 6(s) Plus
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .None
}
override func overrideTraitCollectionForChildViewController(childViewController: UIViewController) -> UITraitCollection? {
// disable default UITraitCollection, fix size of popover view on iPhone 6(s) Plus.
return nil
}
} | mit | 14fde108d94026516183b70a8388495e | 35.72561 | 186 | 0.644968 | 6.052261 | false | false | false | false |
CrossWaterBridge/Attributed | Attributed/MarkupElement.swift | 1 | 2037 | //
// Copyright (c) 2015 Hilton Campbell
//
// 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 struct MarkupElement {
public let name: String
public let attributes: [String: String]
public init(name: String, attributes: [String: String]) {
self.name = name
self.attributes = attributes
}
}
public func ~= (pattern: String, element: MarkupElement) -> Bool {
let scanner = Scanner(string: pattern)
scanner.charactersToBeSkipped = nil
var name: NSString?
if scanner.scanUpTo(".", into: &name), let name = name as String?, name == element.name {
if scanner.scanString(".", into: nil) {
var className: NSString?
if scanner.scanUpTo("", into: &className), let className = className as String?, let elementClassName = element.attributes["class"], elementClassName == className {
return true
}
} else {
return true
}
}
return false
}
| mit | 4d8bcf1011b0a78dace875d2d12591a3 | 38.173077 | 176 | 0.692685 | 4.661327 | false | false | false | false |
imobilize/Molib | Molib/Classes/Networking/DownloadManager/NetworkDownloader.swift | 1 | 2469 | import Foundation
class NetworkDownloader: Downloader {
private let inProgressOperationQueue = OperationQueue()
private var pausedOperationQueue = [DownloaderOperation]()
private let networkOperationService: NetworkRequestService
var delegate: DownloaderDelegate?
init(networkOperationService: NetworkRequestService) {
self.networkOperationService = networkOperationService
}
func addDownloadTask(task: DownloaderTask) {
let downloadOperation = DownloaderOperation(downloaderTask: task, networkOperationService: networkOperationService)
guard inProgressOperationQueue.operations.contains(downloadOperation) == false else {
return
}
downloadOperation.delegate = self
inProgressOperationQueue.addOperation(downloadOperation)
}
func pauseDownloadTask(task: DownloaderTask) {
if let operation = operationForTask(task: task) {
operation.pause()
pausedOperationQueue.append(operation)
}
}
func resumeDownloadTask(task: DownloaderTask) {
if let operation = pausedOperationQueue.first(where: { (operationInQueue) -> Bool in
operationInQueue.matchesDownloaderTask(task: task)
}) {
inProgressOperationQueue.addOperation(operation)
}
}
func retryDownloadTask(task: DownloaderTask) {
addDownloadTask(task: task)
}
func cancelTask(task: DownloaderTask) {
let operation = operationForTask(task: task)
operation?.cancel()
}
private func operationForTask(task: DownloaderTask) -> DownloaderOperation? {
let operationsForTask = inProgressOperationQueue.operations.filter { (operationInQueue) in
var matches = false
if let operation = operationInQueue as? DownloaderOperation {
matches = operation.matchesDownloaderTask(task: task)
}
return matches
}
return operationsForTask.first as? DownloaderOperation
}
}
extension NetworkDownloader: DownloaderOperationDelegate {
func downloaderOperationDidUpdateProgress(progress: Float, forTask: DownloaderTask) {
}
func downloaderOperationDidStartDownload(forTask: DownloaderTask) {
}
func downloaderOperationDidFailDownload(withError: Error, forTask: DownloaderTask) {
}
func downloaderOperationDidComplete(forTask: DownloaderTask) {
}
}
| apache-2.0 | e3975d0bb5c882a21609bfda22fadc19 | 29.8625 | 123 | 0.698258 | 5.511161 | false | false | false | false |
danwey/INSPhotoGallery | INSPhotoGallery/UIVIew+INSPhotoViewer.swift | 1 | 2315 | //
// UIVIew+Snapshot.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library 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
extension UIView {
func ins_snapshotView() -> UIView {
if let contents = layer.contents {
var snapshotedView: UIView!
if let view = self as? UIImageView {
snapshotedView = view.dynamicType.init(image: view.image)
snapshotedView.bounds = view.bounds
} else {
snapshotedView = UIView(frame: frame)
snapshotedView.layer.contents = contents
snapshotedView.layer.bounds = layer.bounds
}
snapshotedView.layer.cornerRadius = layer.cornerRadius
snapshotedView.layer.masksToBounds = layer.masksToBounds
snapshotedView.contentMode = contentMode
snapshotedView.transform = transform
return snapshotedView
} else {
return snapshotViewAfterScreenUpdates(true)
}
}
func ins_translatedCenterPointToContainerView(containerView: UIView) -> CGPoint {
var centerPoint = center
// Special case for zoomed scroll views.
if let scrollView = self.superview as? UIScrollView where scrollView.zoomScale != 1.0 {
centerPoint.x += (scrollView.bounds.width - scrollView.contentSize.width) / 2.0 + scrollView.contentOffset.x
centerPoint.y += (scrollView.bounds.height - scrollView.contentSize.height) / 2.0 + scrollView.contentOffset.y
}
return self.superview?.convertPoint(centerPoint, toView: containerView) ?? CGPoint.zero
}
}
| apache-2.0 | dfaf1201e4d8fccdc8ce22792388d319 | 39.561404 | 122 | 0.657439 | 4.718367 | false | false | false | false |
philipgreat/b2b-swift-app | B2BSimpleApp/B2BSimpleApp/Warehouse.swift | 1 | 2045 | //Domain B2B/Warehouse/
import Foundation
import ObjectMapper //Use this to generate Object
import SwiftyJSON //Use this to verify the JSON Object
struct Warehouse{
var id : String?
var displayName : String?
var location : String?
var owner : String?
var version : Int?
var inventoryList : [Inventory]?
init(){
//lazy load for all the properties
//This is good for UI applications as it might saves RAM which is very expensive in mobile devices
}
static var CLASS_VERSION = "1"
//This value is for serializer like message pack to identify the versions match between
//local and remote object.
}
extension Warehouse: Mappable{
//Confirming to the protocol Mappable of ObjectMapper
//Reference on https://github.com/Hearst-DD/ObjectMapper/
init?(_ map: Map){
}
mutating func mapping(map: Map) {
//Map each field to json fields
id <- map["id"]
displayName <- map["displayName"]
location <- map["location"]
owner <- map["owner"]
version <- map["version"]
inventoryList <- map["inventoryList"]
}
}
extension Warehouse:CustomStringConvertible{
//Confirming to the protocol CustomStringConvertible of Foundation
var description: String{
//Need to find out a way to improve this method performance as this method might called to
//debug or log, using + is faster than \(var).
var result = "warehouse{";
if id != nil {
result += "\tid='\(id!)'"
}
if displayName != nil {
result += "\tdisplay_name='\(displayName!)'"
}
if location != nil {
result += "\tlocation='\(location!)'"
}
if owner != nil {
result += "\towner='\(owner!)'"
}
if version != nil {
result += "\tversion='\(version!)'"
}
result += "}"
return result
}
}
| mit | 6aa1591f5df3c5c10be206de980f59b8 | 22.058824 | 100 | 0.566748 | 3.851224 | false | false | false | false |
alexth/VIPER-test | ViperTest/ViperTest/Data/DataManager.swift | 1 | 1199 | //
// DataManager.swift
// ViperTest
//
// Created by Alex Golub on 10/31/16.
// Copyright © 2016 Alex Golub. All rights reserved.
//
import Foundation
import CoreData
class DataManager {
static let sharedInstance = DataManager()
fileprivate init() {}
// MARK: Core Data stack
lazy var managedObjectContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "ViperTest")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 13bc4e17a2f905ce80ea8ee5e6e6ab7c | 25.622222 | 88 | 0.60601 | 5.324444 | false | false | false | false |
damoyan/BYRClient | FromScratch/ArticleNetResourceHelper.swift | 1 | 4813 | //
// ImageHelper.swift
// FromScratch
//
// Created by Yu Pengyang on 1/5/16.
// Copyright © 2016 Yu Pengyang. All rights reserved.
//
import UIKit
import ImageIO
typealias BYRResourceDownloadCompletionHandler = (String, NSData?, NSError?) -> ()
class ArticleNetResourceHelper {
static let defaultHelper: ArticleNetResourceHelper = {
return ArticleNetResourceHelper()
}()
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: DataDelegate(), delegateQueue: nil)
var imageDownloadCompletionHandler: BYRResourceDownloadCompletionHandler?
/// `handler` is called on background thread after task is completed.
func getResourceWithURLString(urlString: String, completionHandler handler: BYRResourceDownloadCompletionHandler) {
let s = urlString + "?oauth_token=\(AppSharedInfo.sharedInstance.userToken!)"
guard let url = NSURL(string: s) else { return }
let task = session.dataTaskWithURL(url)
(session.delegate as? DataDelegate)?.imageDownloadCompletionHandlers[task] = (urlString, handler)
task.resume()
}
class DataDelegate: NSObject, NSURLSessionDataDelegate {
class TaskData {
var data: NSMutableData = NSMutableData()
var expectedContentLength: Int64 = -1
private var downloadedContentLength: Int64 = 0
var progress: Double = 0
}
var datas = [NSURLSessionTask: TaskData]()
var imageDownloadCompletionHandlers: [NSURLSessionTask: (String, BYRResourceDownloadCompletionHandler)] = [:]
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
let data = TaskData()
data.expectedContentLength = response.expectedContentLength
data.downloadedContentLength = 0
data.progress = 0
datas[dataTask] = data
completionHandler(NSURLSessionResponseDisposition.Allow)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
guard let taskData = datas[dataTask] else { return }
taskData.downloadedContentLength += data.length
taskData.progress = Double(taskData.downloadedContentLength) / Double(taskData.expectedContentLength)
taskData.data.appendData(data)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
guard let taskData = datas[task] else {
let error = NSError(domain: BYRErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "No data return."])
handleCallback(task, data: nil, error: error)
return
}
guard error == nil else {
handleCallback(task, data: nil, error: error)
return
}
handleCallback(task, data: taskData.data, error: nil)
}
func handleCallback(task: NSURLSessionTask, data: NSData?, error: NSError?) {
if let handler = imageDownloadCompletionHandlers[task] {
handler.1(handler.0, data, error)
}
datas.removeValueForKey(task)
imageDownloadCompletionHandlers.removeValueForKey(task)
}
}
}
class ImageHelper {
typealias Handler = (String?, ImageDecoder?, NSError?) -> ()
static let _queue = NSOperationQueue()
class func getImageWithURLString(urlString: String, completionHandler handler: Handler) {
_queue.addOperationWithBlock {
ArticleNetResourceHelper.defaultHelper.getResourceWithURLString(urlString) { (urlString, data, error) -> () in
guard let data = data else {
runHandlerOnMain(handler, urlString: urlString, decoder: nil, error: error)
return
}
let decoder = BYRImageDecoder(data: data)
runHandlerOnMain(handler, urlString: urlString, decoder: decoder, error: nil)
}
}
}
class func getImageWithData(data: NSData, completionHandler handler: Handler) {
_queue.addOperationWithBlock { () -> Void in
let decoder = BYRImageDecoder(data: data)
runHandlerOnMain(handler, urlString: nil, decoder: decoder, error: nil)
}
}
class func runHandlerOnMain(handler: Handler, urlString: String?, decoder: ImageDecoder?, error: NSError?) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(urlString, decoder, error)
})
}
}
| mit | ef4cf842b36229f95cb305773d37bfa5 | 41.210526 | 186 | 0.647548 | 5.224756 | false | false | false | false |
CoderLiLe/Swift | Bool类型/main.swift | 1 | 805 | //
// main.swift
// Bool类型
//
// Created by LiLe on 15/2/28.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
C语言和OC并没有真正的Bool类型
C语言的Bool类型非0即真
OC语言的Bool类型是typedef signed char BOOL;
Swift引入了真正的Bool类型
Bool true false
*/
let isOpen = true;
//let isOpen = 1;
// Swift中if的条件只能是一个Bool的值或者是返回值是Bool类型的表达式(==/!=/>/<等等)
// OC中if可以是任何整数(非0即真), 但是存在的问题是可能将判断写错, 写成了赋值 if(isOpen = 2) , 在开发中为了避免这个问题有经验的程序员会这样写 if(2 == isOpen)来避免这个问题. 在Swift中很好的解决了这个问题
if isOpen
{
print("打开")
}else
{
print("关闭")
}
| mit | 8d256ffd0cc2c33b68ee4a3774c996e8 | 17.172414 | 128 | 0.70778 | 2.384615 | false | false | false | false |
AashiniSharma/Home-Living | Home&Living/Home&LivingVC.swift | 1 | 12286 |
import UIKit
import AlamofireImage
class Home_LivingVC: UIViewController {
//MARK: Properties
var favouritesIndicesArray = [[IndexPath]]() //2D array for storing indexpaths of table view and collection view
var hiddenElementsIndicesArray = [IndexPath]() // array for storing show and hide elements
var hiddenSectionsIndicesArray = [Int]() // array for storing show and hide sections
var picturesData = [[[ImageInfo]]]() //array for storing images of collection view cell
typealias dictionary = [[String:Any]]
//MARK: IB Outlets
@IBOutlet weak var home_LivingTableView: UITableView!
//MARK: view life cycle
override func viewDidLoad() {
super.viewDidLoad()
initialSetup()
getImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: Private Functions
private func initialSetup(){
//setting datasources and delegates for table view
self.home_LivingTableView.dataSource = self
self.home_LivingTableView.delegate = self
//registering xib for table cell
let xib = UINib(nibName: "SectionsforHome&Living", bundle: nil)
home_LivingTableView.register(xib, forCellReuseIdentifier: "SectionsforHome_LivingID")
//registering xib for header section in table view
let nib = UINib(nibName: "TitlesOfSection", bundle: nil)
home_LivingTableView.register(nib, forHeaderFooterViewReuseIdentifier: "TitlesOfSectionID")
}
//function of inserting data
private func getImage(){
var count = 1
for sections in JsonData.data.indices{
picturesData.append([])
for (index,value) in (JsonData.data[sections]["Value"] as! dictionary).enumerated(){
picturesData[sections].append([])
WebController().fetchDataFromPixabay(withQuery: value["Sub Category"] as! String,
page : count,
success: { (images : [ImageInfo]) in
self.picturesData[sections][index] = images
self.home_LivingTableView.reloadData()
},failure: { (error : Error) in
let alert = UIAlertController(title: "Alert", message: "No Internet Connection", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Continue", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
print(error)
})
count += 1
}
}
}
@IBAction func favButtonAction(_ sender: UIButton) {
guard let favouritePage = self.storyboard?.instantiateViewController(withIdentifier: "FavouritesVCID") as? FavouritesVC else{ return }
for indices in favouritesIndicesArray
{
let tableIndexPath = indices[0]
let collectionIndexPath = indices[1]
let data = picturesData[tableIndexPath.section][tableIndexPath.row][collectionIndexPath.row]
favouritePage.favImagesArray.append(data)
}
self.navigationController?.pushViewController(favouritePage, animated: true)
}
}
//MARK: tableview delegates and datasources
extension Home_LivingVC : UITableViewDataSource,UITableViewDelegate {
// return number of sections
func numberOfSections(in tableView: UITableView) -> Int {
return picturesData.count
}
//return number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hiddenSectionsIndicesArray.contains(section){
return 0
} else {
return picturesData[section].count
}
}
//returning table cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SectionsforHome_LivingID", for: indexPath) as? SectionsforHome_Living else {fatalError("Not Found")}
cell.tableIndexpath = indexPath
//setting datasources and delegates for collection view
cell.home_LivingCollectionView.dataSource = self
cell.home_LivingCollectionView.delegate = self
//registering xib for collection view cell
let nib = UINib(nibName: "VarietiesofHome_Living", bundle: nil)
cell.home_LivingCollectionView.register(nib, forCellWithReuseIdentifier: "VarietiesofHome_LivingID")
//MARK: IB Action of masking button
cell.maskButtonOutlet.addTarget(self, action: #selector(maskingAction), for: .touchUpInside)
let data = JsonData.data[indexPath.section]["Value"] as! dictionary
cell.brandsLabel.text = data[indexPath.row]["Sub Category"] as! String?
//persistency for masking and unmasking
if hiddenElementsIndicesArray.contains(indexPath){
cell.maskButtonOutlet.isSelected = true
}else {
cell.maskButtonOutlet.isSelected = false
}
return cell
}
//returning height of row
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if hiddenElementsIndicesArray.contains(indexPath){
return 30
} else {
return 125
}
}
//returning height of header section
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
//returning the title of header section
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "TitlesOfSectionID") as? TitlesOfSection else { return nil}
header.maskingSectionButtonOutlet.addTarget(self, action: #selector(maskingSectionButtonAction), for: .touchUpInside)
header.maskingSectionButtonOutlet.tag = section
if hiddenSectionsIndicesArray.contains(section){
header.maskingSectionButtonOutlet.isSelected = true
} else {
header.maskingSectionButtonOutlet.isSelected = false
}
header.titlesOutlet.text = JsonData.data[section]["Category"] as? String
return header
}
//function of masking elements button
func maskingAction (button : UIButton){
guard let cell = button.tableViewCell as? SectionsforHome_Living else { return }
if button.isSelected {
hiddenElementsIndicesArray = hiddenElementsIndicesArray.filter(){ (index: IndexPath) -> Bool in
return index != home_LivingTableView.indexPath(for: cell)
}
button.isSelected = false
} else {
hiddenElementsIndicesArray.append(home_LivingTableView.indexPath(for: cell)!)
button.isSelected = true
}
home_LivingTableView.reloadRows(at: [home_LivingTableView.indexPath(for: cell)!] , with: .fade )
}
//function of masking sections
func maskingSectionButtonAction(button : UIButton) {
if button.isSelected{
button.isSelected = false
hiddenSectionsIndicesArray = hiddenSectionsIndicesArray.filter(){$0 != button.tag}
}else{
button.isSelected = true
hiddenSectionsIndicesArray.append(button.tag)
}
home_LivingTableView.reloadSections([button.tag], with: .fade)
}
}
// MARK: collection view datasources and delegates
extension Home_LivingVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
//returning number of items in a particular section
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let tableCell = collectionView.tableViewCell as! SectionsforHome_Living
return picturesData[tableCell.tableIndexpath.section][tableCell.tableIndexpath.row].count
}
//returning the cell of collection view
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VarietiesofHome_LivingID", for: indexPath) as? VarietiesofHome_Living else {fatalError("Not Found")
}
//MARK: IB Action of favourites button
cell.favouritesButtonOutlet.addTarget(self, action: #selector(favouritesButtonAction), for: .touchUpInside)
//fetching table cell
let tableCell = collectionView.tableViewCell as! SectionsforHome_Living
// storing images in pictures data array
let data = picturesData[tableCell.tableIndexpath.section][tableCell.tableIndexpath.row][indexPath.row]
if let url = URL(string: data.previewURL) {
cell.varietiesImages.af_setImage(withURL : url)
}
cell.varietyLabel.text = "\(tableCell.tableIndexpath.section).\(tableCell.tableIndexpath.row).\(indexPath.row)"
if favouritesIndicesArray.contains(where: { (indices : [IndexPath]) -> Bool in
return indices == [tableCell.tableIndexpath,indexPath]
}){
cell.favouritesButtonOutlet.isSelected = true
} else {
cell.favouritesButtonOutlet.isSelected = false
}
return cell
}
// pushing the image on other view while selecting on it
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let popUpImagePage = self.storyboard?.instantiateViewController(withIdentifier: "PopupImageVCID") as? PopupImageVC else { return }
let tableCell = collectionView.tableViewCell as! SectionsforHome_Living
let data = picturesData[tableCell.tableIndexpath.section ][tableCell.tableIndexpath.row][indexPath.row]
popUpImagePage.imageUrl = URL(string: data.webformatURL)
UIView.animate(withDuration: 0.5, animations: {
self.navigationController!.pushViewController(popUpImagePage, animated: false)
})
}
//function of favourites button
func favouritesButtonAction(button : UIButton) {
//finding indexpath of table cell
guard let tableCell = button.tableViewCell as? SectionsforHome_Living else { return }
let tableIndexpath = home_LivingTableView.indexPath(for: tableCell)
//finding indexpath of collection cell
guard let collectionCell = button.collectionViewCell as? VarietiesofHome_Living else { return }
let collectionIndexpath = tableCell.home_LivingCollectionView.indexPath(for: collectionCell)
if button.isSelected == false{
favouritesIndicesArray.append([tableIndexpath!,collectionIndexpath!])
print(favouritesIndicesArray)
button.isSelected = true
} else {
favouritesIndicesArray = favouritesIndicesArray.filter(){ (indices: [IndexPath]) -> Bool in
return indices != [tableIndexpath!,collectionIndexpath!]
}
button.isSelected = false
}
}
}
| mit | 6f3620897bf019457a28382d8c9fcb1a | 34.819242 | 181 | 0.61216 | 5.620311 | false | false | false | false |
L550312242/SinaWeiBo-Switf | weibo 1/Class/Module(模块)/Home(首页)/View/CZStatusCell.swift | 1 | 4110 |
import UIKit
let StatusCellMargin: CGFloat = 8
// cell父类
class CZStatusCell: UITableViewCell {
// MARK: - 属性
/// 配图宽度约束
var pictureViewWidthCon: NSLayoutConstraint?
/// 配图高度约束
var pictureViewHeightCon: NSLayoutConstraint?
//MARK: -- 属性 --
///微博模型
var status: CZStatus?{
didSet{
//将模型赋值给 topView
topView.status = status
// 将模型赋值给配图视图
pictureView.status = status
// 调用模型的计算尺寸的方法
let size = pictureView.calcViewSize()
print("配图size: \(size)")
// 重新设置配图的宽高约束
pictureViewWidthCon?.constant = size.width
pictureViewHeightCon?.constant = size.height
//设置微博内容
contentLabel.text = status?.text
}
}
// 设置cell的模型,cell会根据模型,从新设置内容,更新约束.获取子控件的最大Y值
// 返回cell的高度
func rowHeight(status:CZStatus) ->CGFloat{
//设置cell模型
self.status = status
//更新约束
layoutIfNeeded()
//获取子控件的最大Y值
let maxY = CGRectGetMaxY(bottomView.frame)
return maxY
}
//Mark: 构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepareUI()
}
//Mark: --- 准备UI ---
func prepareUI() {
//添加子控件
contentView .addSubview(topView)
contentView .addSubview(contentLabel)
contentView.addSubview(pictureView)
contentView.addSubview(bottomView)
//添加约束
topView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: contentView, size: CGSize(width: UIScreen.width(), height: 53))
//微博内容
contentLabel.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topView, size: nil, offset: CGPoint(x: StatusCellMargin, y: StatusCellMargin))
//设置宽度
contentView.addConstraint( NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.width() - 2 * StatusCellMargin))
// // 微博配图
// 因为转发微博需要设置配图约束,不能再这里设置配图的约束,需要在创建一个cell继承CZStatusCell,添加上配图的约束
//底部视图
bottomView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: UIScreen.width(), height: 44), offset: CGPoint(x: -StatusCellMargin, y: StatusCellMargin))
// //contentView底部和contentLabel的底部重合
// contentView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: bottomView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
}
//Mark: --- 懒加载 ---
//顶部视图
private lazy var topView: CZStatusTopView = CZStatusTopView()
// 微博内容
lazy var contentLabel: UILabel = {
// let label = UILabel(fonsize: 16, textColor: UIColor.blackColor())
let label = UILabel(fonsize: 16, textColor: UIColor.blackColor())
// // 显示多行
// label.nummberOfLines = 0
// 显示多行
label.numberOfLines = 0
return label
}()
//微博配图
lazy var pictureView: CZStatusPictureView = CZStatusPictureView()
/// 底部视图
lazy var bottomView: CZStatusBottomView = CZStatusBottomView()
}
| apache-2.0 | 1d128e9da4791362fe2542bc170edceb | 31.017544 | 266 | 0.609315 | 4.661558 | false | false | false | false |
snapcard/wallet-gen-ios | WalletGenApp/WalletGenApp/WalletInfoCell.swift | 1 | 2941 | import UIKit
class WalletInfoCell : UICollectionViewCell {
private var wallet : [String : AnyObject]!
private var digitalCurrencyLabel : UILabel!
private var qrImage : UIImageView!
private var walletAddressLabel : UILabel!
private var linkButton : UIButton!
private var currency : String!
private var availableBalance : UILabel!
private var balance : UILabel!
private var totalBalance : UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.digitalCurrencyLabel = viewWithTag(1) as! UILabel
self.qrImage = viewWithTag(2) as! UIImageView
self.walletAddressLabel = viewWithTag(3) as! UILabel
self.linkButton = viewWithTag(4) as! UIButton
self.availableBalance = viewWithTag(8) as! UILabel
self.totalBalance = viewWithTag(10) as! UILabel
}
func setWallet(wallet : [String : AnyObject], currency : String) {
self.wallet = wallet
self.currency = currency
let depositAddresses = wallet["depositAddresses"] as! [String : String]
let availableBalances = wallet["availableBalances"] as! [String : Double]
let totalBalances = wallet["totalBalances"] as! [String : Double]
self.digitalCurrencyLabel.text = getLabel(currency)
self.walletAddressLabel.text = depositAddresses[currency]
self.availableBalance.text = String(format: "%.8f", arguments: [availableBalances[currency]!])
self.totalBalance.text = String(format: "%.8f", arguments: [totalBalances[currency]!])
self.qrImage.image = Utilities.toQrImage("\(getUriPrefix(currency)):\(depositAddresses[currency]!)", height: self.qrImage.frame.size.height)
self.linkButton.setTitle("\(getLookupUrl(currency))\(depositAddresses[currency]!)", forState: .Normal)
self.linkButton.addTarget(self, action: Selector("onLookupButtonSelected:"), forControlEvents: .TouchDown)
}
func onLookupButtonSelected(sender : UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: sender.titleForState(.Normal)!)!)
}
private func getUriPrefix(currency : String) -> String {
switch currency {
case "DOGE":
return "dogecoin"
case "LTC":
return "litecoin"
default:
return "bitcoin"
}
}
private func getLabel(currency : String) -> String {
switch currency {
case "DOGE":
return "Đ"
case "LTC":
return "Ł"
default:
return "฿"
}
}
private func getLookupUrl(currency : String) -> String {
switch currency {
case "DOGE":
return "https://dogechain.info/address/"
case "LTC":
return "https://block-explorer.com/address/"
default:
return "https://blockchain.info/address/"
}
}
} | mit | 049f6f432fe2a6f69dfa5ac9ad7ab298 | 37.155844 | 148 | 0.636364 | 4.589063 | false | false | false | false |
CybercomPoland/CPLKeyboardManager | CPLKeyboardManagerTests/CPLKeyboardManagerTests.swift | 1 | 10510 | //
// CPLKeyboardManagerTests.swift
// CPLKeyboardManagerTests
//
// Created by Michal Zietera on 12.04.2017.
// Copyright © 2017 Cybercom Poland. All rights reserved.
//
import XCTest
@testable import CPLKeyboardManager
import Quick
import Nimble
class CPLKeyboardBaseSpec: QuickSpec {
class CPLFakeKeyboardManagerBase : CPLKeyboardManagerBase {
var willShowNotificationReceived = false
var didShowNotificationReceived = false
var willChangeNotificationReceived = false
var didChangeNotificationReceived = false
var willHideNotificationReceived = false
var didHideNotificationReceived = false
//standard handlers flags
var standardWillShowHandlerWasCalled = false
var standardDidShowHandlerWasCalled = false
var standardWillChangeHandlerWasCalled = false
var standardDidChangeHandlerWasCalled = false
var standardWillHideHandlerWasCalled = false
var standardDidHideHandlerWasCalled = false
override func keyboardWillShow(notification: Notification) {
willShowNotificationReceived = true
super.keyboardWillShow(notification: notification)
}
override func keyboardDidShow(notification: Notification) {
didShowNotificationReceived = true
super.keyboardDidShow(notification: notification)
}
override func keyboardWillChange(notification: Notification) {
willChangeNotificationReceived = true
super.keyboardWillChange(notification: notification)
}
override func keyboardDidChange(notification: Notification) {
didChangeNotificationReceived = true
super.keyboardDidChange(notification: notification)
}
override func keyboardWillHide(notification: Notification) {
willHideNotificationReceived = true
super.keyboardWillHide(notification: notification)
}
override func keyboardDidHide(notification: Notification) {
didHideNotificationReceived = true
super.keyboardDidHide(notification: notification)
}
override func handleKeyboardEvent(ofType type: KeyboardEventType, withKeyboardData keyboardData: KeyboardEventData) {
switch type {
case .willShow:
standardWillShowHandlerWasCalled = true
case .didShow:
standardDidShowHandlerWasCalled = true
case .willChange:
standardWillChangeHandlerWasCalled = true
case .didChange:
standardDidChangeHandlerWasCalled = true
case .willHide:
standardWillHideHandlerWasCalled = true
case .didHide:
standardDidHideHandlerWasCalled = true
}
}
}
override func spec() {
var window: UIWindow!
let correctKeyboardNotificationUserInfo: [AnyHashable: Any] = [
UIKeyboardFrameBeginUserInfoKey: CGRect(x: 0, y: 300, width: 200, height: 200),
UIKeyboardFrameEndUserInfoKey: CGRect(x:0, y:100, width: 200, height: 200),
UIKeyboardAnimationDurationUserInfoKey: NSNumber(value: 0.33),
UIKeyboardAnimationCurveUserInfoKey: NSNumber(integerLiteral: 1)
]
let textFieldWithoutAutocorrection = UITextField(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
textFieldWithoutAutocorrection.autocorrectionType = .no
let textFieldWithAutocorrection = UITextField(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
textFieldWithAutocorrection.autocorrectionType = .yes
var fakeKbManagerBase: CPLFakeKeyboardManagerBase!
beforeEach {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
window = UIWindow()
window.addSubview(view)
view.addSubview(textFieldWithAutocorrection)
view.addSubview(textFieldWithoutAutocorrection)
fakeKbManagerBase = CPLFakeKeyboardManagerBase(view: view)
fakeKbManagerBase.start()
//RunLoop.current.run(until: Date())
}
afterEach {
window = nil
fakeKbManagerBase = nil
}
describe("when registered") {
it("responds to all keyboard notifications", closure: {
self.postAllKeyboardNotification()
expect(fakeKbManagerBase.willShowNotificationReceived).to(beTrue())
expect(fakeKbManagerBase.didShowNotificationReceived).to(beTrue())
expect(fakeKbManagerBase.willChangeNotificationReceived).to(beTrue())
expect(fakeKbManagerBase.didChangeNotificationReceived).to(beTrue())
expect(fakeKbManagerBase.willHideNotificationReceived).to(beTrue())
expect(fakeKbManagerBase.didHideNotificationReceived).to(beTrue())
})
}
describe("when not registered") {
it("doesn't respond to any keyboard notification", closure: {
fakeKbManagerBase.unregisterFromNotifications()
self.postAllKeyboardNotification()
expect(fakeKbManagerBase.willShowNotificationReceived).to(beFalse())
expect(fakeKbManagerBase.didShowNotificationReceived).to(beFalse())
expect(fakeKbManagerBase.willChangeNotificationReceived).to(beFalse())
expect(fakeKbManagerBase.didChangeNotificationReceived).to(beFalse())
expect(fakeKbManagerBase.willHideNotificationReceived).to(beFalse())
expect(fakeKbManagerBase.didHideNotificationReceived).to(beFalse())
})
}
describe("when tracking is enabled") {
it("handles correct keyboard notification", closure: {
fakeKbManagerBase.start()
self.postAllKeyboardNotification(withUserInfo: correctKeyboardNotificationUserInfo)
expect(fakeKbManagerBase.standardWillShowHandlerWasCalled).to(beTrue())
expect(fakeKbManagerBase.standardDidShowHandlerWasCalled).to(beTrue())
expect(fakeKbManagerBase.standardWillChangeHandlerWasCalled).to(beTrue())
expect(fakeKbManagerBase.standardDidChangeHandlerWasCalled).to(beTrue())
expect(fakeKbManagerBase.standardWillHideHandlerWasCalled).to(beTrue())
expect(fakeKbManagerBase.standardDidHideHandlerWasCalled).to(beTrue())
})
}
describe("when tracking is disabled") {
it("doesn't handle correct keyboard notification", closure: {
fakeKbManagerBase.stop()
self.postAllKeyboardNotification(withUserInfo: correctKeyboardNotificationUserInfo)
expect(fakeKbManagerBase.standardWillShowHandlerWasCalled).to(beFalse())
expect(fakeKbManagerBase.standardDidShowHandlerWasCalled).to(beFalse())
expect(fakeKbManagerBase.standardWillChangeHandlerWasCalled).to(beFalse())
expect(fakeKbManagerBase.standardDidChangeHandlerWasCalled).to(beFalse())
expect(fakeKbManagerBase.standardWillHideHandlerWasCalled).to(beFalse())
expect(fakeKbManagerBase.standardDidHideHandlerWasCalled).to(beFalse())
})
}
describe("isKeyboardFrameSame") {
var beginFrame: CGRect!
var endFrame: CGRect!
context("when begin height is equal to end height", {
beforeEach {
beginFrame = CGRect(x: 0, y: 300, width: 200, height: 200)
endFrame = CGRect(x: 0, y: 300, width: 200, height: 200)
}
describe("when end height is equal to stored one", {
it("returns true", closure: {
fakeKbManagerBase.currentKeyboardHeight = endFrame.height
let result = fakeKbManagerBase.isKeyboardFrameSame(beginRect: beginFrame, endRect: endFrame)
expect(result).to(beTrue())
})
})
describe("end height is not equal to stored one", {
it("returns false", closure: {
fakeKbManagerBase.currentKeyboardHeight = endFrame.height + 100
let result = fakeKbManagerBase.isKeyboardFrameSame(beginRect: beginFrame, endRect: endFrame)
expect(result).to(beFalse())
})
})
})
context("when begin height is not equal to end height", {
beforeEach {
beginFrame = CGRect(x: 0, y: 300, width: 200, height: 200)
endFrame = CGRect(x: 0, y: 200, width: 200, height: 300)
}
describe("end height is equal to stored one", {
it("returns false", closure: {
fakeKbManagerBase.currentKeyboardHeight = endFrame.height
let result = fakeKbManagerBase.isKeyboardFrameSame(beginRect: beginFrame, endRect: endFrame)
expect(result).to(beFalse())
})
})
describe("end height is not equal to stored one", {
it("returns false", closure: {
fakeKbManagerBase.currentKeyboardHeight = endFrame.height + 100
let result = fakeKbManagerBase.isKeyboardFrameSame(beginRect: beginFrame, endRect: endFrame)
expect(result).to(beFalse())
})
})
})
}
}
func postAllKeyboardNotification(withUserInfo userInfo: [AnyHashable: Any]? = nil) {
let notifCenter = NotificationCenter.default
notifCenter.post(name: NSNotification.Name.UIKeyboardWillShow, object: nil, userInfo: userInfo)
notifCenter.post(name: NSNotification.Name.UIKeyboardDidShow, object: nil, userInfo: userInfo)
notifCenter.post(name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil, userInfo: userInfo)
notifCenter.post(name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil, userInfo: userInfo)
notifCenter.post(name: NSNotification.Name.UIKeyboardWillHide, object: nil, userInfo: userInfo)
notifCenter.post(name: NSNotification.Name.UIKeyboardDidHide, object: nil, userInfo: userInfo)
}
}
| mit | 7edf6bdb53e8b3e1e6463ab64002f10e | 45.5 | 125 | 0.636407 | 5.533965 | false | false | false | false |
material-motion/motion-transitions-objc | tests/unit/TransitionTargetTests.swift | 1 | 1429 | /*
Copyright 2017-present The Material Motion 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 XCTest
import MotionTransitions
class TransitionTargetTests: XCTestCase {
func testCustomTargetResolution() {
let targetView = UIView()
let target = TransitionTarget(view: targetView)
let resolvedView = target.resolve(with: MockTransitionContext())
XCTAssertEqual(targetView, resolvedView)
}
func testForeResolution() {
let target = TransitionTarget.withForeView()
let context = MockTransitionContext()
let resolvedView = target.resolve(with: context)
XCTAssertEqual(context.foreViewController.view, resolvedView)
}
func testBackResolution() {
let target = TransitionTarget.withBackView()
let context = MockTransitionContext()
let resolvedView = target.resolve(with: context)
XCTAssertEqual(context.backViewController.view, resolvedView)
}
}
| apache-2.0 | 47ab19e4a1b7e22aa53de11bf70b1661 | 30.065217 | 73 | 0.764871 | 4.685246 | false | true | false | false |
dotmat/StatusPageIOSampleApp | StatusPageIOStatus/StatusPageIO/StatusPageIOUnresolvedIncidentsViewController.swift | 1 | 5173 | //
// StatusPageIOUnresolvedIncidentsViewControlle.swift
// CloudFlareStatus
//
// Created by Mathew Jenkinson on 09/03/2016.
// Copyright © 2016 Mathew Jenkinson. All rights reserved.
//
import Foundation
import UIKit
class StatusPageIOUnresolvedIncidentsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol {
// Functions and Connections
@IBOutlet var StatusPageIOUnresolvedIncidentsTableView : UITableView!
@IBOutlet weak var NavBar: UINavigationItem!
let api = APIController()
var StatusPageIOUnresolvedIncidentstableData = []
let cellIdentifier = "UnresolvedIncidentsResultsCell"
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func didReceiveAPIResults(results: AnyObject) {
dispatch_async(dispatch_get_main_queue(), {
print(results)
// This Page is going to get details of Status Summary API request, the API Results will get the full JSON string
// we can then use this to work out the state of the API and Twilio.
// We need to know from 'status' the 'description'
// From components we need the value for each item and inside the item we need the description - as the title.
self.NavBar.title = "Current Incidents"
let incidentsData = results["incidents"] as! NSArray
if incidentsData.count == 0 {
// If we have no incidents, print to the console with no incidents and then display a pop up that says that
print("No incidents")
self.StatusPageIOUnresolvedIncidentsTableView.hidden = true
self.displayAlertBox()
}
self.StatusPageIOUnresolvedIncidentstableData = incidentsData
self.StatusPageIOUnresolvedIncidentsTableView.reloadData()
})
}
func displayAlertBox(){
let alertController = UIAlertController(title: "No Incidents!", message:
"No incidents at this time!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return StatusPageIOUnresolvedIncidentstableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UnresolvedIncidentsResultsViewCell
if let rowData: NSDictionary = self.StatusPageIOUnresolvedIncidentstableData[indexPath.row] as? NSDictionary, descriptionTitle = rowData["name"] as? String {
if let componentData: NSArray = rowData["components"] as! NSArray {
if componentData.count > 0 {
let componentDictionary: NSDictionary = componentData[0] as! NSDictionary
if let componentDescription: String = componentDictionary["name"] as? String {
cell.IncidentComponentsEffectedLabel?.text = "Effects: \(componentDescription)"
}
else
{
cell.IncidentComponentsEffectedLabel?.text = ""
}
}
else
{
cell.IncidentComponentsEffectedLabel?.text = ""
}
}
let incidentUpdates: NSArray = rowData["incident_updates"] as! NSArray
let latestUpdate: NSDictionary = incidentUpdates[0] as! NSDictionary
let latestUpdateBody: String = latestUpdate["body"] as! String
cell.IncidentName?.text = descriptionTitle
cell.IncidentStatus?.text = "Current Status: \(rowData["status"] as! String)"
cell.UpdatedAtTimestampLabel?.text = "Last Update: \(rowData["updated_at"] as! String)"
cell.LatestInformationLabel?.text = "Latest: \(latestUpdateBody)"
}
return cell
}
override func viewDidAppear(animated: Bool) {
self.NavBar.title = "Refreshing Data..."
api.getStatusPageIOUnresolvedIncidents()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
api.delegate = self
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 41d7ff276056a3d4d2b26d542c34a0b9 | 41.743802 | 165 | 0.645012 | 5.567277 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Data/Model/Map/MapAnnotation.swift | 1 | 602 | import Foundation
import MapKit
class MapAnnotation: NSObject, MKAnnotation {
var title: String?
var subtitle: String?
var pinColor: UIColor
dynamic var coordinate: CLLocationCoordinate2D
var busData: RealtimeBus
var selected: Bool
init(title: String, coordinate: CLLocationCoordinate2D, pinColor: UIColor, data: RealtimeBus) {
self.title = title
self.subtitle = ""
self.coordinate = coordinate
self.pinColor = pinColor
self.busData = data
self.selected = false
super.init()
}
}
| gpl-3.0 | f50c471471363b43508ef0c2e546164e | 22.153846 | 99 | 0.63289 | 4.777778 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/MessageStorage/MMDefaultMessageStorage.swift | 1 | 13835 | //
// MMDefaultMessageStorage.swift
//
// Created by Andrey K. on 15/09/16.
//
//
import Foundation
import CoreData
/// Default implementation of the Message Storage protocol. Uses Core Data persistent storage with SQLite database.
@objc public class MMDefaultMessageStorage: NSObject, MMMessageStorage, MMMessageStorageFinders, MMMessageStorageRemovers {
var totalMessagesCount_: Int = 0
var nonSeenMessagesCount_: Int = 0
func updateCounters(total: Int?, nonSeen: Int?, force: Bool? = false) {
var doCall: Bool = false
if let total = total, total != totalMessagesCount_ {
doCall = true
totalMessagesCount_ = total
}
if let nonSeen = nonSeen, nonSeen != nonSeenMessagesCount_ {
doCall = true
nonSeenMessagesCount_ = nonSeen
}
if doCall || (force ?? false) {
OperationQueue.main.addOperation {
self.messagesCountersUpdateHandler?(self.totalMessagesCount_, self.nonSeenMessagesCount_)
}
}
}
public var messagesCountersUpdateHandler: ((Int, Int) -> Void)? = nil {
didSet {
updateCounters(total: totalMessagesCount_, nonSeen: nonSeenMessagesCount_, force: true)
}
}
static func makeDefaultMessageStorage() -> MMDefaultMessageStorage? {
if let s = try? MMCoreDataStorage.makeSQLiteMessageStorage() {
return MMDefaultMessageStorage(coreDataStorage: s)
} else {
MMLogError("Mobile messaging failed to initialize default message storage")
return nil
}
}
public func countAllMessages(completion: @escaping (Int) -> Void) {
guard let context = self.context else {
completion(0)
return
}
context.perform {
completion(Message.MM_countOfEntitiesWithContext(context))
}
}
public var queue: DispatchQueue {
return serialQueue
}
init(coreDataStorage: MMCoreDataStorage) {
self.coreDataStorage = coreDataStorage
self.delegateQueue = DispatchQueue.main
super.init()
}
//MARK: - MessageStorage protocol
public func start() {
context = coreDataStorage?.newPrivateContext()
initMessagesCounters()
}
public func stop() {
context = nil
coreDataStorage = nil
delegate = nil
}
public func findAllMessageIds(completion: @escaping (([String]) -> Void)) {
guard let context = self.context else {
completion([])
return
}
context.perform {
let messageIds = Message.MM_selectAttribute("messageId", withPredicte: nil, inContext: context)
self.updateCounters(total: messageIds?.count ?? 0, nonSeen: nil)
completion(messageIds as? [String] ?? [])
}
}
public func findNonSeenMessageIds(completion: @escaping (([String]) -> Void)) {
guard let context = self.context else {
completion([])
return
}
context.perform {
let predicate = NSPredicate(format: "seenStatusValue == \(MMSeenStatus.NotSeen.rawValue)")
let messageIds = Message.MM_selectAttribute("messageId", withPredicte: predicate, inContext: context)
self.updateCounters(total: nil, nonSeen: messageIds?.count ?? 0)
completion(messageIds as? [String] ?? [])
}
}
public func insert(outgoing messages: [MMBaseMessage], completion: @escaping () -> Void) {
persist(
messages,
storageMessageConstructor: { (baseMessage, context) -> Message? in
return Message.makeMoMessage(from: baseMessage, context: context)
},
completion: completion)
}
public func insert(incoming messages: [MMBaseMessage], completion: @escaping () -> Void) {
persist(
messages,
storageMessageConstructor: { (baseMessage, context) -> Message? in
return Message.makeMtMessage(from: baseMessage, context: context)
},
completion: {
self.updateCounters(total: totalMessagesCount_ + messages.count, nonSeen: self.nonSeenMessagesCount_ + messages.count)
completion()
})
}
public func findMessage(withId messageId: MessageId) -> MMBaseMessage? {
guard let context = self.context else {
return nil
}
var result: MMBaseMessage?
context.performAndWait {
if let message = Message.MM_findFirstWithPredicate(NSPredicate(format: "messageId == %@", messageId), context: context), let baseMessage = message.baseMessage {
result = baseMessage
}
}
return result
}
public func update(messageSentStatus status: MM_MOMessageSentStatus, for messageId: MessageId, completion: @escaping () -> Void) {
updateMessages(
foundWith: NSPredicate(format: "messageId == %@", messageId),
applyChanges: { message in message.sentStatusValue = status.rawValue },
completion: completion)
}
public func update(messageSeenStatus status: MMSeenStatus, for messageId: MessageId, completion: @escaping () -> Void) {
var newSeenMessagsCount = 0
updateMessages(
foundWith: NSPredicate(format: "messageId == %@", messageId),
applyChanges: { message in
message.seenStatusValue = status.rawValue
if message.seenDate == nil && (status == .SeenNotSent || status == .SeenSent) {
message.seenDate = MobileMessaging.date.now
newSeenMessagsCount += 1
} else if status == .NotSeen {
message.seenDate = nil
}
},
completion: {
self.updateCounters(total: nil, nonSeen: max(0, self.nonSeenMessagesCount_ - newSeenMessagsCount))
completion()
})
}
public func update(deliveryReportStatus isDelivered: Bool, for messageId: MessageId, completion: @escaping () -> Void) {
updateMessages(
foundWith: NSPredicate(format: "messageId == %@", messageId),
applyChanges: { message in
message.isDeliveryReportSent = isDelivered
message.deliveryReportedDate = isDelivered ? MobileMessaging.date.now : nil
},
completion: completion)
}
//MARK: - Convenience
public weak var delegate: MMMessageStorageDelegate?
public var delegateQueue: DispatchQueue
//MARK: - MessageStorageFinders
public func findAllMessages(completion: @escaping FetchResultBlock) {
queue.async() {
guard let context = self.context else {
completion(nil)
return
}
var baseMessages: [MMBaseMessage]? = nil
context.performAndWait {
let messages = Message.MM_findAllWithPredicate(nil, context: context)
self.updateCounters(total: messages?.count ?? 0, nonSeen: nil)
baseMessages = messages?.baseMessages
}
completion(baseMessages)
}
}
public func findMessages(withIds messageIds: [MessageId], completion: @escaping FetchResultBlock) {
queue.async() {
guard let context = self.context , !messageIds.isEmpty else {
completion(nil)
return
}
var messages: [Message]? = nil
context.performAndWait {
messages = Message.MM_findAllWithPredicate(NSPredicate(format: "messageId IN %@", messageIds), context: context)
}
completion(messages?.baseMessages)
}
}
public func findMessages(withQuery query: MMQuery, completion: @escaping FetchResultBlock) {
queue.async() {
guard let context = self.context else {
completion(nil)
return
}
var messages: [Message]? = nil
context.performAndWait {
messages = Message.MM_findAll(withPredicate: query.predicate, sortDescriptors: query.sortDescriptors, limit: query.limit, skip: query.skip, inContext: context)
}
completion(messages?.baseMessages)
}
}
//MARK: - MessageStorageRemovers
public func removeAllMessages(completion: @escaping ([MessageId]) -> Void) {
queue.async() {
guard let context = self.context else {
completion([])
return
}
var removedMsgIds: [MessageId] = []
context.performAndWait {
if let messages = Message.MM_findAllInContext(context) {
removedMsgIds.append(contentsOf: messages.map({ $0.messageId }))
self.delete(messages: messages)
self.updateCounters(total: 0, nonSeen: 0)
}
}
completion(removedMsgIds)
}
}
public func remove(withIds messageIds: [MessageId], completion: @escaping ([MessageId]) -> Void) {
queue.async() {
guard let context = self.context , !messageIds.isEmpty else {
completion([])
return
}
var removedMsgIds: [MessageId] = []
context.performAndWait {
if let messages = Message.MM_findAllWithPredicate(NSPredicate(format: "messageId IN %@", messageIds), context: context)
{
let deletedNonSeenCount = messages.filter({ $0.seenStatusValue == MMSeenStatus.NotSeen.rawValue }).count
let deletedCount = messages.count
removedMsgIds.append(contentsOf: messages.map({ $0.messageId }))
self.delete(messages: messages)
self.updateCounters(total: max(0, self.totalMessagesCount_ - deletedCount), nonSeen: max(0, self.nonSeenMessagesCount_ - deletedNonSeenCount))
}
}
completion(removedMsgIds)
}
}
public func remove(withQuery query: MMQuery, completion: @escaping ([MessageId]) -> Void) {
queue.async() {
guard let context = self.context else {
completion([])
return
}
var removedMsgIds: [MessageId] = []
context.performAndWait {
if let messages = Message.MM_findAll(withPredicate: query.predicate, sortDescriptors: query.sortDescriptors, limit: query.limit, skip: query.skip, inContext: context)
{
let deletedNonSeenCount = messages.filter({ $0.seenStatusValue == MMSeenStatus.NotSeen.rawValue }).count
let deletedCount = messages.count
removedMsgIds.append(contentsOf: messages.map({ $0.messageId }))
self.delete(messages: messages)
self.updateCounters(total: max(0, self.totalMessagesCount_ - deletedCount), nonSeen: max(0, self.nonSeenMessagesCount_ - deletedNonSeenCount))
}
}
completion(removedMsgIds)
}
}
// MARK: - Internal
var coreDataStorage: MMCoreDataStorage?
var context: NSManagedObjectContext?
// MARK: - Private
private func initMessagesCounters() {
self.countAllAndNonSeenMessages(completion: { total, nonSeen in
self.updateCounters(total: total, nonSeen: nonSeen)
})
}
private func countAllAndNonSeenMessages(completion: @escaping (Int, Int) -> Void) {
guard let context = self.context else {
completion(0, 0)
return
}
context.perform {
let predicate = NSPredicate(format: "seenStatusValue == \(MMSeenStatus.NotSeen.rawValue)")
completion(Message.MM_countOfEntitiesWithContext(context), Message.MM_countOfEntitiesWithPredicate(predicate, inContext: context))
}
}
private func persist(_ messages: [MMBaseMessage], storageMessageConstructor: @escaping (MMBaseMessage, NSManagedObjectContext) -> Message?, completion: () -> Void) {
guard let context = self.context, !messages.isEmpty else {
completion()
return
}
let persistedMessageIds: Set<String> = Set(Message.MM_selectAttribute("messageId", withPredicte: nil, inContext: context) as? Array<String> ?? Array())
let messagesToStore = messages.filter({ !persistedMessageIds.contains($0.messageId) })
if !messagesToStore.isEmpty {
context.performAndWait {
messagesToStore.forEach({
_ = storageMessageConstructor($0, context)
})
context.MM_saveToPersistentStoreAndWait()
}
}
completion()
callDelegateIfNeeded {
self.delegate?.didInsertNewMessages(messagesToStore)
}
}
private let serialQueue: DispatchQueue = MMQueue.Serial.New.MessageStorageQueue.queue.queue
private func delete(messages: [Message]) {
guard let context = context else {
return
}
let deleted = messages.baseMessages
messages.forEach { message in
context.delete(message)
}
context.MM_saveToPersistentStoreAndWait()
self.callDelegateIfNeeded {
self.delegate?.didRemoveMessages(deleted)
}
}
private func didUpdate(message: Message) {
guard let baseMessage = message.baseMessage else {
return
}
self.callDelegateIfNeeded {
self.delegate?.didUpdateMessage(baseMessage)
}
}
private func updateMessages(foundWith predicate: NSPredicate, applyChanges: @escaping (Message) -> Void, completion: @escaping () -> Void) {
guard let context = context else {
completion()
return
}
context.performAndWait {
Message.MM_findAllWithPredicate(predicate, context: context)?.forEach {
applyChanges($0)
context.MM_saveToPersistentStoreAndWait()
self.didUpdate(message: $0)
}
}
completion()
}
private func callDelegateIfNeeded(block: @escaping (() -> Void)) {
if self.delegate != nil {
delegateQueue.async(execute: block)
}
}
}
extension MMMessageStorage {
func batchDeliveryStatusUpdate(messages: [MessageManagedObject], completion: @escaping () -> Void) {
let updatingGroup = DispatchGroup()
messages.forEach {
updatingGroup.enter()
self.update(deliveryReportStatus: $0.reportSent, for: $0.messageId, completion: {
updatingGroup.leave()
})
}
updatingGroup.notify(queue: DispatchQueue.global(qos: .default), execute: completion)
}
func batchFailedSentStatusUpdate(messageIds: [String], completion: @escaping () -> Void) {
let updatingGroup = DispatchGroup()
messageIds.forEach {
updatingGroup.enter()
self.update(messageSentStatus: MM_MOMessageSentStatus.SentWithFailure, for: $0, completion: {
updatingGroup.leave()
})
}
updatingGroup.notify(queue: DispatchQueue.global(qos: .default), execute: completion)
}
func batchSentStatusUpdate(messages: [MM_MOMessage], completion: @escaping () -> Void) {
let updatingGroup = DispatchGroup()
messages.forEach {
updatingGroup.enter()
self.update(messageSentStatus: $0.sentStatus, for: $0.messageId, completion: {
updatingGroup.leave()
})
}
updatingGroup.notify(queue: DispatchQueue.global(qos: .default), execute: completion)
}
func batchSeenStatusUpdate(messageIds: [String], seenStatus: MMSeenStatus, completion: @escaping () -> Void) {
let updatingGroup = DispatchGroup()
messageIds.forEach {
updatingGroup.enter()
self.update(messageSeenStatus: seenStatus, for: $0, completion: {
updatingGroup.leave()
})
}
updatingGroup.notify(queue: DispatchQueue.global(qos: .default), execute: completion)
}
}
extension Array where Element: Message {
fileprivate var baseMessages: [MMBaseMessage] {
return self.compactMap { $0.baseMessage }
}
}
| apache-2.0 | aa1587d9b94365bd234a26e8d82305f2 | 31.174419 | 170 | 0.717962 | 3.756449 | false | false | false | false |
Coderian/SwiftedGPX | SwiftedGPX/Elements/LongitudeType.swift | 1 | 900 | //
// Longitude.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX LongitudeType
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:simpleType name="longitudeType">
/// <xsd:annotation>
/// <xsd:documentation>
/// The longitude of the point. Decimal degrees, WGS84 datum.
/// </xsd:documentation>
/// </xsd:annotation>
/// <xsd:restriction base="xsd:decimal">
/// <xsd:minInclusive value="-180.0"/>
/// <xsd:maxExclusive value="180.0"/>
/// </xsd:restriction>
/// </xsd:simpleType>
public class LongitudeType {
var value:Double = 0.0
var originalValue:String!
public init(longitude: String){
self.originalValue = longitude
self.value = Double(longitude)!
}
} | mit | 2538fe01490dc0cfbf110756ed113b05 | 25.969697 | 72 | 0.598425 | 3.380228 | false | false | false | false |
Ahmed-Ali/RealmObjectEditor | Realm Object Editor/Implementation.swift | 2 | 3096 | //
// Implementation.swift
//
// Create by Ahmed Ali on 24/1/2015
// Copyright © 2015 Ahmed Ali Individual Mobile Developer. All rights reserved.
// Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
class Implementation : NSObject{
var defaultValuesDefination : String!
var fileExtension : String!
var forEachIgnoredProperty : String!
var forEachIndexedAttribute : String!
var forEachPropertyWithDefaultValue : String!
var headerImport : String!
var ignoredProperties : String!
var indexedAttributesDefination : String!
var modelDefinition : String!
var modelEnd : String!
var modelStart : String!
var primaryKeyDefination : String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary){
defaultValuesDefination = dictionary["defaultValuesDefination"] as? String
fileExtension = dictionary["fileExtension"] as? String
forEachIgnoredProperty = dictionary["forEachIgnoredProperty"] as? String
forEachIndexedAttribute = dictionary["forEachIndexedAttribute"] as? String
forEachPropertyWithDefaultValue = dictionary["forEachPropertyWithDefaultValue"] as? String
headerImport = dictionary["headerImport"] as? String
ignoredProperties = dictionary["ignoredProperties"] as? String
indexedAttributesDefination = dictionary["indexedAttributesDefination"] as? String
modelDefinition = dictionary["modelDefinition"] as? String
modelEnd = dictionary["modelEnd"] as? String
modelStart = dictionary["modelStart"] as? String
primaryKeyDefination = dictionary["primaryKeyDefination"] as? String
}
/**
* Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> NSDictionary
{
let dictionary = NSMutableDictionary()
if defaultValuesDefination != nil{
dictionary["defaultValuesDefination"] = defaultValuesDefination
}
if fileExtension != nil{
dictionary["fileExtension"] = fileExtension
}
if forEachIgnoredProperty != nil{
dictionary["forEachIgnoredProperty"] = forEachIgnoredProperty
}
if forEachIndexedAttribute != nil{
dictionary["forEachIndexedAttribute"] = forEachIndexedAttribute
}
if forEachPropertyWithDefaultValue != nil{
dictionary["forEachPropertyWithDefaultValue"] = forEachPropertyWithDefaultValue
}
if headerImport != nil{
dictionary["headerImport"] = headerImport
}
if ignoredProperties != nil{
dictionary["ignoredProperties"] = ignoredProperties
}
if indexedAttributesDefination != nil{
dictionary["indexedAttributesDefination"] = indexedAttributesDefination
}
if modelDefinition != nil{
dictionary["modelDefinition"] = modelDefinition
}
if modelEnd != nil{
dictionary["modelEnd"] = modelEnd
}
if modelStart != nil{
dictionary["modelStart"] = modelStart
}
if primaryKeyDefination != nil{
dictionary["primaryKeyDefination"] = primaryKeyDefination
}
return dictionary
}
} | mit | c3b9917a0d1be30323a169f2a9e169ec | 33.4 | 180 | 0.770275 | 4.415121 | false | false | false | false |
danielmartinprieto/AudioPlayer | AudioPlayer/AudioPlayerTests/RetryEventProducer_Tests.swift | 2 | 1584 | //
// RetryEventProducer_Tests.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 15/04/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import XCTest
@testable import AudioPlayer
class RetryEventProducer_Tests: XCTestCase {
var listener: FakeEventListener!
var producer: RetryEventProducer!
override func setUp() {
super.setUp()
listener = FakeEventListener()
producer = RetryEventProducer()
producer.eventListener = listener
}
override func tearDown() {
listener = nil
producer.stopProducingEvents()
producer = nil
super.tearDown()
}
func testEventListenerGetsCalledUntilMaximumRetryCountHit() {
var receivedRetry = 1
let maximumRetryCount = 3
let r = expectation(description: "Waiting for `onEvent` to get called")
listener.eventClosure = { event, producer in
if let event = event as? RetryEventProducer.RetryEvent {
if event == .retryAvailable {
receivedRetry += 1
} else if event == .retryFailed && receivedRetry == maximumRetryCount {
r.fulfill()
} else {
XCTFail()
r.fulfill()
}
}
}
producer.retryTimeout = 1
producer.maximumRetryCount = maximumRetryCount
producer.startProducingEvents()
waitForExpectations(timeout: 5) { e in
if let _ = e {
XCTFail()
}
}
}
}
| mit | c786a034cb41565b12d184111c4644fa | 26.293103 | 87 | 0.574226 | 5.156352 | false | true | false | false |
anagac3/living-together-server | Tests/AppTests/ToDoControllerTests.swift | 1 | 12240 | //
// ToDoControllerTests.swift
// LivingTogetherServer
//
// Created by Andres Aguilar on 8/21/17.
//
//
import XCTest
import Testing
import HTTP
import Sockets
@testable import Vapor
@testable import App
/// This file shows an example of testing an
/// individual controller without initializing
/// a Droplet.
class ToDoControllerTests: TestCase {
let householdName = " Andre's House "
let residentName = "Andres Aguilar"
let householdName2 = "Rene's House"
let residentName2 = "Rene Signoret"
let toDoDescription = "Sweep the floor"
let drop = try! Droplet.testable()
/// For these tests, we won't be spinning up a live
/// server, and instead we'll be passing our constructed
/// requests programmatically
/// this is usually an effective way to test your
/// application in a convenient and safe manner
/// See RouteTests for an example of a live server test
let controller = ToDoController()
func testToDoRoutes() throws {
let household = Household(name: householdName)
try household.save()
let resident = Resident(name: residentName, householdId: try Node(node: household.id))
try resident.save()
let household2 = Household(name: householdName2)
try household2.save()
let resident2 = Resident(name: residentName2, householdId: try Node(node: household2.id))
try resident2.save()
try deleteAll()
try fetchAll(expectCount: 0)
//Household 1
let toDoId1 = try create(householdId: (household.id?.int)!, residentId: (resident.id?.int)!)
let toDoId2 = try create(householdId: (household.id?.int)!, residentId: (resident.id?.int)!)
//Household 2
_ = try create(householdId: (household2.id!.int)!, residentId: (resident2.id?.int)!)
try fetchAll(expectCount: 3)
try fetchAll(inHousehold: (household.id?.int)!, residentId: (resident.id?.int)!, expectCount: 2)
try fetchAll(inHousehold: (household2.id?.int)!, residentId: (resident2.id?.int)!, expectCount: 1)
let _ = try fetchOne(id: toDoId2!, residentId: (resident.id?.int)!)
try complete(toDoId: toDoId2!, residentId: (resident.id?.int)!)
try reopen(toDoId: toDoId2!, residentId: (resident.id?.int)!)
try history(toDoId: toDoId2!, residentId: (resident.id?.int)!, expectCount: 1)
try complete(toDoId: toDoId1!, residentId: (resident.id?.int)!)
try reopen(toDoId: toDoId1!, residentId: (resident.id?.int)!)
try complete(toDoId: toDoId1!, residentId: (resident.id?.int)!)
try reopen(toDoId: toDoId1!, residentId: (resident.id?.int)!)
try history(toDoId: toDoId1!, residentId: (resident.id?.int)!, expectCount: 2)
try createWrongResident(householdId: (household.id?.int)!, residentId: (resident2.id?.int)!)
try deleteWrongResident(toDoId: toDoId2!, residentId: (resident2.id?.int)!)
try showWrongResident(toDoId: toDoId2!, residentId: (resident2.id?.int)!)
try showWithUnknownResident(toDoId: toDoId1!, residentId: 12512)
try showBadRequest(toDoId:toDoId1! , residentId: (resident2.id?.int)!)
try completeWrongResident(toDoId:toDoId1! , residentId: (resident2.id?.int)!)
try reopenWrongResident(toDoId:toDoId1! , residentId: (resident2.id?.int)!)
try deleteOne(id: toDoId1!, residentId: (resident.id?.int)!)
try fetchAll(inHousehold: (household.id?.int)!, residentId: (resident.id?.int)!, expectCount: 1)
}
func create(householdId: Int, residentId: Int) throws -> Int? {
let req = Request.makeTest(method: .post, path:"create")
req.json = try JSON(node: ["description": toDoDescription, "householdId": householdId, "asigneeId": residentId])
let res = try controller.create(req).makeResponse()
let json = res.json
XCTAssertNotNil(json)
XCTAssertNotNil(json?["description"]?.string)
XCTAssertNotNil(json?["householdId"]?.int)
XCTAssertNotNil(json?["asigneeId"]?.int)
XCTAssertNotNil(json?["id"]?.int)
XCTAssertEqual(json?["description"]?.string, toDoDescription)
XCTAssertEqual(json?["householdId"]?.int, householdId)
XCTAssertEqual(json?["asigneeId"]?.int, residentId)
XCTAssertFalse((json?["completed"]?.bool)!)
return try json?.get("id")
}
func fetchOne(id: Int, residentId: Int) throws -> JSON {
let req = Request.makeTest(method: .post, path: "show")
req.json = try JSON(node: ["id": id, "asigneeId": residentId])
let res = try controller.show(req).makeResponse()
let json = res.json
XCTAssertNotNil(json)
XCTAssertNotNil(json?["description"])
XCTAssertNotNil(json?["householdId"])
XCTAssertNotNil(json?["asigneeId"])
XCTAssertNotNil(json?["id"])
XCTAssertEqual(json?["id"]?.int, id)
return json!
}
func fetchAll(expectCount count: Int) throws {
let req = Request.makeTest(method: .get)
let res = try controller.index(req).makeResponse()
let json = res.json
XCTAssertNotNil(json?.array)
XCTAssertEqual(json?.array?.count, count)
}
func fetchAll(inHousehold householdId: Int, residentId: Int ,expectCount count: Int) throws {
let req = Request.makeTest(method: .post, path: "showAll")
req.json = try JSON(node: ["householdId": householdId, "asigneeId": residentId])
let res = try controller.fetchAll(req).makeResponse()
let json = res.json
XCTAssertNotNil(json?.array)
XCTAssertEqual(json?.array?.count, count)
}
func deleteOne(id: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "delete")
req.json = try JSON(node: ["id": id, "asigneeId": residentId])
_ = try controller.delete(req)
}
func deleteAll() throws {
let req = Request.makeTest(method: .post, path: "deleteAll")
_ = try controller.clear(req)
}
func createWrongResident(householdId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "create")
req.json = try JSON(node: ["description": toDoDescription, "householdId": householdId, "asigneeId": residentId])
XCTAssertThrowsError(try controller.create(req).makeResponse()) { (error) -> Void in
guard let status = (error as? Abort)?.status else {
XCTFail("Error status not found")
return
}
XCTAssertEqual(status, Abort.unauthorized.status)
}
}
func deleteWrongResident(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "delete")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
XCTAssertThrowsError(try controller.delete(req).makeResponse()) { (error) -> Void in
guard let status = (error as? Abort)?.status else {
XCTFail("Error status not found")
return
}
XCTAssertEqual(status, Abort.unauthorized.status)
}
}
func showWrongResident(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "show")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
XCTAssertThrowsError(try controller.show(req).makeResponse()) { (error) -> Void in
guard let status = (error as? Abort)?.status else {
XCTFail("Error status not found")
return
}
XCTAssertEqual(status, Abort.unauthorized.status)
}
}
func showWithUnknownResident(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "show")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
XCTAssertThrowsError(try controller.show(req).makeResponse()) { (error) -> Void in
guard let status = (error as? Abort)?.status else {
XCTFail("Error status not found")
return
}
XCTAssertEqual(status, Abort.notFound.status)
}
}
func showBadRequest(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "show")
req.json = try JSON(node: ["id": toDoId, "residentId": residentId])
XCTAssertThrowsError(try controller.show(req).makeResponse()) { (error) -> Void in
guard let status = (error as? Abort)?.status else {
XCTFail("Error status not found")
return
}
XCTAssertEqual(status, Abort.badRequest.status)
}
}
func complete(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "complete")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
let res = try controller.complete(req).makeResponse()
let json = res.json
XCTAssertNotNil(json)
XCTAssertNotNil(json?["description"]?.string)
XCTAssertNotNil(json?["householdId"]?.int)
XCTAssertNotNil(json?["asigneeId"]?.int)
XCTAssertNotNil(json?["id"]?.int)
XCTAssertEqual(json?["description"]?.string, toDoDescription)
XCTAssertEqual(json?["asigneeId"]?.int, residentId)
XCTAssertTrue((json?["completed"]?.bool)!)
}
func reopen(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "reopen")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
let res = try controller.reopen(req).makeResponse()
let json = res.json
XCTAssertNotNil(json)
XCTAssertNotNil(json?["description"]?.string)
XCTAssertNotNil(json?["householdId"]?.int)
XCTAssertNotNil(json?["asigneeId"]?.int)
XCTAssertNotNil(json?["id"]?.int)
XCTAssertEqual(json?["description"]?.string, toDoDescription)
XCTAssertEqual(json?["asigneeId"]?.int, residentId)
XCTAssertFalse((json?["completed"]?.bool)!)
}
func completeWrongResident(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "complete")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
XCTAssertThrowsError(try controller.complete(req).makeResponse()) { (error) -> Void in
guard let status = (error as? Abort)?.status else {
XCTFail("Error status not found")
return
}
XCTAssertEqual(status, Abort.unauthorized.status)
}
}
func reopenWrongResident(toDoId: Int, residentId: Int) throws {
let req = Request.makeTest(method: .post, path: "reopen")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
XCTAssertThrowsError(try controller.reopen(req).makeResponse()) { (error) -> Void in
guard let status = (error as? Abort)?.status else {
XCTFail("Error status not found")
return
}
XCTAssertEqual(status, Abort.unauthorized.status)
}
}
func history(toDoId: Int, residentId: Int, expectCount count: Int) throws {
let req = Request.makeTest(method: .post, path: "history")
req.json = try JSON(node: ["id": toDoId, "asigneeId": residentId])
let res = try controller.history(req).makeResponse()
let json = res.json
XCTAssertNotNil(json)
XCTAssertEqual(json?.array?.count, count)
}
}
// MARK: Manifest
extension ToDoControllerTests {
/// This is a requirement for XCTest on Linux
/// to function properly.
/// See ./Tests/LinuxMain.swift for examples
static let allTests = [
("testToDoRoutes", testToDoRoutes),
]
}
| mit | 77777b43a3b74d23e91c632a2a66a6b6 | 39.39604 | 120 | 0.611029 | 4.085447 | false | true | false | false |
yonaskolb/SwagGen | Templates/Swift/Sources/AnyCodable.swift | 7 | 6297 | import Foundation
public struct AnyCodable {
let value: Any
init<T>(_ value: T?) {
self.value = value ?? ()
}
}
extension AnyCodable: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self.init(())
} else if let bool = try? container.decode(Bool.self) {
self.init(bool)
} else if let int = try? container.decode(Int.self) {
self.init(int)
} else if let uint = try? container.decode(UInt.self) {
self.init(uint)
} else if let double = try? container.decode(Double.self) {
self.init(double)
} else if let string = try? container.decode(String.self) {
self.init(string)
} else if let array = try? container.decode([AnyCodable].self) {
self.init(array.map { $0.value })
} else if let dictionary = try? container.decode([String: AnyCodable].self) {
self.init(dictionary.mapValues { $0.value })
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "AnyCodable value cannot be decoded")
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self.value {
case is Void:
try container.encodeNil()
case let bool as Bool:
try container.encode(bool)
case let int as Int:
try container.encode(int)
case let int8 as Int8:
try container.encode(int8)
case let int16 as Int16:
try container.encode(int16)
case let int32 as Int32:
try container.encode(int32)
case let int64 as Int64:
try container.encode(int64)
case let uint as UInt:
try container.encode(uint)
case let uint8 as UInt8:
try container.encode(uint8)
case let uint16 as UInt16:
try container.encode(uint16)
case let uint32 as UInt32:
try container.encode(uint32)
case let uint64 as UInt64:
try container.encode(uint64)
case let float as Float:
try container.encode(float)
case let double as Double:
try container.encode(double)
case let string as String:
try container.encode(string)
case let date as Date:
try container.encode(date)
case let url as URL:
try container.encode(url)
case let array as [Any?]:
try container.encode(array.map { AnyCodable($0) })
case let dictionary as [String: Any?]:
try container.encode(dictionary.mapValues { AnyCodable($0) })
case let object as Encodable:
try object.encode(to: encoder)
default:
let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "AnyCodable value cannot be encoded")
throw EncodingError.invalidValue(self.value, context)
}
}
}
extension AnyCodable: Equatable {
static public func ==(lhs: AnyCodable, rhs: AnyCodable) -> Bool {
switch (lhs.value, rhs.value) {
case is (Void, Void):
return true
case let (lhs as Bool, rhs as Bool):
return lhs == rhs
case let (lhs as Int, rhs as Int):
return lhs == rhs
case let (lhs as Int8, rhs as Int8):
return lhs == rhs
case let (lhs as Int16, rhs as Int16):
return lhs == rhs
case let (lhs as Int32, rhs as Int32):
return lhs == rhs
case let (lhs as Int64, rhs as Int64):
return lhs == rhs
case let (lhs as UInt, rhs as UInt):
return lhs == rhs
case let (lhs as UInt8, rhs as UInt8):
return lhs == rhs
case let (lhs as UInt16, rhs as UInt16):
return lhs == rhs
case let (lhs as UInt32, rhs as UInt32):
return lhs == rhs
case let (lhs as UInt64, rhs as UInt64):
return lhs == rhs
case let (lhs as Float, rhs as Float):
return lhs == rhs
case let (lhs as Double, rhs as Double):
return lhs == rhs
case let (lhs as String, rhs as String):
return lhs == rhs
case (let lhs as [String: AnyCodable], let rhs as [String: AnyCodable]):
return lhs == rhs
case (let lhs as [AnyCodable], let rhs as [AnyCodable]):
return lhs == rhs
default:
return false
}
}
}
extension AnyCodable: CustomStringConvertible {
public var description: String {
switch value {
case is Void:
return String(describing: nil as Any?)
case let value as CustomStringConvertible:
return value.description
default:
return String(describing: value)
}
}
}
extension AnyCodable: CustomDebugStringConvertible {
public var debugDescription: String {
switch value {
case let value as CustomDebugStringConvertible:
return "AnyCodable(\(value.debugDescription))"
default:
return "AnyCodable(\(self.description))"
}
}
}
extension AnyCodable: ExpressibleByNilLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByStringLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
public init(nilLiteral: ()) {
self.init(nil as Any?)
}
public init(booleanLiteral value: Bool) {
self.init(value)
}
public init(integerLiteral value: Int) {
self.init(value)
}
public init(floatLiteral value: Double) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
public init(stringLiteral value: String) {
self.init(value)
}
public init(arrayLiteral elements: Any...) {
self.init(elements)
}
public init(dictionaryLiteral elements: (AnyHashable, Any)...) {
self.init(Dictionary<AnyHashable, Any>(elements, uniquingKeysWith: { (first, _) in first }))
}
}
| mit | c92b96a7186f01ccb828dc63598cad31 | 32.494681 | 219 | 0.589963 | 4.606437 | false | false | false | false |
Jauzee/showroom | Showroom/ViewControllers/CarouselViewController/Flow/PageCollectionLayout.swift | 1 | 4805 | //
// PageCollectionLayout.swift
// TestCollectionView
//
// Created by Alex K. on 04/05/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class PageCollectionLayout: UICollectionViewFlowLayout {
fileprivate var lastCollectionViewSize: CGSize = CGSize.zero
var scalingOffset: CGFloat = 200
var minimumScaleFactor: CGFloat = 0.9
var minimumAlphaFactor: CGFloat = 0.3
var scaleItems: Bool = true
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit(itemSize)
}
init(itemSize: CGSize) {
super.init()
commonInit(itemSize)
}
}
// MARK: life cicle
extension PageCollectionLayout {
fileprivate func commonInit(_ itemSize: CGSize) {
scrollDirection = .horizontal
minimumLineSpacing = 6
self.itemSize = itemSize
}
}
// MARK: override
extension PageCollectionLayout {
override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) {
super.invalidateLayout(with: context)
guard let collectionView = self.collectionView else { return }
if collectionView.bounds.size != lastCollectionViewSize {
self.configureInset()
self.lastCollectionViewSize = collectionView.bounds.size
}
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = self.collectionView else {
return proposedContentOffset
}
let proposedRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height)
guard let layoutAttributes = self.layoutAttributesForElements(in: proposedRect) else {
return proposedContentOffset
}
var candidateAttributes: UICollectionViewLayoutAttributes?
let proposedContentOffsetCenterX = proposedContentOffset.x + collectionView.bounds.width / 2
for attributes in layoutAttributes {
if attributes.representedElementCategory != .cell {
continue
}
if candidateAttributes == nil {
candidateAttributes = attributes
continue
}
if fabs(attributes.center.x - proposedContentOffsetCenterX) < fabs(candidateAttributes!.center.x - proposedContentOffsetCenterX) {
candidateAttributes = attributes
}
}
guard let aCandidateAttributes = candidateAttributes else {
return proposedContentOffset
}
var newOffsetX = aCandidateAttributes.center.x - collectionView.bounds.size.width / 2
let offset = newOffsetX - collectionView.contentOffset.x
if (velocity.x < 0 && offset > 0) || (velocity.x > 0 && offset < 0) {
let pageWidth = self.itemSize.width + self.minimumLineSpacing
newOffsetX += velocity.x > 0 ? pageWidth : -pageWidth
}
return CGPoint(x: newOffsetX, y: proposedContentOffset.y)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = self.collectionView,
let superAttributes = super.layoutAttributesForElements(in: rect) else {
return super.layoutAttributesForElements(in: rect)
}
if scaleItems == false{
return super.layoutAttributesForElements(in: rect)
}
let contentOffset = collectionView.contentOffset
let size = collectionView.bounds.size
let visibleRect = CGRect(x: contentOffset.x, y: contentOffset.y, width: size.width, height: size.height)
let visibleCenterX = visibleRect.midX
guard case let newAttributesArray as [UICollectionViewLayoutAttributes] = NSArray(array: superAttributes, copyItems: true) else {
return nil
}
newAttributesArray.forEach {
let distanceFromCenter = visibleCenterX - $0.center.x
let absDistanceFromCenter = min(abs(distanceFromCenter), self.scalingOffset)
let scale = absDistanceFromCenter * (self.minimumScaleFactor - 1) / self.scalingOffset + 1
$0.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1)
let alpha = absDistanceFromCenter * (self.minimumAlphaFactor - 1) / self.scalingOffset + 1
$0.alpha = alpha
}
return newAttributesArray
}
}
// MARK: helpers
extension PageCollectionLayout {
fileprivate func configureInset() -> Void {
guard let collectionView = self.collectionView else {
return
}
let inset = collectionView.bounds.size.width / 2 - itemSize.width / 2
collectionView.contentInset = UIEdgeInsetsMake(0, inset, 0, inset)
collectionView.contentOffset = CGPoint(x: -inset, y: 0)
}
}
| gpl-3.0 | be6c3e45f5623da057154b79661eadde | 31.026667 | 146 | 0.707119 | 4.988577 | false | false | false | false |
artemnovichkov/TransitionRouter | Example/Example/ColorViewController.swift | 1 | 1192 | //
// ColorViewController.swift
// TransitionRouter
//
// Created by Artem Novichkov on 06/12/2016.
// Copyright © 2016 Artem Novichkov. All rights reserved.
//
import UIKit
class ColorViewController: UIViewController {
private let button: UIButton = .custom(with: "Dismiss")
private let color: UIColor
// MARK: - Lifecycle
init(color: UIColor) {
self.color = color
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 = color
view.addSubview(button)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
}
override func viewDidLayoutSubviews() {
button.center = view.center
button.frame.size = CGSize(width: 100, height: 20)
}
//Just for top and bottom edge gesture recognizers
override var prefersStatusBarHidden: Bool {
return true
}
// MARK: - Actions
func buttonAction() {
self.dismiss(animated: true)
}
}
| mit | 5c200c41784a602290eee4aa618b70c3 | 23.306122 | 84 | 0.628044 | 4.49434 | false | false | false | false |
ahoppen/swift | test/IRGen/prespecialized-metadata/struct-inmodule-2argument-1distinct_use.swift | 13 | 2853 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueVyS2iGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwCP{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwxx{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwcp{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwca{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwtk{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwta{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwet{{[^)]*}} to i8*)
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVwst{{[^)]*}} to i8*)
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVyS2iGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSiN", %swift.type* @"$sSiN", i32 0, i32 [[ALIGNMENT]], i64 3 }>, align [[ALIGNMENT]]
struct Value<First, Second> {
let first: First
let second: Second
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVyS2iGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13, second: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* [[ERASED_TYPE_2]], i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), [[INT]]* @"$s4main5ValueVMz") #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | d956c7efd6c362e8a1e6cec9673f60d7 | 53.865385 | 333 | 0.605678 | 3.041578 | false | false | false | false |
wangrui460/WRNavigationBar_swift | WRNavigationBar_swift/WRNavigationBar_swift/Demos/SecondViewController.swift | 1 | 3678 | //
// SecondViewController.swift
// WRNavigationBar_swift
//
// Created by wangrui on 2017/4/21.
// Copyright © 2017年 wangrui. All rights reserved.
//
// Github地址:https://github.com/wangrui460/WRNavigationBar_swift
import UIKit
private let NAVBAR_TRANSLATION_POINT:CGFloat = 0
class SecondViewController: UIViewController
{
lazy var tableView:UITableView = {
let table:UITableView = UITableView(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: self.view.bounds.height), style: .plain)
table.contentInset = UIEdgeInsetsMake(-CGFloat(kNavBarBottom), 0, 0, 0);
table.delegate = self
table.dataSource = self
return table
}()
lazy var imageView:UIImageView = {
let imgView = UIImageView(image: UIImage(named: "image2"))
return imgView
}()
override func viewDidLoad()
{
super.viewDidLoad()
title = "浮动效果"
view.backgroundColor = UIColor.red
view.addSubview(tableView)
tableView.tableHeaderView = imageView
}
deinit {
tableView.delegate = nil
print("SecondVC deinit")
}
}
// MARK: - viewWillAppear .. ScrollViewDidScroll
extension SecondViewController
{
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
tableView.delegate = self;
}
override func viewWillDisappear(_ animated: Bool)
{
super.viewWillDisappear(animated)
tableView.delegate = nil
navigationController?.navigationBar.wr_setTranslationY(translationY: 0)
}
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
let offsetY = scrollView.contentOffset.y
if (offsetY > NAVBAR_TRANSLATION_POINT)
{
UIView.animate(withDuration: 0.3, animations: { [weak self] in
if let weakSelf = self {
weakSelf.setNavigationBarTransformProgress(progress: 1)
}
})
}
else
{
UIView.animate(withDuration: 0.3, animations: { [weak self] in
if let weakSelf = self {
weakSelf.setNavigationBarTransformProgress(progress: 0)
}
})
}
}
// private
func setNavigationBarTransformProgress(progress:CGFloat)
{
navigationController?.navigationBar.wr_setTranslationY(translationY: -CGFloat(kNavBarHeight) * progress)
// 有系统的返回按钮,所以 hasSystemBackIndicator = YES
navigationController?.navigationBar.wr_setBarButtonItemsAlpha(alpha: 1 - progress, hasSystemBackIndicator: true)
}
}
extension SecondViewController:UITableViewDelegate,UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 15
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell.init(style: .default, reuseIdentifier: nil)
let str = String(format: "WRNavigationBar %zd", indexPath.row)
cell.textLabel?.text = str
cell.textLabel?.font = UIFont.systemFont(ofSize: 15)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
let vc:UIViewController = UIViewController()
vc.view.backgroundColor = UIColor.red
let str = String(format: "WRNavigationBar %zd", indexPath.row)
vc.title = str
navigationController?.pushViewController(vc, animated: true)
}
}
| mit | 150a1a57d3cba9b837e96130facf9881 | 30.643478 | 144 | 0.646881 | 4.813492 | false | false | false | false |
informmegp2/inform-me | InformME/ProfileOrganizerViewController.swift | 1 | 7026 | //
// ProfileOrganizerViewController.swift
// InformME
//
// Created by Amal Ibrahim on 2/26/16.
// Copyright © 2016 King Saud University. All rights reserved.
//
import Foundation
import UIKit
class ProfileOrganizerViewController : CenterViewController , UITextFieldDelegate{
/*Hello : ) */
@IBOutlet var usernameField: UITextField!
@IBOutlet var emailField: UITextField!
@IBOutlet var bioField: UITextField!
@IBOutlet var passwordField: UITextField!
var e :EventOrganizer = EventOrganizer()
@IBOutlet weak var menuButton: UIBarButtonItem!
override func viewDidLoad() {
usernameField.delegate = self
emailField.delegate = self
bioField.delegate = self
passwordField.delegate = self
if(Reachability.isConnectedToNetwork()){
e.requestInfo(){
(OrganizerInfo:EventOrganizer) in
dispatch_async(dispatch_get_main_queue()) {
self.usernameField.text = OrganizerInfo.username
self.emailField.text = OrganizerInfo.email
self.bioField.text = OrganizerInfo.bio
}
}
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func save(sender: AnyObject) {
let username = usernameField.text!
let email = emailField.text!
let password = passwordField.text!
let bio = bioField.text!
var count: Int
count = password.characters.count
if (username.isEmpty || email.isEmpty || password.isEmpty) {
displayAlert("", message: "يرجى إدخال كافة الحقول")
}// end if chack
else if ( count < 8)
{
displayAlert("", message: "يرجى إدخال كلمة مرور لا تقل عن ثمانية أحرف")
}//end else if
else if (isValidEmail(email) == false) {
displayAlert("", message: " يرجى إدخال صيغة بريد الكتروني صحيحة")
}
else {
let alertController = UIAlertController(title: "", message: " هل أنت متأكد من رغبتك بحفظ التغييرات؟", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "موافق", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
let e : EventOrganizer = EventOrganizer()
if(Reachability.isConnectedToNetwork()){
e.UpdateProfile ( username, email: email, password: password, bio: bio){
(flag:Bool) in
if(flag) {
//we should perform all segues in the main thread
dispatch_async(dispatch_get_main_queue()) {
print("Heeeeello")
self.performSegueWithIdentifier("backtohomepage", sender:sender)
}}
else{
self.displayAlert("", message: "البريد الإلكتروني مسجل لدينا سابقاً")
}
}
}
else {
self.displayAlert("", message: "الرجاء الاتصال بالانترنت")
}
}
let cancelAction = UIAlertAction(title: "إلغاء الأمر", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
NSLog("Cancel Pressed")
}
//Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
}
}//end fun save
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
//for alert massge
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
if( message != "يرجى إدخال كافة الحقول") {
self.dismissViewControllerAnimated(true, completion: nil) }
})))
self.presentViewController(alert, animated: true, completion: nil)
}//end fun display alert
@IBOutlet var scrollView: UIScrollView!
func textFieldDidBeginEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 150)), animated: true)
}
func textFieldDidEndEditing(textField: UITextField) {
scrollView.setContentOffset((CGPointMake(0, 0)), animated: true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
var window:UIWindow!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let containerViewController = ContainerViewController()
if(segue.identifier == "backtohomepage"){
containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("CenterViewController1") as? CenterViewController
print(window!.rootViewController)
window!.rootViewController = containerViewController
print(window!.rootViewController)
window!.makeKeyAndVisible()
containerViewController.centerViewController.delegate?.collapseSidePanels!()
}
}
func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) }
} | mit | 5bf827d4197fca9dd8322d00a31e2e3c | 30.618605 | 165 | 0.551567 | 5.114372 | false | false | false | false |
ben-ng/swift | test/expr/closure/trailing.swift | 5 | 14988 | // RUN: %target-typecheck-verify-swift
@discardableResult
func takeFunc(_ f: (Int) -> Int) -> Int {}
func takeValueAndFunc(_ value: Int, _ f: (Int) -> Int) {}
func takeTwoFuncs(_ f: (Int) -> Int, _ g: (Int) -> Int) {}
func takeFuncWithDefault(f : ((Int) -> Int)? = nil) {}
func takeTwoFuncsWithDefaults(f1 : ((Int) -> Int)? = nil, f2 : ((String) -> String)? = nil) {}
struct X {
func takeFunc(_ f: (Int) -> Int) {}
func takeValueAndFunc(_ value: Int, f: (Int) -> Int) {}
func takeTwoFuncs(_ f: (Int) -> Int, g: (Int) -> Int) {}
}
func addToMemberCalls(_ x: X) {
x.takeFunc() { x in x }
x.takeFunc() { $0 }
x.takeValueAndFunc(1) { x in x }
x.takeTwoFuncs({ x in x }) { y in y }
}
func addToCalls() {
takeFunc() { x in x }
takeFunc() { $0 }
takeValueAndFunc(1) { x in x }
takeTwoFuncs({ x in x }) { y in y }
}
func makeCalls() {
takeFunc { x in x }
takeFunc { $0 }
takeTwoFuncs ({ x in x }) { y in y }
}
func notPostfix() {
_ = 1 + takeFunc { $0 }
}
class C {
func map(_ x: (Int) -> Int) -> C { return self }
func filter(_ x: (Int) -> Bool) -> C { return self }
}
var a = C().map {$0 + 1}.filter {$0 % 3 == 0}
var b = C().map {$0 + 1}
.filter {$0 % 3 == 0}
var c = C().map
{
$0 + 1
}
var c2 = C().map // expected-note{{parsing trailing closure for this call}}
{ // expected-warning{{trailing closure is separated from call site}}
$0 + 1
}
var c3 = C().map // expected-note{{parsing trailing closure for this call}}
// blah blah blah
{ // expected-warning{{trailing closure is separated from call site}}
$0 + 1
}
// Calls with multiple trailing closures should be rejected until we have time
// to design it right.
// <rdar://problem/16835718> Ban multiple trailing closures
func multiTrailingClosure(_ a : () -> (), b : () -> ()) { // expected-note {{'multiTrailingClosure(_:b:)' declared here}}
multiTrailingClosure({}) {} // ok
multiTrailingClosure {} {} // expected-error {{missing argument for parameter #1 in call}} expected-error {{consecutive statements on a line must be separated by ';'}} {{26-26=;}} expected-error {{braced block of statements is an unused closure}} expected-error{{expression resolves to an unused function}}
}
func labeledArgumentAndTrailingClosure() {
// Trailing closures can bind to labeled parameters.
takeFuncWithDefault { $0 + 1 }
takeFuncWithDefault() { $0 + 1 }
// ... but not non-trailing closures.
takeFuncWithDefault({ $0 + 1 }) // expected-error {{missing argument label 'f:' in call}} {{23-23=f: }}
takeFuncWithDefault(f: { $0 + 1 })
// Trailing closure binds to last parameter, always.
takeTwoFuncsWithDefaults { "Hello, " + $0 }
takeTwoFuncsWithDefaults { $0 + 1 } // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '((String) -> String)?'}}
takeTwoFuncsWithDefaults(f1: {$0 + 1 })
}
// rdar://problem/17965209
func rdar17965209_f<T>(_ t: T) {}
func rdar17965209(x: Int = 0, _ handler: (_ y: Int) -> ()) {}
func rdar17965209_test() {
rdar17965209() {
(y) -> () in
rdar17965209_f(1)
}
rdar17965209(x: 5) {
(y) -> () in
rdar17965209_f(1)
}
}
// <rdar://problem/22298549> QoI: Unwanted trailing closure produces weird error
func limitXY(_ xy:Int, toGamut gamut: [Int]) {}
let someInt = 0
let intArray = [someInt]
limitXY(someInt, toGamut: intArray) {} // expected-error {{extra argument 'toGamut' in call}}
// <rdar://problem/23036383> QoI: Invalid trailing closures in stmt-conditions produce lowsy diagnostics
func retBool(x: () -> Int) -> Bool {}
func maybeInt(_: () -> Int) -> Int? {}
class Foo23036383 {
init() {}
func map(_: (Int) -> Int) -> Int? {}
func meth1(x: Int, _: () -> Int) -> Bool {}
func meth2(_: Int, y: () -> Int) -> Bool {}
func filter(by: (Int) -> Bool) -> [Int] {}
}
enum MyErr : Error {
case A
}
func r23036383(foo: Foo23036383?, obj: Foo23036383) {
if retBool(x: { 1 }) { } // OK
if (retBool { 1 }) { } // OK
if retBool{ 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{13-13=(x: }} {{18-18=)}}
}
if retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{13-14=(x: }} {{19-19=)}}
}
if retBool() { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{14-16=x: }} {{21-21=)}}
} else if retBool( ) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{21-24=x: }} {{29-29=)}}
}
if let _ = maybeInt { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}}
}
if let _ = maybeInt { 1 } , true { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}}
}
if let _ = foo?.map {$0+1} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{29-29=)}}
}
if let _ = foo?.map() {$0+1} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{23-25=}} {{31-31=)}}
}
if let _ = foo, retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{26-27=(x: }} {{32-32=)}}
}
if obj.meth1(x: 1) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{20-22=, }} {{27-27=)}}
}
if obj.meth2(1) { 0 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{17-19=, y: }} {{24-24=)}}
}
for _ in obj.filter {$0 > 4} { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(by: }} {{31-31=)}}
}
for _ in obj.filter {$0 > 4} where true { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(by: }} {{31-31=)}}
}
for _ in [1,2] where retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{31-32=(x: }} {{37-37=)}}
}
while retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{16-17=(x: }} {{22-22=)}}
}
while let _ = foo, retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{29-30=(x: }} {{35-35=)}}
}
switch retBool { return 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{17-18=(x: }} {{30-30=)}}
default: break
}
do {
throw MyErr.A;
} catch MyErr.A where retBool { 1 } { // expected-error {{trailing closure requires parentheses for disambiguation in this context}} {{32-33=(x: }} {{38-38=)}}
} catch { }
if let _ = maybeInt { 1 }, retBool { 1 } { }
// expected-error@-1 {{trailing closure requires parentheses for disambiguation in this context}} {{22-23=(}} {{28-28=)}}
// expected-error@-2 {{trailing closure requires parentheses for disambiguation in this context}} {{37-38=(x: }} {{43-43=)}}
}
func overloadOnLabel(a: () -> Void) {}
func overloadOnLabel(b: () -> Void) {}
func overloadOnLabel(c: () -> Void) {}
func overloadOnLabel2(a: () -> Void) {}
func overloadOnLabel2(_: () -> Void) {}
func overloadOnLabelArgs(_: Int, a: () -> Void) {}
func overloadOnLabelArgs(_: Int, b: () -> Void) {}
func overloadOnLabelArgs2(_: Int, a: () -> Void) {}
func overloadOnLabelArgs2(_: Int, _: () -> Void) {}
func overloadOnLabelDefaultArgs(x: Int = 0, a: () -> Void) {}
func overloadOnLabelDefaultArgs(x: Int = 1, b: () -> Void) {}
func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 0, a: () -> Void) {}
func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 1, b: () -> Void) {}
func overloadOnDefaultArgsOnly(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly(y: Int = 1, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly2(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly2(y: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly3(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnDefaultArgsOnly3(x: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}}
func overloadOnSomeDefaultArgsOnly(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly(_: Int, y: Int = 1, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly2(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly2(_: Int, y: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly3(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}}
func overloadOnSomeDefaultArgsOnly3(_: Int, x: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}}
func testOverloadAmbiguity() {
overloadOnLabel {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{18-19=(a: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{18-19=(b: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{18-19=(c: }} {{21-21=)}}
overloadOnLabel() {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{19-21=a: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{19-21=b: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{19-21=c: }} {{23-23=)}}
overloadOnLabel2 {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{19-20=(a: }} {{22-22=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{19-20=(}} {{22-22=)}}
overloadOnLabel2() {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{20-22=a: }} {{24-24=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{20-22=}} {{24-24=)}}
overloadOnLabelArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:a:)'}} {{24-26=, a: }} {{28-28=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:b:)'}} {{24-26=, b: }} {{28-28=)}}
overloadOnLabelArgs2(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs2(_:a:)'}} {{25-27=, a: }} {{29-29=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabelArgs2'}} {{25-27=, }} {{29-29=)}}
overloadOnLabelDefaultArgs {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{29-30=(a: }} {{32-32=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{29-30=(b: }} {{32-32=)}}
overloadOnLabelDefaultArgs() {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{30-32=a: }} {{34-34=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{30-32=b: }} {{34-34=)}}
overloadOnLabelDefaultArgs(x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{34-36=, a: }} {{38-38=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{34-36=, b: }} {{38-38=)}}
overloadOnLabelSomeDefaultArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{35-37=, a: }} {{39-39=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{35-37=, b: }} {{39-39=)}}
overloadOnLabelSomeDefaultArgs(1, x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{41-43=, a: }} {{45-45=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{41-43=, b: }} {{45-45=)}}
overloadOnLabelSomeDefaultArgs( // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{12-5=, a: }} {{4-4=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{12-5=, b: }} {{4-4=)}}
1, x: 2
) {
// some
}
overloadOnDefaultArgsOnly {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}}
overloadOnDefaultArgsOnly() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}}
overloadOnDefaultArgsOnly2 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}}
overloadOnDefaultArgsOnly2() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}}
overloadOnDefaultArgsOnly3 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}}
overloadOnDefaultArgsOnly3() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}}
overloadOnSomeDefaultArgsOnly(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly'}}
overloadOnSomeDefaultArgsOnly2(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly2'}}
overloadOnSomeDefaultArgsOnly3(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly3(_:x:a:)'}}
}
| apache-2.0 | c42552ec9b1db9930434c3720e3421ba | 58.952 | 485 | 0.665933 | 3.925616 | false | false | false | false |
UncleJoke/Spiral | Spiral/ZenHelpScene.swift | 1 | 1896 | //
// ZenHelpScene.swift
// Spiral
//
// Created by 杨萧玉 on 15/5/3.
// Copyright (c) 2015年 杨萧玉. All rights reserved.
//
import SpriteKit
class ZenHelpScene: SKScene {
func lightWithFinger(point:CGPoint){
if let light = self.childNodeWithName("light") as? SKLightNode {
light.lightColor = SKColor.whiteColor()
light.position = self.convertPointFromView(point)
}
}
func turnOffLight() {
(self.childNodeWithName("light") as? SKLightNode)?.lightColor = SKColor.brownColor()
}
func back() {
if !Data.sharedData.gameOver {
return
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { () -> Void in
Data.sharedData.currentMode = .Zen
Data.sharedData.gameOver = false
Data.sharedData.reset()
let gvc = UIApplication.sharedApplication().keyWindow?.rootViewController as! GameViewController
gvc.startRecordWithHandler { () -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if self.scene is ZenHelpScene {
gvc.addGestureRecognizers()
let scene = ZenModeScene(size: self.size)
let push = SKTransition.pushWithDirection(SKTransitionDirection.Right, duration: 1)
push.pausesIncomingScene = false
self.scene?.view?.presentScene(scene, transition: push)
}
})
}
}
}
override func didMoveToView(view: SKView) {
let bg = childNodeWithName("background") as! SKSpriteNode
let w = bg.size.width
let h = bg.size.height
let scale = max(view.frame.width/w, view.frame.height/h)
bg.xScale = scale
bg.yScale = scale
}
}
| mit | 184182de60f57e8d0fea2f3bfb657f52 | 33.851852 | 108 | 0.572264 | 4.681592 | false | false | false | false |
nervousnet/nervousnet-HUB-iOS | nervousnet-HUB-iOS/CoreLocationSensor.swift | 1 | 6260 | //
// CoreMotionSensors.swift
// nervousnet-HUB-iOS
//
// Created by Lewin Könemann on 16.03.17.
// Copyright © 2017 ETH Zurich - COSS. All rights reserved.
//
import Foundation
import XCGLogger
import CoreLocation
enum CoreLocationError : Error {
case authorizationError(CLAuthorizationStatus)
}
//This is the raw data. Apple offers some processing to remove known sources of noise, which we should discuss
@available(iOS 10.0, *)
class CoreLocationSensor : BaseSensor, CLLocationManagerDelegate {
//TODO: Move these to the VM as singletons
let locationManager = CLLocationManager()
var authorizationStatus : CLAuthorizationStatus = CLAuthorizationStatus.notDetermined
var timer : Timer = Timer.init()
let operationQueue = OperationQueue.init()
required public init (conf: BasicSensorConfiguration) {
//TODO: check if parameter Dimension is as required 3
super.init(conf: conf)
authorizationStatus = CLLocationManager.authorizationStatus()
if authorizationStatus != CLAuthorizationStatus.restricted && authorizationStatus != CLAuthorizationStatus.denied {
startListener()
}
else {
}
}
func onConfChanged (){
stopListener()
startListener()
}
//TODO: add NSLocationAlwaysUSageDescription key to Info.plist
override func startListener() -> Bool {
locationManager.delegate = self
if authorizationStatus == CLAuthorizationStatus.notDetermined{
locationManager.requestAlwaysAuthorization()
}
if authorizationStatus != CLAuthorizationStatus.restricted && authorizationStatus != CLAuthorizationStatus.denied {
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(super.configuration.samplingrate), repeats: true, block: {timer in self.locationManager.requestLocation()})
return true
}
print("failed")
return false
}
override func stopListener() -> Bool {
timer.invalidate()
return false
}
func locHandler (data : CLLocation?, time : Date, error: Error?) -> Void {
//log.debug(data.debugDescription)
// let timestamp = Int64(time.timeIntervalSince1970 * 1000)
let timestamp = Int64(Date().timeIntervalSince1970 * 1000)
if data != nil {
let lat = data!.coordinate.latitude
let long = data!.coordinate.longitude
let speed = data!.speed
// print(lat, long, speed)
do {
let sensorReading = try SensorReading(config: super.configuration, values: [lat, long, speed], timestamp: timestamp)
super.push(reading: sensorReading)
if let navController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController{
if let visualizer = navController.visibleViewController as? SensorStatisticsViewController{
DispatchQueue.main.async {
visualizer.updateGraph(sensorReading: sensorReading)
}
}
}
} catch _ {
log.error("This should not happen. 'values' count does not match param dimension. Pushing empty 'SensorReading'")
super.push(reading: SensorReading(config: super.configuration, timestamp: timestamp))
}
}
else {
super.push(reading: SensorReading(config: super.configuration, timestamp: timestamp))
}
}
//Delegate
func locationManager (didupdateLocations : [CLLocation]){
print("wtf is this?")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
locHandler(data: location, time : location.timestamp, error: nil)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locHandler(data: nil, time: Date.init(), error: error)
}
func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) {
}
func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager, didUPdateTo: CLLocation, from: CLLocation) {
}
func locationManagerDidPauseLocationUpdates(_ manager: CLLocationManager) {
}
func locationManagerDidResumeLocationUpdates(_ manager: CLLocationManager) {
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
}
func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool {
return false
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
}
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
}
func locationManager (_manager: CLLocationManager, didDetermineState: CLRegionState, for: CLRegion){
}
func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
}
func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
}
func locationManager(_ manager: CLLocationManager, rangingBeaconsDidFailFor region: CLBeaconRegion, withError error: Error) {
}
func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
}
}
| gpl-3.0 | 31f327c0b14255052c9f7ce2fd9e2b6e | 30.928571 | 179 | 0.645733 | 5.815985 | false | false | false | false |
genedelisa/PlayerNodePlayground | playernodePlayground.playground/Contents.swift | 1 | 2700 |
/*:
# AVAudioPlayerNode
How to read a sound file, add effects, and play the damn thing.
*/
import AVFoundation
import PlaygroundSupport
//: Create the angine
let engine = AVAudioEngine()
//: Create a few effects
let delay = AVAudioUnitDelay()
delay.delayTime = 2
delay.feedback = 50
delay.lowPassCutoff = 15000
delay.wetDryMix = 100
let reverb = AVAudioUnitReverb()
reverb.loadFactoryPreset(.cathedral)
reverb.wetDryMix = 50
var timePitch = AVAudioUnitTimePitch()
timePitch.pitch = 100 // cents
timePitch.rate = 2
//: Finally, create the star of the show
let player = AVAudioPlayerNode()
//: Now we have 3 nodes. Attach them to the engine to use them. The order doesn't matter here.
engine.attach(player)
engine.attach(delay)
engine.attach(reverb)
engine.attach(timePitch)
//: Read the sound file. It's in the Resources folder.
// mp3 seems to hang
// guard let audioFileURL = Bundle.main.url(forResource: "jfk", withExtension: "mp3") else {
// wav works
guard let audioFileURL = Bundle.main.url(forResource: "snare-analog", withExtension: "wav") else {
fatalError("audio file is not in bundle.")
}
var audioFile: AVAudioFile?
do {
audioFile = try AVAudioFile(forReading: audioFileURL)
} catch {
fatalError("canot create AVAudioFile \(error)")
}
//: If this fails, you messed up. Is the sound file there?
if let soundFile = audioFile {
//: Now create the "graph". You can have fun here trying different connections.
let format = soundFile.processingFormat
engine.connect(player, to: delay, format: format)
engine.connect(delay, to: reverb, format: format)
engine.connect(reverb, to: engine.mainMixerNode, format: format)
//: macOS doesn't have an audio session, so do this check.
#if os(iOS) || os(watchOS) || os(tvOS)
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSession.Category.playback)
try session.overrideOutputAudioPort(.speaker)
try session.setActive(true)
} catch {
fatalError("cannot create/set session \(error)")
}
#endif
//: Start your engines!
do {
try engine.start()
} catch {
fatalError("Could not start engine. error: \(error).")
}
//: Now play it! See the docs for the time thing. nil means "now".
let when: AVAudioTime? = nil
player.scheduleFile(soundFile, at: when) {
print("scheduled now")
// just for fun
player.rate = 0.5
player.play()
}
//: or just play
// player.play()
}
//: you might not hear anything if you don't do this. You'll have to hit the stop button.
PlaygroundPage.current.needsIndefiniteExecution = true
| mit | 94146b885fcfac9baad5a3b8720a55f5 | 27.125 | 98 | 0.685556 | 3.988183 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift | 1 | 11146 | /**
* Copyright IBM Corporation 2018
*
* 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
/**
Analyze various features of text content at scale. Provide text, raw HTML, or a public URL, and IBM Watson Natural
Language Understanding will give you results for the features you request. The service cleans HTML content before
analysis by default, so the results can ignore most advertisements and other unwanted content.
You can create <a target="_blank"
href="https://www.ibm.com/watson/developercloud/doc/natural-language-understanding/customizing.html">custom models</a>
with Watson Knowledge Studio that can be used to detect custom entities and relations in Natural Language
Understanding.
*/
public class NaturalLanguageUnderstanding {
/// The base URL to use when contacting the service.
public var serviceURL = "https://gateway.watsonplatform.net/natural-language-understanding/api"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
private let credentials: Credentials
private let domain = "com.ibm.watson.developer-cloud.NaturalLanguageUnderstandingV1"
private let version: String
/**
Create a `NaturalLanguageUnderstanding` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
- parameter version: The release date of the version of the API to use. Specify the date
in "YYYY-MM-DD" format.
*/
public init(username: String, password: String, version: String) {
self.credentials = .basicAuthentication(username: username, password: password)
self.version = version
}
/**
If the response or data represents an error returned by the Natural Language Understanding service,
then return NSError with information about the error that occured. Otherwise, return nil.
- parameter response: the URL response returned from the service.
- parameter data: Raw data returned from the service that may represent an error.
*/
private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? {
// First check http status code in response
if let response = response {
if (200..<300).contains(response.statusCode) {
return nil
}
}
// ensure data is not nil
guard let data = data else {
if let code = response?.statusCode {
return NSError(domain: domain, code: code, userInfo: nil)
}
return nil // RestKit will generate error for this case
}
let code = response?.statusCode ?? 400
do {
let json = try JSONWrapper(data: data)
let message = try json.getString(at: "error")
var userInfo = [NSLocalizedDescriptionKey: message]
if let description = try? json.getString(at: "description") {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = description
}
return NSError(domain: domain, code: code, userInfo: userInfo)
} catch {
return NSError(domain: domain, code: code, userInfo: nil)
}
}
/**
Analyze text, HTML, or a public webpage.
Analyzes text, HTML, or a public webpage with one or more text analysis features. ### Concepts Identify general
concepts that are referenced or alluded to in your content. Concepts that are detected typically have an associated
link to a DBpedia resource. ### Emotion Detect anger, disgust, fear, joy, or sadness that is conveyed by your
content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases
found in the text. ### Entities Detect important people, places, geopolitical entities and other types of entities
in your content. Entity detection recognizes consecutive coreferences of each entity. For example, analysis of the
following text would count \"Barack Obama\" and \"He\" as the same entity: \"Barack Obama was the 44th President
of the United States. He took office in January 2009.\" ### Keywords Determine the most important keywords in your
content. Keyword phrases are organized by relevance in the results. ### Metadata Get author information,
publication date, and the title of your text/HTML content. ### Relations Recognize when two entities are related,
and identify the type of relation. For example, you can identify an \"awardedTo\" relation between an award and
its recipient. ### Semantic Roles Parse sentences into subject-action-object form, and identify entities and
keywords that are subjects or objects of an action. ### Sentiment Determine whether your content conveys postive
or negative sentiment. Sentiment information can be returned for detected entities, keywords, or user-specified
target phrases found in the text. ### Categories Categorize your content into a hierarchical 5-level taxonomy.
For example, \"Leonardo DiCaprio won an Oscar\" returns \"/art and entertainment/movies and tv/movies\" as the most
confident classification.
- parameter parameters: An object containing request parameters. The `features` object and one of the `text`, `html`, or `url` attributes
are required.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func analyze(
parameters: Parameters,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (AnalysisResults) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(parameters) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v1/analyze",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<AnalysisResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
List models.
Lists available models for Relations and Entities features, including Watson Knowledge Studio custom models that
you have created and linked to your Natural Language Understanding service.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listModels(
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (ListModelsResults) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let request = RestRequest(
method: "GET",
url: serviceURL + "/v1/models",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<ListModelsResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete model.
Deletes a custom model.
- parameter modelID: model_id of the model to delete.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteModel(
modelID: String,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (DeleteModelResults) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<DeleteModelResults>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
}
| mit | a10b78c209012319cde9bf5c26ece6b5 | 42.20155 | 142 | 0.664543 | 5.098811 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/QueryNoticesResponse.swift | 1 | 1269 | /**
* Copyright IBM Corporation 2018
*
* 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
/** QueryNoticesResponse. */
public struct QueryNoticesResponse: Decodable {
public var matchingResults: Int?
public var results: [QueryNoticesResult]?
public var aggregations: [QueryAggregation]?
public var passages: [QueryPassages]?
public var duplicatesRemoved: Int?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case matchingResults = "matching_results"
case results = "results"
case aggregations = "aggregations"
case passages = "passages"
case duplicatesRemoved = "duplicates_removed"
}
}
| mit | 0d48366282a4b96a8a403221e358401f | 29.95122 | 82 | 0.718676 | 4.391003 | false | false | false | false |
mannie/Smart-Organise | Organise By Date/Organise By Date/OrganiseByDate.swift | 1 | 872 | //
// OrganiseByDate.swift
// Organise By Date
//
// Created by Mannie Tagarira on 10/06/2015.
// Copyright (c) 2015 Mannie Tagarira. All rights reserved.
//
import Automator
import TAGToolbox
class OrganiseByDate: AMBundleAction {
override func runWithInput(input: AnyObject?) throws -> AnyObject {
let inputFilePaths = Set<String>(input as! Array<String>)
var outputFilePaths = Set<String>()
let date = NSDate()
let fileManager = NSFileManager.defaultManager()
for sourcePath in inputFilePaths {
if let organisedItem = fileManager.organiseItemAtPath(sourcePath, withDate: date) {
outputFilePaths.insert(organisedItem)
}
}
deliverUserNotification(Array<String>(outputFilePaths))
return outputFilePaths
}
}
| bsd-3-clause | c646048f5706e85a23511436395bccf0 | 25.424242 | 95 | 0.636468 | 4.613757 | false | false | false | false |
sochalewski/TinySwift | TinySwift/UIView.swift | 1 | 1278 | //
// UIView.swift
// TinySwift
//
// Created by Piotr Sochalewski on 19.10.2016.
// Copyright © 2016 Piotr Sochalewski. All rights reserved.
//
#if !os(watchOS)
import UIKit
public extension UIView {
/**
Returns a view instantiated from the nib/xib corresponding to the view.
For example a snippet for `MyView.xib`:
class MyView: UIView {
private(set) var view: UIView?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
fileprivate func setup() {
view = viewFromNib
guard let view = view else { return }
addSubview(view)
}
}
*/
var viewFromNib: UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as? UIView
view?.frame = bounds
view?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return view
}
}
#endif
| mit | 513c1e61fd363151af9fa730fe987309 | 28.697674 | 88 | 0.495693 | 4.949612 | false | false | false | false |
naokits/my-programming-marathon | JunkCodes/DebuggingOrNot.swift | 1 | 793 |
/// デバッガを使用中かどうかを返す
/// [ios - Detect if Swift app is being run from Xcode - Stack Overflow](http://stackoverflow.com/questions/33177182/detect-if-swift-app-is-being-run-from-xcode/33177600#33177600)
func amIBeingDebugged() -> Bool {
var info = kinfo_proc()
var mib : [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
var size = strideofValue(info)
let junk = sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0)
assert(junk == 0, "sysctl failed")
return (info.kp_proc.p_flag & P_TRACED) != 0
}
/// 利用する側
func hoge() {
if amIBeingDebugged() {
print("デバッグ中")
} else {
print("デバッグ中ではない")
}
}
| mit | d86485535c274535dfb53a0c8b7d40fd | 33.52381 | 183 | 0.571034 | 3.046218 | false | false | false | false |
multinerd/Mia | Mia/Libraries/Rosewood/Rosewood+Benchmark.swift | 1 | 4419 | // MARK: -
extension Rosewood {
public struct Benchmark {
}
}
// MARK: -
extension Rosewood.Benchmark {
public typealias BenchmarkBlock = () -> Void
// MARK: Public Methods
/// Calls a set of code the specified number of times, returning the average in the form of a dictionary.
///
/// - Parameters:
/// - name: The benchmark name.
/// - iterations: The number of times to run code
/// - block: The code to run
/// - Returns: Returns a dictionary with the time for each run.
@discardableResult
public static func task(_ name: String, iterations: Int = 1, block: BenchmarkBlock) -> [String: Double] {
guard Rosewood.Configuration.enabled else { return [:] }
precondition(iterations > 0, "Iterations must be a positive integer")
var data: [String: Double] = [:]
var total: Double = 0
var samples = [ Double ]()
Rosewood.printToDebugger("\n🖤Measure \(name)")
if iterations == 1 {
let took = benchmark(name, forBlock: block).first!
samples.append(took.value)
total += took.value
data["1"] = took.value
} else {
for i in 0..<iterations {
let took = benchmark("Iteration \(i + 1)", forBlock: block).first!
samples.append(took.value)
total += took.value
data["\(i + 1)"] = took.value
}
let average = total / Double(iterations)
var deviation = 0.0
for result in samples {
let difference = result - average
deviation += difference * difference
}
let variance = deviation / Double(iterations)
Rosewood.printToDebugger("🖤\t- Total: \(total.millisecondString)")
Rosewood.printToDebugger("🖤\t- Average: \(average.millisecondString)")
Rosewood.printToDebugger("🖤\t- STD Dev: \(variance.millisecondString)")
}
return data
}
/// Prints a message with an optional timestamp from start of measurement.
///
/// - Parameters:
/// - message: The message to log.
/// - includeTimeStamp: Bool value to show time.
public static func log(message: String, includeTimeStamp: Bool = false) {
reportContaining()
if includeTimeStamp {
let currentTime = now
let timeStamp = currentTime - timingStack[timingStack.count - 1].startTime
Rosewood.printToDebugger("🖤\(depthIndent)\(message) \(timeStamp.millisecondString)")
} else {
Rosewood.printToDebugger("🖤\(depthIndent)\(message)")
}
}
// MARK: Private Methods
private static func benchmark(_ name: String, forBlock block: BenchmarkBlock) -> [String: Double] {
startBenchmark(name)
block()
return stopBenchmark()
}
private static func startBenchmark(_ name: String) {
reportContaining()
timingStack.append((now, name, false))
depth += 1
}
private static func stopBenchmark() -> [String: Double] {
let endTime = now
precondition(depth > 0, "Attempt to stop a measurement when none has been started")
let beginning = timingStack.removeLast()
depth -= 1
let took = endTime - beginning.startTime
let log = "🖤\(depthIndent)\(beginning.name): \(took.millisecondString)"
Rosewood.printToDebugger(log)
return [ log: took ]
}
private static func reportContaining() {
if depth > 0 && Rosewood.Configuration.enabled {
for stackPointer in 0..<timingStack.count {
let containingMeasurement = timingStack[stackPointer]
if !containingMeasurement.reported {
print(String(repeating: "\t" + "Measuring \(containingMeasurement.name):", count: stackPointer))
timingStack[stackPointer] = (containingMeasurement.startTime, containingMeasurement.name, true)
}
}
}
}
}
private var depth = 0
private var logs = [ String ]()
private var timingStack = [ (startTime: Double, name: String, reported: Bool) ]()
private var now: Double {
return Date().timeIntervalSinceReferenceDate
}
private var depthIndent: String {
return String(repeating: "\t", count: depth)
}
| mit | e7c2fe741f5f88adc1245abb83b7a76a | 28.918367 | 116 | 0.593452 | 4.658898 | false | false | false | false |
zzeleznick/piazza-clone | Pizzazz/Pizzazz/CourseInfoViewController.swift | 1 | 4742 | //
// CourseInfoViewController.swift
// Pizzazz
//
// Created by Zach Zeleznick on 5/6/16.
// Copyright © 2016 zzeleznick. All rights reserved.
//
import UIKit
class CourseInfoViewController: ViewController {
var tableView: UITableView!
typealias CellType = ClassViewCell
fileprivate struct Main {
static let CellIdentifier = "cell"
static let CellClass = CellType.self
}
typealias InfoCellType = ClassInfoViewCell
fileprivate struct Info {
static let CellIdentifier = "infoCell"
static let CellClass = InfoCellType.self
}
typealias SecondaryCellType = StaffViewCell
fileprivate struct Secondary {
static let CellIdentifier = "staffCell"
static let CellClass = SecondaryCellType.self
}
let sections = ["Course Information", "General Information", "Staff",] //"Resources"]
var dummyTitle: String! = "Class 0"
var dummySubtitle: String! = "Description Class 0"
let dummyText = "University of Drumpf, Main Campus (America, United States of), Spring 2016"
let info = ["This is a class description", "This is a second line about the class"]
let staffNames = ["John Dermot", "Brianna Radnovich", "Nikolas Thomas",
"Sarah Beekman", "Diana Marshall"]
override func addToolbar() {
let toolbar = UIToolbar()
toolbar.barTintColor = UIColor(white: 0.95, alpha: 1.0)
view.addUIElement(toolbar, frame: CGRect(x: 0, y: h-40, width: w, height: 40))
}
func composeButtonPressed() {
let dest = NewQuestionViewController()
navigationController?.pushViewController(dest, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: CGRect(x: 0, y: 0, width: w, height: h-50))
tableView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
tableView.dataSource = self
tableView.delegate = self
tableView.register(Main.CellClass,
forCellReuseIdentifier: Main.CellIdentifier)
tableView.register(Info.CellClass,
forCellReuseIdentifier: Info.CellIdentifier)
tableView.register(Secondary.CellClass,
forCellReuseIdentifier: Secondary.CellIdentifier)
tableView.rowHeight = 90
view.addSubview(tableView)
addToolbar()
}
}
extension CourseInfoViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 32
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = (indexPath as NSIndexPath).section
if section == 1{
return 80
}
else if section == 2 {
return 120
}
return 100
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = HeaderViewCell()
let text = sections[section]
headerView.titleLabel.text = text
return headerView
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = (indexPath as NSIndexPath).section
if section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: Info.CellIdentifier, for: indexPath) as! InfoCellType
cell.selectionStyle = .none
cell.lines = info
return cell
}
else if section == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: Secondary.CellIdentifier, for: indexPath) as! SecondaryCellType
cell.selectionStyle = .none
cell.names = staffNames
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: Main.CellIdentifier, for: indexPath) as! CellType
cell.selectionStyle = .none
cell.titleLabel.text = dummyTitle
cell.subtitleLabel.text = dummySubtitle
cell.bodyLabel.text = dummyText
cell.hideSettings()
return cell
}
}
}
| mit | ae09ea59843680fe6ed1b461896b91c1 | 35.751938 | 136 | 0.622443 | 5.215622 | false | false | false | false |
TabletopAssistant/DiceKit | TomeOfKnowledge.playground/Pages/Exploring Expressions.xcplaygroundpage/Contents.swift | 1 | 3722 | //: ## Exploring Expressions
//:
//: Our expressions are more robust than what is needed for typical tabletop play. In fact, our generic expression system is capable of modeling expressions that would otherwise be considered too cumbersome or complex to physically roll. In order to help developers understand what their expressions actually represent, we have added various tools to make working with expressions as easy as possible.
import DiceKit
//: Lets start with the negative-sided die.
let negativeDie = d(-12)
//: A die with negative sides by default has results in the range `-sides...-1` (but you can assign different rollers to `Die.roller`). We have two ways to represent an expression as a string.
//: * `normalString` is the string returned from `negativeDie.description`. Our descriptions are intended to be readable and closely match regular dice notation. This also happens to be the text that playgrounds display to the right.
//: * `verboseString` is what is returned from `negativeDie.debugDescription`. These strings tend to do less to make the result readable, and are intended to show exactly what types are used.
let normalString = String(negativeDie)
let verboseString = String(reflecting: negativeDie)
//: When we look at the `description` of a die roll, we seperate the rolled value from the total number of sides with a |. So a d6 that rolled a 3 would be written as 3|6. Or with our special negative die:
let negativeResult = negativeDie.roll()
//: Multiplication expressions are particularly interesting to look at. We will make one multiplication expression and see what happens when we make a third multiplication expression from the first one and a die.
let oneD2 = 1 * d(2)
let d3 = d(3)
//: `oneD2` is of the type `MultiplicationExpression<Constant, Die>` because it is made by multiplying a `Consant` (the expression type `Int` is converted to) by a `Die`.
oneD2 is MultiplicationExpression<Constant, Die>
//: We can make a new multiplication expression with these two expressions. This expression works like a "normal" multiplication expression, but the multiplier is 1 half the time, and 2 the other half of the time.
let oneD2d3 = oneD2 * d3
//: When we `evaluate()` a multiplication expression, we can see what each side of the expression evaluated to. First, an easy case. This result type has a `.multiplierResult` and `.multiplicandResults`. The multiplier is always 2, because it is a constant. The multiplicand is evaluated and summed n number of times to give the result, where n is the multiplier result. We seperate the multiplier and multiplicand with the symbol `*>` in the description, which says that the result of the left hand side is the length of the right hand side.
let twoD20 = 2 * d(20)
let twoD20result = twoD20.evaluate()
//: Now lets evaluate our compound multiplication expression. The leftmost term is the multiplier for 1d2. It must always be 1. The middle term is either a 1|2 or a 2|2, depending on what the d2 rolled. Finally, the rightmost term is either a single d3 roll or the sum of two d3 rolls, depending on what the d2 rolled.
let oneD2d3result = oneD2d3.evaluate()
//: The result of the expression is always the sum of the rightmost term.
let value = oneD2d3result.resultValue
//: Try making more expressions in this playground. There is no limitation on what expression types you can put together to make a new expression. If your expression gets too complicated to easily tell its type, use the `dump()` function to investigate it in the console window.
let whatIsThisExpression = d3 * (d(20) - 2)
dump(whatIsThisExpression) //Check out the debug area for a handy expression tree! :)
//: [Previous](@previous)
//: [Next](@next)
| apache-2.0 | b3189cfddce0c83593f0737fda41b041 | 83.590909 | 543 | 0.771628 | 4.224745 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Tests/pinkNoiseTests.swift | 1 | 1086 | //
// pinkNoiseTests.swift
// AudioKit
//
// Created by Aurelius Prochazka on 8/9/16.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
import AudioKit
import XCTest
class PinkNoiseTests: AKTestCase {
override func setUp() {
super.setUp()
duration = 1.0
}
func testDefault() {
output = AKOperationGenerator { _ in
return AKOperation.pinkNoise()
}
AKTestMD5("ddf3ff7735d85181d93abd7655b9658b")
}
func testAmplitude() {
output = AKOperationGenerator { _ in
return AKOperation.pinkNoise(amplitude: 0.456)
}
AKTestMD5("225013a98880fabae9333b4b281dfbbe")
}
func testParameterSweep() {
output = AKOperationGenerator { _ in
let line = AKOperation.lineSegment(
trigger: AKOperation.metronome(),
start: 0,
end: 1,
duration: self.duration)
return AKOperation.pinkNoise(amplitude: line)
}
AKTestMD5("a3ff6fe8636bee3dadad539a2448226f")
}
}
| mit | 6f0cd068af51fc7448e3dd4f0ae61abe | 23.111111 | 61 | 0.598157 | 4.157088 | false | true | false | false |
nadejdanicolova/ios-project | Wallpapers/Wallpapers/ViewControllers/SearchViewController.swift | 1 | 4121 | import UIKit
class SearchViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, HttpRequesterDelegate{
let reuseIdentifier = "Search Cell"
var searchedQuery : String = ""
var images : [Image] = []
var handle: Timer?
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var collectionView: UICollectionView!
var url: String {
get{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let a = "\(appDelegate.baseUrl)&q=\(searchedQuery)"
print(a)
return a
}
}
var http: HttpRequester? {
get{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.http
}
}
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "ImageCollectionCell", bundle: nil)
self.collectionView.register(cellNib, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.searchBar.delegate = self
self.http?.delegate = self
// Do any additional setup after loading the view.
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let query = searchBar.text?.lowercased()
handle?.invalidate()
if((query?.characters.count)! > 3) {
handle = setTimeout(delay: 1, block: {
self.searchedQuery = query!.replacingOccurrences(of: " ", with: "+")
self.http?.get(fromUrl: self.url)
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didReceiveData(data: Any) {
let dataArray = data as! [Dictionary<String, Any>]
self.images = dataArray.map(){Image(withDict: $0)}
DispatchQueue.main.async{
self.collectionView?.reloadData()
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionCell
let imageUrl = self.images[indexPath.row].previewUrl
let url = URL(string: imageUrl!)
cell.image.kf.setImage(with: url)
cell.likesCount.text = "\(self.images[indexPath.row].likes!)"
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let imageId = "\(self.images[indexPath.row].id!)"
let nextVC = UIStoryboard(name: "Main" , bundle: nil).instantiateViewController(withIdentifier: "imagePreviewViewController") as! ImagePreviewViewController
nextVC.imageId = imageId
self.show(nextVC, sender: self)
}
//-prehvurlqne-
func setTimeout(delay:TimeInterval, block:@escaping ()->Void) -> Timer {
return Timer.scheduledTimer(timeInterval: delay, target: BlockOperation(block: block), selector: #selector(Operation.main), userInfo: nil, repeats: false)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 5da7f0c39d5582b945341b7e0b61e748 | 32.233871 | 164 | 0.621451 | 5.465517 | false | false | false | false |
finder39/Swimgur | SWNetworking/Models/Token.swift | 1 | 1827 | //
// Token.swift
// Swimgur
//
// Created by Joseph Neuman on 8/8/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import Foundation
private let tokenAccessTokenKey = "access_token";
private let tokenAccountUsernameKey = "account_username";
private let tokenExpiresInKey = "expires_in";
private let tokenRefreshTokenKey = "refresh_token";
private let tokenScopeKey = "scope";
private let tokenTokenTypeKey = "token_type";
public class Token {
public var accessToken: String?
public var accountUsername: String?
public var expiresIn: UInt?
public var refreshToken: String?
public var scope: String?
public var tokenType: String?
public init(dictionary:Dictionary<String, AnyObject>) {
accessToken = dictionary[tokenAccessTokenKey] as AnyObject? as String?
accountUsername = dictionary[tokenAccountUsernameKey] as AnyObject? as String?
expiresIn = dictionary[tokenExpiresInKey] as AnyObject? as UInt?
refreshToken = dictionary[tokenRefreshTokenKey] as AnyObject? as String?
scope = dictionary[tokenScopeKey] as AnyObject? as? String
tokenType = dictionary[tokenTokenTypeKey] as AnyObject? as String?
}
public func asDictionary() -> Dictionary<String, AnyObject> {
var dictionary:Dictionary<String, AnyObject> = Dictionary()
if let accessToken = accessToken { dictionary[tokenAccessTokenKey] = accessToken }
if let accountUsername = accountUsername { dictionary[tokenAccountUsernameKey] = accountUsername }
if let expiresIn = expiresIn { dictionary[tokenExpiresInKey] = expiresIn }
if let refreshToken = refreshToken { dictionary[tokenRefreshTokenKey] = refreshToken }
if let scope = scope { dictionary[tokenScopeKey] = scope }
if let tokenType = tokenType { dictionary[tokenTokenTypeKey] = tokenType }
return dictionary
}
} | mit | 43ffdfac2f71993963c70c2e8a393a5d | 39.622222 | 102 | 0.754242 | 4.456098 | false | false | false | false |
zbamstudio/DonutChart | Source/AnimationLayer.swift | 1 | 1795 | /*
MIT License
Copyright (c) [2017] [Emrah Ozer / Zbam Studio]
*/
import QuartzCore
class AnimationLayer: CALayer
{
@NSManaged var progress: CGFloat
@NSManaged var progressColor: CGColor
@NSManaged var outlineColor: CGColor
@NSManaged var textColor: CGColor
@NSManaged var radius: CGFloat
@NSManaged var thickness: CGFloat
@NSManaged var outlineWidth: CGFloat
override init() {
super.init()
}
override init(layer: Any) {
super.init(layer: layer)
if let layer = layer as? AnimationLayer {
progress = layer.progress
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate class func isCustomAnimKey(_ key: String) -> Bool {
let keys = ["progress","progressColor","outlineColor","textColor","radius","thickness","outlineWidth"]
return try keys.contains(key)
}
override class func needsDisplay(forKey key: String) -> Bool {
if self.isCustomAnimKey(key) {
return true
}
return super.needsDisplay(forKey: key)
}
override func action(forKey event: String) -> CAAction? {
if AnimationLayer.isCustomAnimKey(event) {
// get duration and timing of the uiview animation
if let animation = super.action(forKey: "backgroundColor") as? CABasicAnimation {
animation.keyPath = event
if let pLayer = presentation() {
animation.fromValue = pLayer.value(forKey: event)
}
animation.toValue = nil
return animation
}
setNeedsDisplay()
return nil
}
return super.action(forKey: event)
}
}
| mit | 5f7a36c1bef6d147f5817747743e48cb | 25.397059 | 110 | 0.594986 | 4.851351 | false | false | false | false |
FasaMo/CodeStackView | Demo/CodeStackViewDemo/CodeStackViewDemo/ViewController.swift | 1 | 3688 | //
// ViewController.swift
// CodeStackViewDemo
//
// Created by Fasa Mo on 15/9/14.
// Copyright © 2015年 FasaMo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var didSetupConstraints = false
var photoStackView = UIStackView(axis: .Vertical, distribution: .FillEqually)
var infoStackView = UIStackView(axis: .Vertical, alignment: .Leading, spacing: 0)
var infoTopStackView = UIStackView(axis: .Horizontal, alignment: .FirstBaseline, spacing: 20)
var infoButtonsStackView = UIStackView(axis: .Horizontal, spacing: 5)
let images = ["nature-1", "nature-2", "nature-3"]
let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.text = "Nature"
titleLabel.font = UIFont.systemFontOfSize(30)
return titleLabel
}()
let descLabel: UILabel = {
let descLabel = UILabel()
descLabel.text = "A collection of nature photos from magdeleine.co"
descLabel.numberOfLines = 0
return descLabel
}()
let likeButton: UIButton = {
let likeButton = UIButton()
likeButton.setTitle("Like", forState: .Normal)
likeButton.setTitleColor(.redColor(), forState: .Normal)
return likeButton
}()
let shareButton: UIButton = {
let shareButton = UIButton()
shareButton.setTitle("Share", forState: .Normal)
shareButton.setTitleColor(.redColor(), forState: .Normal)
return shareButton
}()
}
// MARK: LifeCircle
extension ViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Add Subviews
infoButtonsStackView.addArrangedSubview(self.likeButton)
infoButtonsStackView.addArrangedSubview(self.shareButton)
infoTopStackView.addArrangedSubview(titleLabel)
infoTopStackView.addArrangedSubview(infoButtonsStackView)
infoStackView.addArrangedSubview(infoTopStackView)
infoStackView.addArrangedSubview(descLabel)
view.addSubview(infoStackView)
for imageName in self.images {
let imageView = UIImageView()
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = UIImage(named: imageName)
photoStackView.addArrangedSubview(imageView)
}
view.addSubview(photoStackView)
// Trigger
view.setNeedsUpdateConstraints()
}
}
// MARK: UpdateViewConstraints
extension ViewController {
override func updateViewConstraints() {
if !didSetupConstraints {
let padding = CGFloat(8.0)
view.addConstraint(photoStackView.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 20))
view.addConstraint(photoStackView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: padding * 2))
view.addConstraint(photoStackView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant: -padding * 2))
view.addConstraint(photoStackView.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: 0.7))
view.addConstraint(infoStackView.topAnchor.constraintEqualToAnchor(photoStackView.bottomAnchor, constant: padding))
view.addConstraint(infoStackView.leadingAnchor.constraintEqualToAnchor(photoStackView.leadingAnchor))
view.addConstraint(infoStackView.trailingAnchor.constraintEqualToAnchor(photoStackView.trailingAnchor))
didSetupConstraints = true
}
super.updateViewConstraints()
}
} | mit | 9ab29dcb7cc1dfa86edb41c41f00e66b | 34.442308 | 131 | 0.672456 | 5.443131 | false | false | false | false |
jonybur/asdk-networkimagecollection | Sample/BSWaterfallViewCell.swift | 1 | 1046 | //
// BSWaterfallViewCell.swift
// Sample
//
// Created by Jonathan Bursztyn on 1/10/17.
// Copyright © 2017 Jonathan Bursztyn. All rights reserved.
//
import UIKit
import AsyncDisplayKit
import Foundation
class BSWaterfallViewCell: ASCellNode {
let _imageNode : ASNetworkImageNode = ASNetworkImageNode()
var _picture : Picture!
required init(with picture : Picture) {
super.init()
_imageNode.setURL(URL(string: picture.url), resetToDefault: false)
_imageNode.shouldRenderProgressImages = true
_picture = picture
self.addSubnode(self._imageNode)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let imagePlace = ASRatioLayoutSpec(ratio: self._picture.ratio.height, child: _imageNode)
let stackLayout = ASStackLayoutSpec.vertical()
stackLayout.justifyContent = .start
stackLayout.alignItems = .start
stackLayout.style.flexShrink = 1.0
stackLayout.children = [imagePlace]
return ASInsetLayoutSpec(insets: UIEdgeInsets.zero, child: stackLayout)
}
}
| mit | ab92582041168f0727f11c2072f9f2d7 | 25.125 | 90 | 0.745455 | 3.899254 | false | false | false | false |
GenerallyHelpfulSoftware/Scalar2D | Utils/Sources/Parsing.swift | 1 | 3137 | //
// Parsing.swift
// Scalar2D
//
// Created by Glenn Howes on 11/2/17.
// Copyright © 2017-2019 Generally Helpful Software. All rights reserved.
//
//
// The MIT License (MIT)
// Copyright (c) 2016-2019 Generally Helpful Software
// 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 protocol ParseBufferError : Error
{
var failurePoint : String.UnicodeScalarView.Index?{get}
}
public extension ParseBufferError
{
func description(forBuffer buffer: String.UnicodeScalarView) -> String
{
guard let failurePoint = self.failurePoint else
{
return self.localizedDescription
}
let lineCount = buffer.lineCount(before: failurePoint)
let lineCountString = "Failure at line: \(lineCount+1)"
var beginCursor = failurePoint
var endCursor = failurePoint
let validRange = buffer.startIndex..<buffer.endIndex
var rangeCount = 10 // arbitrary
while rangeCount >= 0
{
let newBegin = buffer.index(before: beginCursor)
if validRange.contains(newBegin)
{
beginCursor = newBegin
}
let newEnd = buffer.index(after: endCursor)
if validRange.contains(newEnd)
{
endCursor = newEnd
}
rangeCount -= 1
}
let rangeString = String(buffer[beginCursor...endCursor])
return lineCountString + "\n" + ">>> \(rangeString) <<<<\n" + self.localizedDescription
}
}
extension String.UnicodeScalarView
{
public func lineCount(before: String.UnicodeScalarView.Index) -> Int
{
var result = 0
var cursor = self.startIndex
let range = cursor..<before
while range.contains(cursor) {
let character = self[cursor]
if character == "\n"
{
result += 1
}
cursor = self.index(after: cursor)
}
return result
}
}
| mit | 8e8383e5e488f25369f047f57e2b2a85 | 30.676768 | 95 | 0.632653 | 4.673621 | false | false | false | false |
kcome/SwiftIB | SwiftIB/ScannerSubscription.swift | 1 | 2132 | //
// ScannerSubscription.swift
// SwiftIB
//
// Created by Hanfei Li on 1/01/2015.
// Copyright (c) 2014-2019 Hanfei Li. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to
// do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
public struct ScannerSubscription {
let NO_ROW_NUMBER_SPECIFIED = -1
var numberOfRows: Int = -1
var instrument: String = ""
var locationCode: String = ""
var scanCode: String = ""
var abovePrice: Double = Double.nan
var belowPrice: Double = Double.nan
var aboveVolume: Int = Int.max
var averageOptionVolumeAbove: Int = Int.max
var marketCapAbove: Double = Double.nan
var marketCapBelow: Double = Double.nan
var moodyRatingAbove: String = ""
var moodyRatingBelow: String = ""
var spRatingAbove: String = ""
var spRatingBelow: String = ""
var maturityDateAbove: String = ""
var maturityDateBelow: String = ""
var couponRateAbove: Double = Double.nan
var couponRateBelow: Double = Double.nan
var excludeConvertible: String = ""
var scannerSettingPairs: String = ""
var stockTypeFilter: String = ""
}
| mit | b08d33b20547943b766fd94d80d212a4 | 40 | 84 | 0.723734 | 4.205128 | false | false | false | false |
TheInfiniteKind/duckduckgo-iOS | DuckDuckGo/OmniBar.swift | 1 | 4336 | //
// OmniBar.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 17/02/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import UIKit
import Core
extension OmniBar: NibLoading {}
class OmniBar: UIView {
public enum Style: String {
case home = "OmniBarHome"
case web = "OmniBarWeb"
}
var style: Style!
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var refreshButton: UIButton?
@IBOutlet weak var dismissButton: UIButton!
@IBOutlet weak var textField: UITextField!
weak var omniDelegate: OmniBarDelegate?
static func loadFromXib(withStyle style: Style) -> OmniBar {
let omniBar = OmniBar.load(nibName: style.rawValue)
omniBar.style = style
return omniBar
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
configureTextField()
}
private func configureTextField() {
textField.placeholder = UserText.searchDuckDuckGo
textField.delegate = self
}
@discardableResult override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
@discardableResult override func resignFirstResponder() -> Bool {
return textField.resignFirstResponder()
}
func clear() {
textField.text = nil
}
func refreshText(forUrl url: URL?) {
guard let url = url else {
textField.text = nil
return
}
if let query = AppUrls.searchQuery(fromUrl: url) {
textField.text = URL.decode(query: query)
return
}
if AppUrls.isDuckDuckGo(url: url) {
textField.text = nil
return
}
textField.text = url.absoluteString
}
fileprivate func showDismissButton() {
dismissButton.isHidden = false
}
fileprivate func hideDismissButton() {
dismissButton.isHidden = true
}
fileprivate func showRefreshButton() {
refreshButton?.isHidden = false
}
fileprivate func hideRefreshButton() {
refreshButton?.isHidden = true
}
@IBAction func onFireButtonPressed() {
omniDelegate?.onFireButtonPressed()
}
@IBAction func onRefreshButtonPressed() {
omniDelegate?.onRefreshButtonPressed()
}
@IBAction func onBookmarksButtonPressed() {
omniDelegate?.onBookmarksButtonPressed()
}
@IBAction func onDismissButtonPressed() {
resignFirstResponder()
omniDelegate?.onDismissButtonPressed()
}
@IBAction func onTextEntered(_ sender: Any) {
onQuerySubmitted()
}
func onQuerySubmitted() {
guard let query = textField.text?.trimWhitespace(), !query.isEmpty else {
return
}
resignFirstResponder()
if let omniDelegate = omniDelegate {
omniDelegate.onOmniQuerySubmitted(query)
}
}
}
extension OmniBar: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
hideRefreshButton()
showDismissButton()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldQuery = textField.text,
let queryRange = oldQuery.range(from: range) else {
return true
}
let newQuery = oldQuery.replacingCharacters(in: queryRange, with: string)
omniDelegate?.onOmniQueryUpdated(newQuery)
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
showRefreshButton()
hideDismissButton()
}
}
extension String {
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = from16.samePosition(in: self),
let to = to16.samePosition(in: self)
else { return nil }
return from ..< to
}
}
| apache-2.0 | 349f621206799f7e4905704dc8816542 | 25.759259 | 129 | 0.615456 | 4.937358 | false | false | false | false |
wavio/STHLMParkingAPI | Carthage/Checkouts/SwiftDate/ExampleProject/ExampleProjectTests/ExampleProjectTests.swift | 1 | 4926 | //
// ExampleProjectTests.swift
// ExampleProjectTests
//
// Created by Mark Norgren on 5/21/15.
//
//
import UIKit
import XCTest
class ExampleProjectTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDateDifferences_DaysMonthsYears() {
let date1 = "1983-03-10".toDate(format: DateFormat.ISO8601)
let date2 = "1984-05-15".toDate(format: DateFormat.ISO8601)
let diff = date1?.difference(date2!, unitFlags: [NSCalendarUnit.Day,NSCalendarUnit.Month,NSCalendarUnit.Year])
let diffDays = diff!.day
let diffMonths = diff!.month
let diffYears = diff!.year
XCTAssertTrue(diffDays == 5, "SwiftDate failed to testing differences between two dates in terms of days")
XCTAssertTrue(diffMonths == 2, "SwiftDate failed to testing differences between two dates in terms of months")
XCTAssertTrue(diffYears == 1, "SwiftDate failed to testing differences between two dates in terms of years")
}
func testDateDifferences_HoursMinutes() {
let date1 = "1997-07-16T19:20+01:00".toDate(format: DateFormat.ISO8601)
let date2 = "1997-07-17T02:25+01:00".toDate(format: DateFormat.ISO8601)
let diff = date1?.difference(date2!, unitFlags: [NSCalendarUnit.Hour,NSCalendarUnit.Minute])
XCTAssertTrue(diff!.hour == 7, "SwiftDate failed to testing differences between two dates in terms of hours")
XCTAssertTrue(diff!.minute == 5, "SwiftDate failed to testing differences between two dates in terms of minutes")
}
func testISO8601_Year() {
let dateString = "1983"
let date = dateString.toDate(format: DateFormat.ISO8601)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy"
let controlDate = dateFormatter.dateFromString(dateString)
XCTAssertEqual(date!, controlDate!, "SwiftDate should equal controlDate")
}
// dateFormatter = "yyyy-MM"
func testISO8601_YearMonth() {
let dateString = "1983-03"
let date = dateString.toDate(format: DateFormat.ISO8601)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM"
let controlDate = dateFormatter.dateFromString(dateString)
XCTAssertEqual(date!, controlDate!, "SwiftDate should equal controlDate")
}
// dateFormatter = "yyyy-MM-DD"
func testISO8601_YearMonthDay() {
let dateString = "1983-03-10"
let date = dateString.toDate(format: DateFormat.ISO8601)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let controlDate = dateFormatter.dateFromString(dateString)
XCTAssertEqual(date!, controlDate!, "SwiftDate should equal controlDate")
}
// dateFormatter = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
func testISO8601_YearMonthDayHoursMinutes() {
let dateString = "1997-07-16T19:20+01:00"
let date = dateString.toDate(format: DateFormat.ISO8601)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mmZ"
let controlDate = dateFormatter.dateFromString(dateString)
XCTAssertEqual(date!, controlDate!, "SwiftDate should equal controlDate")
}
// "yyyy-MM-dd'T'HH:mm:ssZ"
func testISO8601_YearMonthDayHoursMinutesSeconds() {
let dateString = "1997-07-16T19:20:30+01:00"
let date = dateString.toDate(format: DateFormat.ISO8601)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let controlDate = dateFormatter.dateFromString(dateString)
XCTAssertEqual(date!, controlDate!, "SwiftDate should equal controlDate")
}
// "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
func testISO8601_YearMonthDayHoursMinutesSecondsFractionOfSecondTwoPlaces() {
let dateString = "1997-07-16T19:20:30.45+01:00"
let date = dateString.toDate(format: DateFormat.ISO8601)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let controlDate = dateFormatter.dateFromString(dateString)
XCTAssertEqual(date!, controlDate!, "SwiftDate should equal controlDate")
}
// "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
func testISO8601_YearMonthDayHoursMinutesSecondsFractionOfSecondThreePlaces() {
let dateString = "1997-07-16T19:20:30.456+01:00"
let date = dateString.toDate(format: DateFormat.ISO8601)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let controlDate = dateFormatter.dateFromString(dateString)
XCTAssertEqual(date!, controlDate!, "SwiftDate should equal controlDate")
}
}
| mit | 0c67ab03a7dae8a82f078ebe2ece049c | 45.037383 | 115 | 0.70138 | 4.111853 | false | true | false | false |
kevinvanderlugt/Exercism-Solutions | swift/raindrops/Raindrops.swift | 2 | 369 | struct Raindrops {
static func convert(number: Int) -> String {
let responses = sorted([ 3: "Pling", 5: "Plang", 7: "Plong" ], { $0.0 < $1.0 } )
let response = responses.reduce("") { response, pair in
return response + (number % pair.0 == 0 ? pair.1 : "")
}
return response != "" ? response : "\(number)"
}
} | mit | 69190b98ef766c71e2ea1469a0a97979 | 36 | 88 | 0.504065 | 3.653465 | false | false | false | false |
rheinfabrik/Heimdall.swift | HeimdallrTests/OAuthAccessTokenSpec.swift | 3 | 6669 | import Heimdallr
import Nimble
import Quick
import Result
class OAuthAccessTokenSpec: QuickSpec {
override func spec() {
describe("-copy") {
let accessToken = OAuthAccessToken(accessToken: "accessToken",
tokenType: "tokenType",
expiresAt: Date(timeIntervalSince1970: 0),
refreshToken: "refreshToken")
it("returns a copy of an access token") {
let result: OAuthAccessToken = accessToken.copy()
expect(result).toNot(beIdenticalTo(accessToken))
}
context("when providing a new access token") {
let result = accessToken.copy(accessToken: "accessToken2")
it("sets the provided access token on the new access token") {
expect(result.accessToken).to(equal("accessToken2"))
}
it("sets the original token type on the new access token") {
expect(result.tokenType).to(equal(accessToken.tokenType))
}
it("sets the original expiration date on the new access token") {
expect(result.expiresAt).to(equal(accessToken.expiresAt))
}
it("sets the original refreh token on the new access token") {
expect(result.refreshToken).to(equal(accessToken.refreshToken))
}
}
context("when providing a new token type") {
let result = accessToken.copy(tokenType: "tokenType2")
it("sets the original access token on the new access token") {
expect(result.accessToken).to(equal(accessToken.accessToken))
}
it("sets the provided token type on the new access token") {
expect(result.tokenType).to(equal("tokenType2"))
}
it("sets the original expiration date on the new access token") {
expect(result.expiresAt).to(equal(accessToken.expiresAt))
}
it("sets the original refreh token on the new access token") {
expect(result.refreshToken).to(equal(accessToken.refreshToken))
}
}
context("when providing a new expiration date") {
let result = accessToken.copy(expiresAt: Date(timeIntervalSince1970: 1))
it("sets the original access token on the new access token") {
expect(result.accessToken).to(equal(accessToken.accessToken))
}
it("sets the original token type on the new access token") {
expect(result.tokenType).to(equal(accessToken.tokenType))
}
it("sets the provided expiration date on the new access token") {
expect(result.expiresAt).to(equal(Date(timeIntervalSince1970: 1)))
}
it("sets the original refreh token on the new access token") {
expect(result.refreshToken).to(equal(accessToken.refreshToken))
}
}
context("when providing a new refresh token") {
let result = accessToken.copy(refreshToken: "refreshToken2")
it("sets the original access token on the new access token") {
expect(result.accessToken).to(equal(accessToken.accessToken))
}
it("sets the original token type on the new access token") {
expect(result.tokenType).to(equal(accessToken.tokenType))
}
it("sets the original expiration date on the new access token") {
expect(result.expiresAt).to(equal(accessToken.expiresAt))
}
it("sets the provided refresh token on the new access token") {
expect(result.refreshToken).to(equal("refreshToken2"))
}
}
}
describe("<Equatable> ==") {
it("returns true if access tokens are equal") {
let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType")
let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType")
expect(lhs == rhs).to(beTrue())
}
it("returns false if access tokens are not equal") {
let lhs = OAuthAccessToken(accessToken: "accessTokena", tokenType: "tokenType")
let rhs = OAuthAccessToken(accessToken: "accessTokenb", tokenType: "tokenType")
expect(lhs == rhs).to(beFalse())
}
it("returns false if token types are not equal") {
let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypea")
let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypeb")
expect(lhs == rhs).to(beFalse())
}
it("returns false if expiration times are not equal") {
let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: Date(timeIntervalSinceNow: 1))
let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", expiresAt: Date(timeIntervalSinceNow: -1))
expect(lhs == rhs).to(beFalse())
}
it("returns false if refresh tokens are not equal") {
let lhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", refreshToken: "refreshTokena")
let rhs = OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType", refreshToken: "refreshTokenb")
expect(lhs == rhs).to(beFalse())
}
}
describe("+decode") {
context("without an expiration date") {
it("creates a valid access token") {
let accessToken = OAuthAccessToken.decode([
"access_token": "accessToken" as AnyObject,
"token_type": "tokenType" as AnyObject
])
expect(accessToken).toNot(beNil())
expect(accessToken?.accessToken).to(equal("accessToken"))
expect(accessToken?.tokenType).to(equal("tokenType"))
expect(accessToken?.expiresAt).to(beNil())
expect(accessToken?.refreshToken).to(beNil())
}
}
}
}
}
| apache-2.0 | 6e0e741c18ec07e35bb568f71d5b6724 | 42.025806 | 137 | 0.545809 | 5.608915 | false | false | false | false |
Antidote-for-Tox/Antidote | Antidote/EnterPinController.swift | 1 | 4028 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
import SnapKit
private struct Constants {
static let PinLength = 4
}
protocol EnterPinControllerDelegate: class {
func enterPinController(_ controller: EnterPinController, successWithPin pin: String)
// This method may be called only for ValidatePin state.
func enterPinControllerFailure(_ controller: EnterPinController)
}
class EnterPinController: UIViewController {
enum State {
case validatePin(validPin: String)
case setPin
}
weak var delegate: EnterPinControllerDelegate?
let state: State
var topText: String {
get {
return pinInputView.topText
}
set {
customLoadView()
pinInputView.topText = newValue
}
}
var descriptionText: String? {
get {
return pinInputView.descriptionText
}
set {
customLoadView()
pinInputView.descriptionText = newValue
}
}
fileprivate let theme: Theme
fileprivate var pinInputView: PinInputView!
fileprivate var enteredString: String = ""
init(theme: Theme, state: State) {
self.theme = theme
self.state = state
super.init(nibName: nil, bundle: nil)
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
loadViewWithBackgroundColor(theme.colorForType(.NormalBackground))
createViews()
installConstraints()
pinInputView.applyColors()
}
override var shouldAutorotate : Bool {
return false
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
func resetEnteredPin() {
enteredString = ""
pinInputView.enteredNumbersCount = enteredString.count
}
}
extension EnterPinController: PinInputViewDelegate {
func pinInputView(_ view: PinInputView, numericButtonPressed i: Int) {
guard enteredString.count < Constants.PinLength else {
return
}
enteredString += "\(i)"
pinInputView.enteredNumbersCount = enteredString.count
if enteredString.count == Constants.PinLength {
switch state {
case .validatePin(let validPin):
if enteredString == validPin {
delegate?.enterPinController(self, successWithPin: enteredString)
}
else {
delegate?.enterPinControllerFailure(self)
}
case .setPin:
delegate?.enterPinController(self, successWithPin: enteredString)
}
}
}
func pinInputViewDeleteButtonPressed(_ view: PinInputView) {
guard enteredString.count > 0 else {
return
}
enteredString = String(enteredString.dropLast())
view.enteredNumbersCount = enteredString.count
}
}
private extension EnterPinController {
func createViews() {
pinInputView = PinInputView(pinLength: Constants.PinLength,
topColor: theme.colorForType(.LockGradientTop),
bottomColor: theme.colorForType(.LockGradientBottom))
pinInputView.delegate = self
view.addSubview(pinInputView)
}
func installConstraints() {
pinInputView.snp.makeConstraints {
$0.center.equalTo(view)
}
}
func customLoadView() {
if #available(iOS 9.0, *) {
loadViewIfNeeded()
} else {
if !isViewLoaded {
// creating view
view.setNeedsDisplay()
}
}
}
}
| mpl-2.0 | d157f98e22d501dae8d1f36ea344027e | 26.216216 | 90 | 0.60576 | 5.197419 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/NSURLQueryItem.swift | 1 | 2300 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
//
// NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property.
open class NSURLQueryItem: NSObject, NSSecureCoding, NSCopying {
open private(set) var name: String
open private(set) var value: String?
public init(name: String, value: String?) {
self.name = name
self.value = value
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
required public init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let encodedName = aDecoder.decodeObject(forKey: "NS.name") as! NSString
self.name = encodedName._swiftObject
let encodedValue = aDecoder.decodeObject(forKey: "NS.value") as? NSString
self.value = encodedValue?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.name._bridgeToObjectiveC(), forKey: "NS.name")
aCoder.encode(self.value?._bridgeToObjectiveC(), forKey: "NS.value")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLQueryItem else { return false }
return other === self
|| (other.name == self.name
&& other.value == self.value)
}
}
extension NSURLQueryItem: _StructTypeBridgeable {
public typealias _StructType = URLQueryItem
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 197a93351a6f23e95ec45ff1010d64df | 32.333333 | 195 | 0.665652 | 4.811715 | false | false | false | false |
iOSTestApps/HausClock | HausClock/Models/Game.swift | 2 | 3011 | //
// Game.swift
// HausClock
//
// Created by Tom Brown on 11/28/14.
// Copyright (c) 2014 not. All rights reserved.
//
import Foundation
import ReactiveCocoa
import AudioToolbox
var game = Game() // Global game instance - Is there a canonical way to do this?
class Game {
enum State {
case Initial // The game hasn't started yet
case Active
case Paused
case Finished
}
var state: ObservableProperty<State> = ObservableProperty(.Initial)
let clockTickInterval:Double = 0.1 // This currently causes massive re-rendering. Should only update text as necessary
init() {
NSTimer.scheduledTimerWithTimeInterval(clockTickInterval, target: self, selector: Selector("onClockTick"), userInfo: nil, repeats: true)
reset()
// Buzz when the game finishes
let finishedStream = state.values().skipRepeats{ $0 == $1}.filter { $0 == Game.State.Finished }
// TODO: It seems that the concatenation doesn't join correctly. Perhaps we want merge?
let delayedStream = finishedStream.delay(3.0, onScheduler: MainScheduler())
let doubledStream = delayedStream.concat(finishedStream)
finishedStream.start { _ in AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) }
}
var players = [
Player(position: .Top),
Player(position: .Bottom)
]
func reset() {
for player in players {
player.secondsRemaining.value = player.initialTimeInSeconds
}
setPlayerToActive(.Top)
state.value = .Initial
}
func userDidTouchButton(position: Player.Position) {
switch state.value {
case .Initial, .Active:
setPlayerToActive(position)
case .Finished, .Paused:
break
}
}
func getPlayerByPosition(position: Player.Position) -> Player {
return players.filter{ $0.position == position }.first!
}
private func setPlayerToActive(position: Player.Position) {
var activePlayer = getPlayerByPosition(position)
var inactivePlayer = getPlayerByPosition(position.opposite())
activePlayer.state.value = .Active
inactivePlayer.state.value = .Waiting
state.value = .Active
}
private func getActivePlayer() -> Player? {
return players.filter{ $0.state.value == Player.State.Active }.first
}
@objc private func onClockTick() {
if state.value == .Active {
decrementActivePlayer()
}
}
// Decrements the active player if one is available. If the player has lost, changes the player state
private func decrementActivePlayer() {
if var activePlayer = getActivePlayer() {
activePlayer.secondsRemaining.value -= clockTickInterval
if activePlayer.secondsRemaining.value <= 0 {
state.value = .Finished
}
}
}
} | mit | 8e2801db97fdd086412863974049f5a2 | 30.375 | 144 | 0.627698 | 4.779365 | false | false | false | false |
pvieito/PythonKit | Tests/PythonKitTests/PythonFunctionTests.swift | 1 | 13356 | import XCTest
import PythonKit
class PythonFunctionTests: XCTestCase {
private var canUsePythonFunction: Bool {
let versionMajor = Python.versionInfo.major
let versionMinor = Python.versionInfo.minor
return (versionMajor == 3 && versionMinor >= 1) || versionMajor > 3
}
func testPythonFunction() {
guard canUsePythonFunction else {
return
}
let pythonAdd = PythonFunction { args in
let lhs = args[0]
let rhs = args[1]
return lhs + rhs
}.pythonObject
let pythonSum = pythonAdd(2, 3)
XCTAssertNotNil(Double(pythonSum))
XCTAssertEqual(pythonSum, 5)
// Test function with keyword arguments
// Since there is no alternative function signature, `args` and `kwargs`
// can be used without manually stating their type. This differs from
// the behavior when there are no keywords.
let pythonSelect = PythonFunction { args, kwargs in
// NOTE: This may fail on Python versions before 3.6 because they do
// not preserve order of keyword arguments
XCTAssertEqual(args[0], true)
XCTAssertEqual(kwargs[0].key, "y")
XCTAssertEqual(kwargs[0].value, 2)
XCTAssertEqual(kwargs[1].key, "x")
XCTAssertEqual(kwargs[1].value, 3)
let conditional = Bool(args[0])!
let xIndex = kwargs.firstIndex(where: { $0.key == "x" })!
let yIndex = kwargs.firstIndex(where: { $0.key == "y" })!
return kwargs[conditional ? xIndex : yIndex].value
}.pythonObject
let pythonSelectOutput = pythonSelect(true, y: 2, x: 3)
XCTAssertEqual(pythonSelectOutput, 3)
}
// From https://www.geeksforgeeks.org/create-classes-dynamically-in-python
func testPythonClassConstruction() {
guard canUsePythonFunction else {
return
}
let constructor = PythonInstanceMethod { args in
let `self` = args[0]
`self`.constructor_arg = args[1]
return Python.None
}
// Instead of calling `print`, use this to test what would be output.
var printOutput: String?
// Example of function using an alternative syntax for `args`.
let displayMethod = PythonInstanceMethod { (args: [PythonObject]) in
// let `self` = args[0]
printOutput = String(args[1])
return Python.None
}
let classMethodOriginal = PythonInstanceMethod { args in
// let cls = args[0]
printOutput = String(args[1])
return Python.None
}
// Did not explicitly convert `constructor` or `displayMethod` to
// PythonObject. This is intentional, as the `PythonClass` initializer
// should take any `PythonConvertible` and not just `PythonObject`.
let classMethod = Python.classmethod(classMethodOriginal.pythonObject)
let Geeks = PythonClass("Geeks", members: [
// Constructor
"__init__": constructor,
// Data members
"string_attribute": "Geeks 4 geeks!",
"int_attribute": 1706256,
// Member functions
"func_arg": displayMethod,
"class_func": classMethod,
]).pythonObject
let obj = Geeks("constructor argument")
XCTAssertEqual(obj.constructor_arg, "constructor argument")
XCTAssertEqual(obj.string_attribute, "Geeks 4 geeks!")
XCTAssertEqual(obj.int_attribute, 1706256)
obj.func_arg("Geeks for Geeks")
XCTAssertEqual(printOutput, "Geeks for Geeks")
Geeks.class_func("Class Dynamically Created!")
XCTAssertEqual(printOutput, "Class Dynamically Created!")
}
// Previously, there was a build error where passing a simple
// `PythonClass.Members` literal made the literal's type ambiguous. It was
// confused with `[String: PythonObject]`. The solution was adding a
// `@_disfavoredOverload` attribute to the more specific initializer.
func testPythonClassInitializer() {
guard canUsePythonFunction else {
return
}
let MyClass = PythonClass(
"MyClass",
superclasses: [Python.object],
members: [
"memberName": "memberValue",
]
).pythonObject
let memberValue = MyClass().memberName
XCTAssertEqual(String(memberValue), "memberValue")
}
func testPythonClassInheritance() {
guard canUsePythonFunction else {
return
}
var helloOutput: String?
var helloWorldOutput: String?
// Declare subclasses of `Python.Exception`
let HelloException = PythonClass(
"HelloException",
superclasses: [Python.Exception],
members: [
"str_prefix": "HelloException-prefix ",
"__init__": PythonInstanceMethod { args in
let `self` = args[0]
let message = "hello \(args[1])"
helloOutput = String(message)
// Conventional `super` syntax does not work; use this instead.
Python.Exception.__init__(`self`, message)
return Python.None
},
// Example of function using the `self` convention instead of `args`.
"__str__": PythonInstanceMethod { (`self`: PythonObject) in
return `self`.str_prefix + Python.repr(`self`)
}
]
).pythonObject
let HelloWorldException = PythonClass(
"HelloWorldException",
superclasses: [HelloException],
members: [
"str_prefix": "HelloWorldException-prefix ",
"__init__": PythonInstanceMethod { args in
let `self` = args[0]
let message = "world \(args[1])"
helloWorldOutput = String(message)
`self`.int_param = args[2]
// Conventional `super` syntax does not work; use this instead.
HelloException.__init__(`self`, message)
return Python.None
},
// Example of function using the `self` convention instead of `args`.
"custom_method": PythonInstanceMethod { (`self`: PythonObject) in
return `self`.int_param
}
]
).pythonObject
// Test that inheritance works as expected
let error1 = HelloException("test 1")
XCTAssertEqual(helloOutput, "hello test 1")
XCTAssertEqual(Python.str(error1), "HelloException-prefix HelloException('hello test 1')")
XCTAssertEqual(Python.repr(error1), "HelloException('hello test 1')")
let error2 = HelloWorldException("test 1", 123)
XCTAssertEqual(helloOutput, "hello world test 1")
XCTAssertEqual(helloWorldOutput, "world test 1")
XCTAssertEqual(Python.str(error2), "HelloWorldException-prefix HelloWorldException('hello world test 1')")
XCTAssertEqual(Python.repr(error2), "HelloWorldException('hello world test 1')")
XCTAssertEqual(error2.custom_method(), 123)
XCTAssertNotEqual(error2.custom_method(), "123")
// Test that subclasses behave like Python exceptions
// Example of function with no named parameters, which can be stated
// ergonomically using an underscore. The ignored input is a [PythonObject].
let testFunction = PythonFunction { _ in
throw HelloWorldException("EXAMPLE ERROR MESSAGE", 2)
}.pythonObject
do {
try testFunction.throwing.dynamicallyCall(withArguments: [])
XCTFail("testFunction did not throw an error.")
} catch PythonError.exception(let error, _) {
guard let description = String(error) else {
XCTFail("A string could not be created from a HelloWorldException.")
return
}
XCTAssertTrue(description.contains("EXAMPLE ERROR MESSAGE"))
XCTAssertTrue(description.contains("HelloWorldException"))
} catch {
XCTFail("Got error that was not a Python exception: \(error.localizedDescription)")
}
}
// Tests the ability to dynamically construct an argument list with keywords
// and instantiate a `PythonInstanceMethod` with keywords.
func testPythonClassInheritanceWithKeywords() {
guard canUsePythonFunction else {
return
}
func getValue(key: String, kwargs: [(String, PythonObject)]) -> PythonObject {
let index = kwargs.firstIndex(where: { $0.0 == key })!
return kwargs[index].1
}
// Base class has the following arguments:
// __init__():
// - 1 unnamed argument
// - param1
// - param2
//
// test_method():
// - param1
// - param2
let BaseClass = PythonClass(
"BaseClass",
superclasses: [],
members: [
"__init__": PythonInstanceMethod { args, kwargs in
let `self` = args[0]
`self`.arg1 = args[1]
`self`.param1 = getValue(key: "param1", kwargs: kwargs)
`self`.param2 = getValue(key: "param2", kwargs: kwargs)
return Python.None
},
"test_method": PythonInstanceMethod { args, kwargs in
let `self` = args[0]
`self`.param1 += getValue(key: "param1", kwargs: kwargs)
`self`.param2 += getValue(key: "param2", kwargs: kwargs)
return Python.None
}
]
).pythonObject
// Derived class accepts the following arguments:
// __init__():
// - param2
// - param3
//
// test_method():
// - param1
// - param2
// - param3
let DerivedClass = PythonClass(
"DerivedClass",
superclasses: [],
members: [
"__init__": PythonInstanceMethod { args, kwargs in
let `self` = args[0]
`self`.param3 = getValue(key: "param3", kwargs: kwargs)
// Lists the arguments in an order different than they are
// specified (self, param2, param3, param1, arg1). The
// correct order is (self, arg1, param1, param2, param3).
let newKeywordArguments = args.map {
("", $0)
} + kwargs + [
("param1", 1),
("", 0)
]
BaseClass.__init__.dynamicallyCall(
withKeywordArguments: newKeywordArguments)
return Python.None
},
"test_method": PythonInstanceMethod { args, kwargs in
let `self` = args[0]
`self`.param3 += getValue(key: "param3", kwargs: kwargs)
BaseClass.test_method.dynamicallyCall(
withKeywordArguments: args.map { ("", $0) } + kwargs)
return Python.None
}
]
).pythonObject
let derivedInstance = DerivedClass(param2: 2, param3: 3)
XCTAssertEqual(derivedInstance.arg1, 0)
XCTAssertEqual(derivedInstance.param1, 1)
XCTAssertEqual(derivedInstance.param2, 2)
XCTAssertEqual(derivedInstance.checking.param3, 3)
derivedInstance.test_method(param1: 1, param2: 2, param3: 3)
XCTAssertEqual(derivedInstance.arg1, 0)
XCTAssertEqual(derivedInstance.param1, 2)
XCTAssertEqual(derivedInstance.param2, 4)
XCTAssertEqual(derivedInstance.checking.param3, 6)
// Validate that subclassing and instantiating the derived class does
// not affect behavior of the parent class.
let baseInstance = BaseClass(0, param1: 10, param2: 20)
XCTAssertEqual(baseInstance.arg1, 0)
XCTAssertEqual(baseInstance.param1, 10)
XCTAssertEqual(baseInstance.param2, 20)
XCTAssertEqual(baseInstance.checking.param3, nil)
baseInstance.test_method(param1: 10, param2: 20)
XCTAssertEqual(baseInstance.arg1, 0)
XCTAssertEqual(baseInstance.param1, 20)
XCTAssertEqual(baseInstance.param2, 40)
XCTAssertEqual(baseInstance.checking.param3, nil)
}
}
| apache-2.0 | 8495db2129024084ea4d8d35e36d6d9e | 38.167155 | 114 | 0.542078 | 5.034301 | false | true | false | false |
ashfurrow/eidolon | KioskTests/Models/ArtworkTests.swift | 2 | 2693 | import Quick
import Nimble
@testable
import Kiosk
class ArtworkTests: QuickSpec {
override func spec() {
let id = "wah-wah"
let title = "title"
let date = "late 2014"
let blurb = "pretty good"
let artistID = "artist-1"
let artistName = "Artist 1"
let artistDict = ["id" : artistID, "name": artistName]
let data: [String: AnyObject] = ["id":id as AnyObject , "title" : title as AnyObject, "date":date as AnyObject, "blurb":blurb as AnyObject, "artist":artistDict as AnyObject]
var artwork: Artwork!
beforeEach {
artwork = Artwork.fromJSON(data)
}
it("converts from JSON") {
expect(artwork.id) == id
expect(artwork.artists?.count) == 1
expect(artwork.artists?.first?.id) == artistID
}
it("grabs the default image") {
let defaultImage = Image.fromJSON([
"id": "default",
"image_url":"http://image.com/:version.jpg",
"image_versions" : ["small"],
"original_width": size.width,
"original_height": size.height,
"default_image": true
])
let otherImage = Image.fromJSON([
"id": "nonDefault",
"image_url":"http://image.com/:version.jpg",
"image_versions" : ["small"],
"original_width": size.width,
"original_height": size.height
])
artwork.images = [defaultImage, otherImage]
expect(artwork.defaultImage!.id) == "default"
}
it("grabs the first image as default if there is no default image specified") {
let image = Image.fromJSON([
"id": "default",
"image_url":"http://image.com/:version.jpg",
"image_versions" : ["small"],
"original_width": size.width,
"original_height": size.height,
])
let otherImage = Image.fromJSON([
"id": "nonDefault",
"image_url":"http://image.com/:version.jpg",
"image_versions" : ["small"],
"original_width": size.width,
"original_height": size.height
])
artwork.images = [image, otherImage]
expect(artwork.defaultImage!.id) == "default"
}
it("updates the soldStatus") {
let newArtwork = Artwork.fromJSON(data)
newArtwork.soldStatus = true
artwork.updateWithValues(newArtwork)
expect(artwork.soldStatus) == true
}
}
}
| mit | d913d9465c6ee25d5ed5b1718d671369 | 31.445783 | 182 | 0.511326 | 4.488333 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/BitcoinKit/Models/Accounts/BitcoinWalletAccount.swift | 1 | 1272 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BitcoinChainKit
import PlatformKit
public struct BitcoinWalletAccount: Equatable {
// MARK: Public Properties
public let archived: Bool
public let index: Int
public let label: String?
public let publicKeys: XPubs
// MARK: Internal Properties
var isActive: Bool {
!archived
}
// MARK: Initializers
public init(index: Int, label: String?, archived: Bool, publicKeys: XPubs) {
self.index = index
self.label = label
self.archived = archived
self.publicKeys = publicKeys
}
public init(index: Int, account: PayloadBitcoinWalletAccountV4) {
self.index = index
archived = account.archived
label = account.label
let xpubs = account.derivations
.map { derivation in
XPub(address: derivation.xpub, derivationType: derivation.type)
}
publicKeys = XPubs(xpubs: xpubs)
}
public init(index: Int, account: PayloadBitcoinWalletAccountV3) {
self.index = index
archived = account.archived
label = account.label
publicKeys = XPubs(xpubs: [.init(address: account.xpub, derivationType: .legacy)])
}
}
| lgpl-3.0 | 08dde4dc9790d29a412a1fca592fdbeb | 26.042553 | 90 | 0.641227 | 4.382759 | false | false | false | false |
iOSWizards/AwesomeMedia | AwesomeMedia/Classes/Views/AwesomeMediaAudioPlayerView.swift | 1 | 10167 | //
// AwesomeMediaMiniAudioView.swift
// AwesomeMedia
//
// Created by Evandro Harrison Hoffmann on 4/25/18.
//
import UIKit
import AwesomeUIMagic
public class AwesomeMediaAudioPlayerView: UIView {
@IBOutlet public weak var mainView: UIView!
@IBOutlet public weak var coverImageView: UIImageView!
@IBOutlet public weak var fullscreenButton: UIButton!
@IBOutlet public weak var playButton: UIButton!
@IBOutlet public weak var titleLabel: UILabel!
@IBOutlet public weak var timeLabel: UILabel?
// Public variables
public var mediaParams = AwesomeMediaParams()
public var isLocked = false
public var canRemove = false
public var trackingSource: AwesomeMediaTrackingSource = .audioMiniplayer
// Private variables
fileprivate var removeTimer: Timer?
// Callbacks
public var fullScreenCallback: FullScreenCallback?
override public func awakeFromNib() {
super.awakeFromNib()
// add observers
addObservers()
}
public func configure(withMediaParams mediaParams: AwesomeMediaParams, trackingSource: AwesomeMediaTrackingSource) {
self.mediaParams = mediaParams
self.trackingSource = trackingSource
// Load cover Image
loadCoverImage()
// Set Media Information
updateMediaInformation()
// Update play button status
updatePlayStatus()
// check for loading state
mainView.stopLoadingAnimation()
if AwesomeMediaManager.shared.mediaIsLoading(withParams: mediaParams) {
mainView.startLoadingAnimation()
}
}
// MARK: - Events
@IBAction func playButtonPressed(_ sender: Any) {
AwesomeMediaPlayerType.type = .audio
playButton.isSelected = !playButton.isSelected
// Play/Stop media
if playButton.isSelected {
AwesomeMediaManager.shared.playMedia(withParams: self.mediaParams, viewController: parentViewController)
} else {
sharedAVPlayer.pause()
}
// tracking event
if playButton.isSelected {
track(event: .startedPlaying, source: trackingSource)
} else {
track(event: .stoppedPlaying, source: trackingSource)
}
}
@IBAction func fullscreenButtonPressed(_ sender: Any) {
fullScreenCallback?()
track(event: .toggleFullscreen, source: trackingSource)
}
}
// MARK: - Media Information
extension AwesomeMediaAudioPlayerView {
public func updateMediaInformation() {
titleLabel.text = mediaParams.title
timeLabel?.text = mediaParams.duration.timeString.uppercased()
}
public func loadCoverImage() {
guard let coverImageUrl = mediaParams.coverUrl else {
return
}
// set the cover image
coverImageView.setImage(coverImageUrl)
}
fileprivate func updatePlayStatus() {
playButton.isSelected = sharedAVPlayer.isPlaying(withParams: mediaParams)
}
}
// MARK: - Observers
extension AwesomeMediaAudioPlayerView: AwesomeMediaEventObserver {
public func addObservers() {
AwesomeMediaNotificationCenter.addObservers([.basic, .timedOut, .stopped, .hideMiniPlayer], to: self)
}
public func removeObservers() {
AwesomeMediaNotificationCenter.removeObservers(from: self)
}
public func startedPlaying() {
guard sharedAVPlayer.isPlaying(withParams: mediaParams) else {
return
}
// cancel remove timer
cancelRemoveTimer()
// change play button selection
playButton.isSelected = true
// update Control Center
AwesomeMediaControlCenter.updateControlCenter(withParams: mediaParams)
// remove media alert if present
parentViewController?.removeAlertIfPresent()
}
public func pausedPlaying() {
playButton.isSelected = sharedAVPlayer.isPlaying(withParams: mediaParams)
// unlock buttons
stoppedBuffering()
// configure auto remove
setupAutoRemove()
}
public func stoppedPlaying() {
pausedPlaying()
stoppedBuffering()
finishedPlaying()
// remove media alert if present
parentViewController?.removeAlertIfPresent()
}
public func startedBuffering() {
guard sharedAVPlayer.isCurrentItem(withParams: mediaParams) else {
stoppedBuffering()
return
}
mainView.startLoadingAnimation()
lock(true, animated: true)
}
public func stoppedBuffering() {
mainView.stopLoadingAnimation()
lock(false, animated: true)
}
public func finishedPlaying() {
playButton.isSelected = false
// unlock buttons
lock(false, animated: true)
// configure auto remove
setupAutoRemove()
}
public func timedOut() {
parentViewController?.showMediaTimedOutAlert()
}
public func hideMiniPlayer(_ notification: NSNotification) {
remove(animated: false)
}
}
// MARK: - States
extension AwesomeMediaAudioPlayerView: AwesomeMediaControlState {
public func lock(_ lock: Bool, animated: Bool) {
if animated {
UIView.animate(withDuration: 0.3) {
self.setLockedState(locked: lock)
}
} else {
setLockedState(locked: lock)
}
}
public func setLockedState(locked: Bool) {
self.isLocked = locked
let lockedAlpha: CGFloat = 0.5
playButton.isUserInteractionEnabled = !locked
playButton.alpha = locked ? lockedAlpha : 1.0
}
}
// MARK: - Animations
extension AwesomeMediaAudioPlayerView {
public func show() {
//translatesAutoresizingMaskIntoConstraints = true
frame.origin.y = UIScreen.main.bounds.size.height
UIView.animate(withDuration: 0.3, animations: {
self.frame.origin.y = UIScreen.main.bounds.size.height-self.frame.size.height
}, completion: { (_) in
//self.translatesAutoresizingMaskIntoConstraints = false
})
}
public func remove(animated: Bool) {
// remove observers
removeObservers()
guard animated else {
removeFromSuperview()
return
}
translatesAutoresizingMaskIntoConstraints = true
UIView.animate(withDuration: 0.3, animations: {
self.frame.origin.y = UIScreen.main.bounds.size.height
}, completion: { (_) in
self.removeFromSuperview()
})
}
public func setupAutoRemove() {
cancelRemoveTimer()
guard canRemove else {
return
}
removeTimer = Timer.scheduledTimer(withTimeInterval: AwesomeMedia.removeAudioControlViewTime, repeats: false) { (_) in
self.remove(animated: true)
}
}
public func cancelRemoveTimer() {
removeTimer?.invalidate()
removeTimer = nil
}
}
// MARK: - View Initialization
extension AwesomeMediaAudioPlayerView {
public static var newInstance: AwesomeMediaAudioPlayerView {
return AwesomeMedia.bundle.loadNibNamed("AwesomeMediaAudioPlayerView", owner: self, options: nil)![0] as! AwesomeMediaAudioPlayerView
}
}
extension UIView {
public func addAudioPlayer(withParams params: AwesomeMediaParams, animated: Bool = false) -> AwesomeMediaAudioPlayerView? {
guard !isShowingAudioControlView else {
return nil
}
let playerView = AwesomeMediaAudioPlayerView.newInstance
playerView.configure(withMediaParams: params, trackingSource: .audioMiniplayer)
playerView.canRemove = true
addSubview(playerView)
playerView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: playerView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: playerView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: playerView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: playerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: isPad ? 100 : 88))
// show with animation
if animated {
playerView.show()
}
// add fullscreen callback
playerView.fullScreenCallback = { [weak self] in
guard let self = self else { return }
guard let playerType = AwesomeMediaPlayerType.type else {
return
}
switch playerType {
case .video:
self.parentViewController?.presentVideoFullscreen(withMediaParams: params)
case .verticalVideo:
self.parentViewController?.presentVerticalVideoFullscreen(withMediaParams: params)
default:
self.parentViewController?.presentAudioFullscreen(withMediaParams: params)
}
}
return playerView
}
public func removeAudioControlView(animated: Bool = false) {
for subview in subviews where subview is AwesomeMediaAudioPlayerView {
(subview as? AwesomeMediaAudioPlayerView)?.remove(animated: animated)
}
}
public var isShowingAudioControlView: Bool {
for subview in subviews where subview is AwesomeMediaAudioPlayerView {
return true
}
return false
}
}
| mit | 472dbfc0b11f0f8fae73658498d55af8 | 28.99115 | 182 | 0.626438 | 5.626453 | false | false | false | false |
huonw/swift | test/expr/expressions.swift | 1 | 34742 | // RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Tests and samples.
//===----------------------------------------------------------------------===//
// Comment. With unicode characters: ¡ç®åz¥!
func markUsed<T>(_: T) {}
// Various function types.
var func1 : () -> () // No input, no output.
var func2 : (Int) -> Int
var func3 : () -> () -> () // Takes nothing, returns a fn.
var func3a : () -> (() -> ()) // same as func3
var func6 : (_ fn : (Int,Int) -> Int) -> () // Takes a fn, returns nothing.
var func7 : () -> (Int,Int,Int) // Takes nothing, returns tuple.
// Top-Level expressions. These are 'main' content.
func1()
_ = 4+7
var bind_test1 : () -> () = func1
var bind_test2 : Int = 4; func1 // expected-error {{expression resolves to an unused variable}}
(func1, func2) // expected-error {{expression resolves to an unused variable}}
func basictest() {
// Simple integer variables.
var x : Int
var x2 = 4 // Simple Type inference.
var x3 = 4+x*(4+x2)/97 // Basic Expressions.
// Declaring a variable Void, aka (), is fine too.
var v : Void
var x4 : Bool = true
var x5 : Bool =
4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}}
//var x6 : Float = 4+5
var x7 = 4; 5 // expected-warning {{integer literal is unused}}
// Test implicit conversion of integer literal to non-Int64 type.
var x8 : Int8 = 4
x8 = x8 + 1
_ = x8 + 1
_ = 0 + x8
1.0 + x8 // expected-error{{binary operator '+' cannot be applied to operands of type 'Double' and 'Int8'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var x9 : Int16 = x8 + 1 // expected-error {{cannot convert value of type 'Int8' to specified type 'Int16'}}
// Various tuple types.
var tuple1 : ()
var tuple2 : (Int)
var tuple3 : (Int, Int, ())
var tuple2a : (a : Int) // expected-error{{cannot create a single-element tuple with an element label}}{{18-22=}}
var tuple3a : (a : Int, b : Int, c : ())
var tuple4 = (1, 2) // Tuple literal.
var tuple5 = (1, 2, 3, 4) // Tuple literal.
var tuple6 = (1 2) // expected-error {{expected ',' separator}} {{18-18=,}}
// Brace expressions.
var brace3 = {
var brace2 = 42 // variable shadowing.
_ = brace2+7
}
// Function calls.
var call1 : () = func1()
var call2 = func2(1)
var call3 : () = func3()()
// Cannot call an integer.
bind_test2() // expected-error {{cannot call value of non-function type 'Int'}}{{13-15=}}
}
// <https://bugs.swift.org/browse/SR-3522>
func testUnusedLiterals_SR3522() {
42 // expected-warning {{integer literal is unused}}
2.71828 // expected-warning {{floating-point literal is unused}}
true // expected-warning {{boolean literal is unused}}
false // expected-warning {{boolean literal is unused}}
"Hello" // expected-warning {{string literal is unused}}
"Hello \(42)" // expected-warning {{string literal is unused}}
#file // expected-warning {{#file literal is unused}}
(#line) // expected-warning {{#line literal is unused}}
#column // expected-warning {{#column literal is unused}}
#function // expected-warning {{#function literal is unused}}
#dsohandle // expected-warning {{#dsohandle literal is unused}}
__FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}} expected-warning {{#file literal is unused}}
__LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}} expected-warning {{#line literal is unused}}
__COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}} expected-warning {{#column literal is unused}}
__FUNCTION__ // expected-error {{__FUNCTION__ has been replaced with #function in Swift 3}} expected-warning {{#function literal is unused}}
__DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}} expected-warning {{#dsohandle literal is unused}}
nil // expected-error {{'nil' requires a contextual type}}
#fileLiteral(resourceName: "what.txt") // expected-error {{could not infer type of file reference literal}} expected-note * {{}}
#imageLiteral(resourceName: "hello.png") // expected-error {{could not infer type of image literal}} expected-note * {{}}
#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // expected-error {{could not infer type of color literal}} expected-note * {{}}
}
// Infix operators and attribute lists.
infix operator %% : MinPrecedence
precedencegroup MinPrecedence {
associativity: left
lowerThan: AssignmentPrecedence
}
func %%(a: Int, b: Int) -> () {}
var infixtest : () = 4 % 2 + 27 %% 123
// The 'func' keyword gives a nice simplification for function definitions.
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl2() {
return funcdecl1(4, 2)
}
func funcdecl3() -> Int {
return 12
}
func funcdecl4(_ a: ((Int) -> Int), b: Int) {}
func signal(_ sig: Int, f: (Int) -> Void) -> (Int) -> Void {}
// Doing fun things with named arguments. Basic stuff first.
func funcdecl6(_ a: Int, b: Int) -> Int { return a+b }
// Can dive into tuples, 'b' is a reference to a whole tuple, c and d are
// fields in one. Cannot dive into functions or through aliases.
func funcdecl7(_ a: Int, b: (c: Int, d: Int), third: (c: Int, d: Int)) -> Int {
_ = a + b.0 + b.c + third.0 + third.1
b.foo // expected-error {{value of tuple type '(c: Int, d: Int)' has no member 'foo'}}
}
// Error recovery.
func testfunc2 (_: ((), Int) -> Int) -> Int {}
func errorRecovery() {
testfunc2({ $0 + 1 }) // expected-error {{contextual closure type '((), Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
enum union1 {
case bar
case baz
}
var a: Int = .hello // expected-error {{type 'Int' has no member 'hello'}}
var b: union1 = .bar // ok
var c: union1 = .xyz // expected-error {{type 'union1' has no member 'xyz'}}
var d: (Int,Int,Int) = (1,2) // expected-error {{cannot convert value of type '(Int, Int)' to specified type '(Int, Int, Int)'}}
var e: (Int,Int) = (1, 2, 3) // expected-error {{cannot convert value of type '(Int, Int, Int)' to specified type '(Int, Int)'}}
var f: (Int,Int) = (1, 2, f : 3) // expected-error {{cannot convert value of type '(Int, Int, f: Int)' to specified type '(Int, Int)'}}
// <rdar://problem/22426860> CrashTracer: [USER] swift at …mous_namespace::ConstraintGenerator::getTypeForPattern + 698
var (g1, g2, g3) = (1, 2) // expected-error {{'(Int, Int)' is not convertible to '(_, _, _)', tuples have a different number of elements}}
}
func acceptsInt(_ x: Int) {}
acceptsInt(unknown_var) // expected-error {{use of unresolved identifier 'unknown_var'}}
var test1a: (Int) -> (Int) -> Int = { { $0 } } // expected-error{{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{38-38= _ in}}
var test1b = { 42 }
var test1c = { { 42 } }
var test1d = { { { 42 } } }
func test2(_ a: Int, b: Int) -> (c: Int) { // expected-error{{cannot create a single-element tuple with an element label}} {{34-37=}} expected-note {{did you mean 'a'?}} expected-note {{did you mean 'b'?}}
_ = a+b
a+b+c // expected-error{{use of unresolved identifier 'c'}}
return a+b
}
func test3(_ arg1: Int, arg2: Int) -> Int {
return 4
}
func test4() -> ((_ arg1: Int, _ arg2: Int) -> Int) {
return test3
}
func test5() {
let a: (Int, Int) = (1,2)
var
_: ((Int) -> Int, Int) = a // expected-error {{cannot convert value of type '(Int, Int)' to specified type '((Int) -> Int, Int)'}}
let c: (a: Int, b: Int) = (1,2)
let _: (b: Int, a: Int) = c // Ok, reshuffle tuple.
}
// Functions can obviously take and return values.
func w3(_ a: Int) -> Int { return a }
func w4(_: Int) -> Int { return 4 }
func b1() {}
func foo1(_ a: Int, b: Int) -> Int {}
func foo2(_ a: Int) -> (_ b: Int) -> Int {}
func foo3(_ a: Int = 2, b: Int = 3) {}
prefix operator ^^
prefix func ^^(a: Int) -> Int {
return a + 1
}
func test_unary1() {
var x: Int
x = ^^(^^x)
x = *x // expected-error {{'*' is not a prefix unary operator}}
x = x* // expected-error {{'*' is not a postfix unary operator}}
x = +(-x)
x = + -x // expected-error {{unary operator cannot be separated from its operand}} {{8-9=}}
}
func test_unary2() {
var x: Int
// FIXME: second diagnostic is redundant.
x = &; // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}}
}
func test_unary3() {
var x: Int
// FIXME: second diagnostic is redundant.
x = &, // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}}
}
func test_as_1() {
var _: Int
}
func test_as_2() {
let x: Int = 1
x as [] // expected-error {{expected element type}} {{9-9= <#type#>}}
}
func test_lambda() {
// A simple closure.
var a = { (value: Int) -> () in markUsed(value+1) }
// A recursive lambda.
// FIXME: This should definitely be accepted.
var fib = { (n: Int) -> Int in
if (n < 2) {
return n
}
return fib(n-1)+fib(n-2) // expected-error 2 {{variable used within its own initial value}}
}
}
func test_lambda2() {
{ () -> protocol<Int> in
// expected-warning @-1 {{'protocol<...>' composition syntax is deprecated and not needed here}} {{11-24=Int}}
// expected-error @-2 {{non-protocol, non-class type 'Int' cannot be used within a protocol-constrained type}}
// expected-warning @-3 {{result of call to closure returning 'Any' is unused}}
return 1
}()
}
func test_floating_point() {
_ = 0.0
_ = 100.1
var _: Float = 0.0
var _: Double = 0.0
}
func test_nonassoc(_ x: Int, y: Int) -> Bool {
// FIXME: the second error and note here should arguably disappear
return x == y == x // expected-error {{adjacent operators are in non-associative precedence group 'ComparisonPrecedence'}} expected-error {{binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '==' exist with these partially matching parameter lists:}}
}
// More realistic examples.
func fib(_ n: Int) -> Int {
if (n < 2) {
return n
}
return fib(n-2) + fib(n-1)
}
//===----------------------------------------------------------------------===//
// Integer Literals
//===----------------------------------------------------------------------===//
// FIXME: Should warn about integer constants being too large <rdar://problem/14070127>
var
il_a: Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}}
var il_b: Int8
= 123123
var il_c: Int8 = 4 // ok
struct int_test4 : ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral value: Int) {} // user type.
}
var il_g: int_test4 = 4
// This just barely fits in Int64.
var il_i: Int64 = 18446744073709551615
// This constant is too large to fit in an Int64, but it is fine for Int128.
// FIXME: Should warn about the first. <rdar://problem/14070127>
var il_j: Int64 = 18446744073709551616
// var il_k: Int128 = 18446744073709551616
var bin_literal: Int64 = 0b100101
var hex_literal: Int64 = 0x100101
var oct_literal: Int64 = 0o100101
// verify that we're not using C rules
var oct_literal_test: Int64 = 0123
assert(oct_literal_test == 123)
// ensure that we swallow random invalid chars after the first invalid char
var invalid_num_literal: Int64 = 0QWERTY // expected-error{{'Q' is not a valid digit in integer literal}}
var invalid_bin_literal: Int64 = 0bQWERTY // expected-error{{'Q' is not a valid binary digit (0 or 1) in integer literal}}
var invalid_hex_literal: Int64 = 0xQWERTY // expected-error{{'Q' is not a valid hexadecimal digit (0-9, A-F) in integer literal}}
var invalid_oct_literal: Int64 = 0oQWERTY // expected-error{{'Q' is not a valid octal digit (0-7) in integer literal}}
var invalid_exp_literal: Double = 1.0e+QWERTY // expected-error{{'Q' is not a valid digit in floating point exponent}}
var invalid_fp_exp_literal: Double = 0x1p+QWERTY // expected-error{{'Q' is not a valid digit in floating point exponent}}
// don't emit a partial integer literal if the invalid char is valid for identifiers.
var invalid_num_literal_prefix: Int64 = 0a1234567 // expected-error{{'a' is not a valid digit in integer literal}}
var invalid_num_literal_middle: Int64 = 0123A5678 // expected-error{{'A' is not a valid digit in integer literal}}
var invalid_bin_literal_middle: Int64 = 0b1020101 // expected-error{{'2' is not a valid binary digit (0 or 1) in integer literal}}
var invalid_oct_literal_middle: Int64 = 0o1357864 // expected-error{{'8' is not a valid octal digit (0-7) in integer literal}}
var invalid_hex_literal_middle: Int64 = 0x147ADG0 // expected-error{{'G' is not a valid hexadecimal digit (0-9, A-F) in integer literal}}
var invalid_hex_literal_exponent_ = 0xffp+12abc // expected-error{{'a' is not a valid digit in floating point exponent}}
var invalid_float_literal_exponent = 12e1abc // expected-error{{'a' is not a valid digit in floating point exponent}}
// rdar://11088443
var negative_int32: Int32 = -1
// <rdar://problem/11287167>
var tupleelemvar = 1
markUsed((tupleelemvar, tupleelemvar).1)
func int_literals() {
// Fits exactly in 64-bits - rdar://11297273
_ = 1239123123123123
// Overly large integer.
// FIXME: Should warn about it. <rdar://problem/14070127>
_ = 123912312312312312312
}
// <rdar://problem/12830375>
func tuple_of_rvalues(_ a:Int, b:Int) -> Int {
return (a, b).1
}
extension Int {
func testLexingMethodAfterIntLiteral() {}
func _0() {}
// Hex letters
func ffa() {}
// Hex letters + non hex.
func describe() {}
// Hex letters + 'p'.
func eap() {}
// Hex letters + 'p' + non hex.
func fpValue() {}
}
123.testLexingMethodAfterIntLiteral()
0b101.testLexingMethodAfterIntLiteral()
0o123.testLexingMethodAfterIntLiteral()
0x1FFF.testLexingMethodAfterIntLiteral()
123._0()
0b101._0()
0o123._0()
0x1FFF._0()
0x1fff.ffa()
0x1FFF.describe()
0x1FFF.eap()
0x1FFF.fpValue()
var separator1: Int = 1_
var separator2: Int = 1_000
var separator4: Int = 0b1111_0000_
var separator5: Int = 0b1111_0000
var separator6: Int = 0o127_777_
var separator7: Int = 0o127_777
var separator8: Int = 0x12FF_FFFF
var separator9: Int = 0x12FF_FFFF_
//===----------------------------------------------------------------------===//
// Float Literals
//===----------------------------------------------------------------------===//
var fl_a = 0.0
var fl_b: Double = 1.0
var fl_c: Float = 2.0
// FIXME: crummy diagnostic
var fl_d: Float = 2.0.0 // expected-error {{expected named member of numeric literal}}
var fl_e: Float = 1.0e42
var fl_f: Float = 1.0e+ // expected-error {{expected a digit in floating point exponent}}
var fl_g: Float = 1.0E+42
var fl_h: Float = 2e-42
var vl_i: Float = -.45 // expected-error {{'.45' is not a valid floating point literal; it must be written '0.45'}} {{20-20=0}}
var fl_j: Float = 0x1p0
var fl_k: Float = 0x1.0p0
var fl_l: Float = 0x1.0 // expected-error {{hexadecimal floating point literal must end with an exponent}}
var fl_m: Float = 0x1.FFFFFEP-2
var fl_n: Float = 0x1.fffffep+2
var fl_o: Float = 0x1.fffffep+ // expected-error {{expected a digit in floating point exponent}}
var fl_p: Float = 0x1p // expected-error {{expected a digit in floating point exponent}}
var fl_q: Float = 0x1p+ // expected-error {{expected a digit in floating point exponent}}
var fl_r: Float = 0x1.0fp // expected-error {{expected a digit in floating point exponent}}
var fl_s: Float = 0x1.0fp+ // expected-error {{expected a digit in floating point exponent}}
var fl_t: Float = 0x1.p // expected-error {{value of type 'Int' has no member 'p'}}
var fl_u: Float = 0x1.p2 // expected-error {{value of type 'Int' has no member 'p2'}}
var fl_v: Float = 0x1.p+ // expected-error {{'+' is not a postfix unary operator}}
var fl_w: Float = 0x1.p+2 // expected-error {{value of type 'Int' has no member 'p'}}
var if1: Double = 1.0 + 4 // integer literal ok as double.
var if2: Float = 1.0 + 4 // integer literal ok as float.
var fl_separator1: Double = 1_.2_
var fl_separator2: Double = 1_000.2_
var fl_separator3: Double = 1_000.200_001
var fl_separator4: Double = 1_000.200_001e1_
var fl_separator5: Double = 1_000.200_001e1_000
var fl_separator6: Double = 1_000.200_001e1_000
var fl_separator7: Double = 0x1_.0FFF_p1_
var fl_separator8: Double = 0x1_0000.0FFF_ABCDp10_001
var fl_bad_separator1: Double = 1e_ // expected-error {{'_' is not a valid first character in floating point exponent}}
var fl_bad_separator2: Double = 0x1p_ // expected-error {{'_' is not a valid first character in floating point exponent}}
//===----------------------------------------------------------------------===//
// String Literals
//===----------------------------------------------------------------------===//
var st_a = ""
var st_b: String = ""
var st_c = "asdfasd // expected-error {{unterminated string literal}}
var st_d = " \t\n\r\"\'\\ " // Valid simple escapes
var st_e = " \u{12}\u{0012}\u{00000078} " // Valid unicode escapes
var st_u1 = " \u{1} "
var st_u2 = " \u{123} "
var st_u3 = " \u{1234567} " // expected-error {{invalid unicode scalar}}
var st_u4 = " \q " // expected-error {{invalid escape sequence in literal}}
var st_u5 = " \u{FFFFFFFF} " // expected-error {{invalid unicode scalar}}
var st_u6 = " \u{D7FF} \u{E000} " // Fencepost UTF-16 surrogate pairs.
var st_u7 = " \u{D800} " // expected-error {{invalid unicode scalar}}
var st_u8 = " \u{DFFF} " // expected-error {{invalid unicode scalar}}
var st_u10 = " \u{0010FFFD} " // Last valid codepoint, 0xFFFE and 0xFFFF are reserved in each plane
var st_u11 = " \u{00110000} " // expected-error {{invalid unicode scalar}}
func stringliterals(_ d: [String: Int]) {
// rdar://11385385
let x = 4
"Hello \(x+1) world" // expected-warning {{string literal is unused}}
"Error: \(x+1"; // expected-error {{unterminated string literal}}
"Error: \(x+1 // expected-error {{unterminated string literal}}
; // expected-error {{';' statements are not allowed}}
// rdar://14050788 [DF] String Interpolations can't contain quotes
"test \("nested")"
"test \("\("doubly nested")")"
"test \(d["hi"])"
"test \("quoted-paren )")"
"test \("quoted-paren (")"
"test \("\\")"
"test \("\n")"
"test \("\")" // expected-error {{unterminated string literal}}
"test \
// expected-error @-1 {{unterminated string literal}} expected-error @-1 {{invalid escape sequence in literal}}
"test \("\
// expected-error @-1 {{unterminated string literal}}
"test newline \("something" +
"something else")"
// expected-error @-2 {{unterminated string literal}} expected-error @-1 {{unterminated string literal}}
// expected-warning @+2 {{variable 'x2' was never used; consider replacing with '_' or removing it}}
// expected-error @+1 {{unterminated string literal}}
var x2 : () = ("hello" + "
;
}
func testSingleQuoteStringLiterals() {
_ = 'abc' // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}}
_ = 'abc' + "def" // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}}
_ = 'ab\nc' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\nc"}}
_ = "abc\('def')" // expected-error{{single-quoted string literal found, use '"'}}{{13-18="def"}}
_ = "abc' // expected-error{{unterminated string literal}}
_ = 'abc" // expected-error{{unterminated string literal}}
_ = "a'c"
_ = 'ab\'c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab'c"}}
_ = 'ab"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-13="ab\\"c"}}
_ = 'ab\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\"c"}}
_ = 'ab\\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-15="ab\\\\\\"c"}}
}
// <rdar://problem/17128913>
var s = ""
s.append(contentsOf: ["x"])
//===----------------------------------------------------------------------===//
// InOut arguments
//===----------------------------------------------------------------------===//
func takesInt(_ x: Int) {}
func takesExplicitInt(_ x: inout Int) { }
func testInOut(_ arg: inout Int) {
var x: Int
takesExplicitInt(x) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
takesExplicitInt(&x)
takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}}
var y = &x //expected-error {{use of extraneous '&'}}
var z = &arg //expected-error {{use of extraneous '&'}}
takesExplicitInt(5) // expected-error {{cannot pass immutable value as inout argument: literals are not mutable}}
}
//===----------------------------------------------------------------------===//
// Conversions
//===----------------------------------------------------------------------===//
var pi_f: Float
var pi_d: Double
struct SpecialPi {} // Type with no implicit construction.
var pi_s: SpecialPi
func getPi() -> Float {} // expected-note 3 {{found this candidate}}
func getPi() -> Double {} // expected-note 3 {{found this candidate}}
func getPi() -> SpecialPi {}
enum Empty { }
extension Empty {
init(_ f: Float) { }
}
func conversionTest(_ a: inout Double, b: inout Int) {
var f: Float
var d: Double
a = Double(b)
a = Double(f)
a = Double(d) // no-warning
b = Int(a)
f = Float(b)
var pi_f1 = Float(pi_f)
var pi_d1 = Double(pi_d)
var pi_s1 = SpecialPi(pi_s) // expected-error {{argument passed to call that takes no arguments}}
var pi_f2 = Float(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_d2 = Double(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_s2: SpecialPi = getPi() // no-warning
var float = Float.self
var pi_f3 = float.init(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_f4 = float.init(pi_f)
var e = Empty(f)
var e2 = Empty(d) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Float'}}
var e3 = Empty(Float(d))
}
struct Rule { // expected-note {{'init(target:dependencies:)' declared here}}
var target: String
var dependencies: String
}
var ruleVar: Rule
ruleVar = Rule("a") // expected-error {{missing argument for parameter 'dependencies' in call}}
class C {
var x: C?
init(other: C?) { x = other }
func method() {}
}
_ = C(3) // expected-error {{missing argument label 'other:' in call}}
_ = C(other: 3) // expected-error {{cannot convert value of type 'Int' to expected argument type 'C?'}}
//===----------------------------------------------------------------------===//
// Unary Operators
//===----------------------------------------------------------------------===//
func unaryOps(_ i8: inout Int8, i64: inout Int64) {
i8 = ~i8
i64 += 1
i8 -= 1
Int64(5) += 1 // expected-error{{left side of mutating operator isn't mutable: function call returns immutable value}}
// <rdar://problem/17691565> attempt to modify a 'let' variable with ++ results in typecheck error not being able to apply ++ to Float
let a = i8 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
a += 1 // expected-error {{left side of mutating operator isn't mutable: 'a' is a 'let' constant}}
var b : Int { get { }}
b += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a get-only property}}
}
//===----------------------------------------------------------------------===//
// Iteration
//===----------------------------------------------------------------------===//
func..<(x: Double, y: Double) -> Double {
return x + y
}
func iterators() {
_ = 0..<42
_ = 0.0..<42.0
}
//===----------------------------------------------------------------------===//
// Magic literal expressions
//===----------------------------------------------------------------------===//
func magic_literals() {
_ = __FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}}
_ = __LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}}
_ = __COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}}
_ = __DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}}
_ = #file
_ = #line + #column
var _: UInt8 = #line + #column
}
//===----------------------------------------------------------------------===//
// lvalue processing
//===----------------------------------------------------------------------===//
infix operator +-+=
@discardableResult
func +-+= (x: inout Int, y: Int) -> Int { return 0}
func lvalue_processing() {
var i = 0
i += 1 // obviously ok
var fn = (+-+=)
var n = 42
fn(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{6-6=&}}
fn(&n, 12) // expected-warning {{result of call to function returning 'Int' is unused}}
n +-+= 12
(+-+=)(&n, 12) // ok.
(+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
}
struct Foo {
func method() {}
mutating func mutatingMethod() {}
}
func test() {
var x = Foo()
let y = Foo()
// rdar://15708430
(&x).method() // expected-error {{use of extraneous '&'}}
(&x).mutatingMethod() // expected-error {{use of extraneous '&'}}
}
// Unused results.
func unusedExpressionResults() {
// Unused l-value
_ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}}
// <rdar://problem/20749592> Conditional Optional binding hides compiler error
let optionalc:C? = nil
optionalc?.method() // ok
optionalc?.method // expected-error {{expression resolves to an unused function}}
}
//===----------------------------------------------------------------------===//
// Collection Literals
//===----------------------------------------------------------------------===//
func arrayLiterals() {
let _ = [1,2,3]
let _ : [Int] = []
let _ = [] // expected-error {{empty collection literal requires an explicit type}}
}
func dictionaryLiterals() {
let _ = [1 : "foo",2 : "bar",3 : "baz"]
let _: Dictionary<Int, String> = [:]
let _ = [:] // expected-error {{empty collection literal requires an explicit type}}
}
func invalidDictionaryLiteral() {
// FIXME: lots of unnecessary diagnostics.
var a = [1: ; // expected-error {{expected value in dictionary literal}}
var b = [1: ;] // expected-error {{expected value in dictionary literal}}
var c = [1: "one" ;] // expected-error {{expected key expression in dictionary literal}} expected-error {{expected ',' separator}} {{20-20=,}}
var d = [1: "one", ;] // expected-error {{expected key expression in dictionary literal}}
var e = [1: "one", 2] // expected-error {{expected ':' in dictionary literal}}
var f = [1: "one", 2 ;] // expected-error {{expected ':' in dictionary literal}}
var g = [1: "one", 2: ;] // expected-error {{expected value in dictionary literal}}
}
// FIXME: The issue here is a type compatibility problem, there is no ambiguity.
[4].joined(separator: [1]) // expected-error {{type of expression is ambiguous without more context}}
[4].joined(separator: [[[1]]]) // expected-error {{type of expression is ambiguous without more context}}
//===----------------------------------------------------------------------===//
// nil/metatype comparisons
//===----------------------------------------------------------------------===//
_ = Int.self == nil // expected-warning {{comparing non-optional value of type 'Any.Type' to 'nil' always returns false}}
_ = nil == Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to 'nil' always returns false}}
_ = Int.self != nil // expected-warning {{comparing non-optional value of type 'Any.Type' to 'nil' always returns true}}
_ = nil != Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to 'nil' always returns true}}
// <rdar://problem/19032294> Disallow postfix ? when not chaining
func testOptionalChaining(_ a : Int?, b : Int!, c : Int??) {
_ = a? // expected-error {{optional chain has no effect, expression already produces 'Int?'}} {{8-9=}}
_ = a?.customMirror
_ = b? // expected-error {{optional chain has no effect, expression already produces 'Int?'}}
_ = b?.customMirror
var _: Int? = c? // expected-error {{'?' must be followed by a call, member lookup, or subscript}}
}
// <rdar://problem/19657458> Nil Coalescing operator (??) should have a higher precedence
func testNilCoalescePrecedence(cond: Bool, a: Int?, r: ClosedRange<Int>?) {
// ?? should have higher precedence than logical operators like || and comparisons.
if cond || (a ?? 42 > 0) {} // Ok.
if (cond || a) ?? 42 > 0 {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}}
if (cond || a) ?? (42 > 0) {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}}
if cond || a ?? 42 > 0 {} // Parses as the first one, not the others.
// ?? should have lower precedence than range and arithmetic operators.
let r1 = r ?? (0...42) // ok
let r2 = (r ?? 0)...42 // not ok: expected-error {{cannot convert value of type 'Int' to expected argument type 'ClosedRange<Int>'}}
let r3 = r ?? 0...42 // parses as the first one, not the second.
// <rdar://problem/27457457> [Type checker] Diagnose unsavory optional injections
// Accidental optional injection for ??.
let i = 42
_ = i ?? 17 // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Int', so the right side is never used}} {{9-15=}}
}
// <rdar://problem/19772570> Parsing of as and ?? regressed
func testOptionalTypeParsing(_ a : AnyObject) -> String {
return a as? String ?? "default name string here"
}
func testParenExprInTheWay() {
let x = 42
if x & 4.0 {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}}
if (x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}}
if !(x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}}
//expected-note @-1 {{expected an argument list of type '(Int, Int)'}}
if x & x {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/21352576> Mixed method/property overload groups can cause a crash during constraint optimization
public struct TestPropMethodOverloadGroup {
public typealias Hello = String
public let apply:(Hello) -> Int
public func apply(_ input:Hello) -> Int {
return apply(input)
}
}
// <rdar://problem/18496742> Passing ternary operator expression as inout crashes Swift compiler
func inoutTests(_ arr: inout Int) {
var x = 1, y = 2
(true ? &x : &y) // expected-error 2 {{use of extraneous '&'}}
let a = (true ? &x : &y) // expected-error 2 {{use of extraneous '&'}}
inoutTests(true ? &x : &y) // expected-error {{use of extraneous '&'}}
&_ // expected-error {{use of extraneous '&'}}
inoutTests((&x, 24).0) // expected-error {{use of extraneous '&'}}
inoutTests((&x)) // expected-error {{use of extraneous '&'}}
inoutTests(&x)
// <rdar://problem/17489894> inout not rejected as operand to assignment operator
&x += y // expected-error {{'&' can only appear immediately in a call argument list}}}
// <rdar://problem/23249098>
func takeAny(_ x: Any) {}
takeAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
func takeManyAny(_ x: Any...) {}
takeManyAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
takeManyAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
func takeIntAndAny(_ x: Int, _ y: Any) {}
takeIntAndAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
}
// <rdar://problem/20802757> Compiler crash in default argument & inout expr
var g20802757 = 2
func r20802757(_ z: inout Int = &g20802757) { // expected-error {{use of extraneous '&'}}
print(z)
}
_ = _.foo // expected-error {{type of expression is ambiguous without more context}}
// <rdar://problem/22211854> wrong arg list crashing sourcekit
func r22211854() {
func f(_ x: Int, _ y: Int, _ z: String = "") {} // expected-note 2 {{'f' declared here}}
func g<T>(_ x: T, _ y: T, _ z: String = "") {} // expected-note 2 {{'g' declared here}}
f(1) // expected-error{{missing argument for parameter #2 in call}}
g(1) // expected-error{{missing argument for parameter #2 in call}}
func h() -> Int { return 1 }
f(h() == 1) // expected-error{{missing argument for parameter #2 in call}}
g(h() == 1) // expected-error{{missing argument for parameter #2 in call}}
}
// <rdar://problem/22348394> Compiler crash on invoking function with labeled defaulted param with non-labeled argument
func r22348394() {
func f(x: Int = 0) { }
f(Int(3)) // expected-error{{missing argument label 'x:' in call}}
}
// <rdar://problem/23185177> Compiler crashes in Assertion failed: ((AllowOverwrite || !E->hasLValueAccessKind()) && "l-value access kind has already been set"), function visit
protocol P { var y: String? { get } }
func r23185177(_ x: P?) -> [String] {
return x?.y // expected-error{{cannot convert return expression of type 'String?' to return type '[String]'}}
}
// <rdar://problem/22913570> Miscompile: wrong argument parsing when calling a function in swift2.0
func r22913570() {
func f(_ from: Int = 0, to: Int) {} // expected-note {{'f(_:to:)' declared here}}
f(1 + 1) // expected-error{{missing argument for parameter 'to' in call}}
}
// SR-628 mixing lvalues and rvalues in tuple expression
var x = 0
var y = 1
let _ = (x, x + 1).0
let _ = (x, 3).1
(x,y) = (2,3)
(x,4) = (1,2) // expected-error {{expression is not assignable: literals are not mutable}}
(x,y).1 = 7 // expected-error {{cannot assign to immutable expression of type 'Int'}}
x = (x,(3,y)).1.1
// SR-3439 subscript with pound exprssions.
Sr3439: do {
class B {
init() {}
subscript(x: Int) -> Int { return x }
subscript(x: String) -> String { return x }
func foo() {
_ = self[#line] // Ok.
}
}
class C : B {
func bar() {
_ = super[#file] // Ok.
}
}
let obj = C();
_ = obj[#column] // Ok.
}
| apache-2.0 | 97af43253c2114fc290f51bfa074de16 | 37.086623 | 310 | 0.60927 | 3.593524 | false | true | false | false |
YQqiang/Nunchakus | Nunchakus/Nunchakus/Services/SelfieModel.swift | 1 | 1110 | //
// SelfieModel.swift
// Nunchakus
//
// Created by sungrow on 2017/3/22.
// Copyright © 2017年 sungrow. All rights reserved.
//
import UIKit
import Kanna
class SelfieModel: BaseModel {
var title: String?
var video: String?
var img: String?
var time: String?
override init(html: XMLElement) {
super.init(html: html)
self.time = html.at_xpath("span")?.content
guard let a = html.at_xpath("a") else {
return
}
self.title = a["title"]
self.video = a["href"]
if let imgNode = a.at_xpath("img") {
img = imgNode["src"]
}
}
}
extension SelfieModel {
class func isHaveNextPage(html: XPathObject) -> Bool {
let maxCount = html[html.count - 1]["href"]?.components(separatedBy: "/")
guard let maxC = maxCount, maxC.count >= 2 else {
return false
}
let max = maxC[maxC.count - 2]
for a in html {
if (a.className == "now") {
return max != (a.content ?? "1")
}
}
return false
}
}
| mit | ff7792e07d3e987a241ebbd5e715f6eb | 23.065217 | 81 | 0.531165 | 3.677741 | false | false | false | false |
jerkoch/SwipeCellKit | Source/SwipeExpanding.swift | 11 | 4352 | //
// SwipeExpanding.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
/**
Adopt the `SwipeExpanding` protocol in objects that implement custom appearance of actions during expansion.
*/
public protocol SwipeExpanding {
/**
Asks your object for the animation timing parameters.
- parameter buttons: The expansion action button, which includes expanding action plus the remaining actions in the view.
- parameter expanding: The new expansion state.
- parameter otherActionButtons: The other action buttons in the view, not including the action button being expanded.
*/
func animationTimingParameters(buttons: [UIButton], expanding: Bool) -> SwipeExpansionAnimationTimingParameters
/**
Tells your object when the expansion state is changing.
- parameter button: The expansion action button.
- parameter expanding: The new expansion state.
- parameter otherActionButtons: The other action buttons in the view, not including the action button being expanded.
*/
func actionButton(_ button: UIButton, didChange expanding: Bool, otherActionButtons: [UIButton])
}
/**
Specifies timing information for the overall expansion animation.
*/
public struct SwipeExpansionAnimationTimingParameters {
/// Returns a `SwipeExpansionAnimationTimingParameters` instance with default animation parameters.
public static var `default`: SwipeExpansionAnimationTimingParameters { return SwipeExpansionAnimationTimingParameters() }
/// The duration of the expansion animation.
public var duration: Double
/// The delay before starting the expansion animation.
public var delay: Double
/**
Contructs a new `SwipeExpansionAnimationTimingParameters` instance.
- parameter duration: The duration of the animation.
- parameter delay: The delay before starting the expansion animation.
- returns: The new `SwipeExpansionAnimationTimingParameters` instance.
*/
public init(duration: Double = 0.6, delay: Double = 0) {
self.duration = duration
self.delay = delay
}
}
/**
A scale and alpha expansion object drives the custom appearance of the effected actions during expansion.
*/
public struct ScaleAndAlphaExpansion: SwipeExpanding {
/// Returns a `ScaleAndAlphaExpansion` instance with default expansion options.
public static var `default`: ScaleAndAlphaExpansion { return ScaleAndAlphaExpansion() }
/// The duration of the animation.
public let duration: Double
/// The scale factor used during animation.
public let scale: CGFloat
/// The inter-button delay between animations.
public let interButtonDelay: Double
/**
Contructs a new `ScaleAndAlphaExpansion` instance.
- parameter duration: The duration of the animation.
- parameter scale: The scale factor used during animation.
- parameter interButtonDelay: The inter-button delay between animations.
- returns: The new `ScaleAndAlphaExpansion` instance.
*/
public init(duration: Double = 0.15, scale: CGFloat = 0.8, interButtonDelay: Double = 0.1) {
self.duration = duration
self.scale = scale
self.interButtonDelay = interButtonDelay
}
/// :nodoc:
public func animationTimingParameters(buttons: [UIButton], expanding: Bool) -> SwipeExpansionAnimationTimingParameters {
var timingParameters = SwipeExpansionAnimationTimingParameters.default
timingParameters.delay = expanding ? interButtonDelay : 0
return timingParameters
}
/// :nodoc:
public func actionButton(_ button: UIButton, didChange expanding: Bool, otherActionButtons: [UIButton]) {
let buttons = expanding ? otherActionButtons : otherActionButtons.reversed()
buttons.enumerated().forEach { index, button in
UIView.animate(withDuration: duration, delay: interButtonDelay * Double(expanding ? index : index + 1), options: [], animations: {
button.transform = expanding ? .init(scaleX: self.scale, y: self.scale) : .identity
button.alpha = expanding ? 0.0 : 1.0
}, completion: nil)
}
}
}
| mit | 5dad1deb99846ca39a764b246ce27a10 | 35.258333 | 142 | 0.696851 | 5.173603 | false | false | false | false |
bencochran/SpringExperiment | BouncyDemo/ViewController.swift | 1 | 1062 | //
// ViewController.swift
// Bounce
//
// Created by Ben Cochran on 9/12/15.
// Copyright © 2015 Ben Cochran. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private static var numberFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
return formatter
}()
@IBOutlet var bounceView: BounceView!
@IBOutlet var tensionLabel: UILabel!
@IBOutlet var frictionLabel: UILabel!
@IBAction func handleGesture(sender: UIGestureRecognizer) {
bounceView.animateTo(sender.locationInView(bounceView))
}
@IBAction func handleTension(sender: UISlider) {
bounceView.tension = Double(sender.value)
tensionLabel.text = ViewController.numberFormatter.stringFromNumber(sender.value)
}
@IBAction func handleFriction(sender: UISlider) {
bounceView.friction = Double(sender.value)
frictionLabel.text = ViewController.numberFormatter.stringFromNumber(sender.value)
}
}
| bsd-3-clause | 6658d9868c4825f8e861147981b15c9f | 28.472222 | 90 | 0.701225 | 4.715556 | false | false | false | false |
weirdindiankid/Tinder-Clone | TinderClone/Tabs/SettingsViewController.swift | 1 | 18288 | //
// SettingsViewController.swift
// TinderClone
//
// Created by Dharmesh Tarapore on 20/01/2015.
// Copyright (c) 2015 Dharmesh Tarapore. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate {
var pickerContainer = UIView()
var picker = UIDatePicker()
var updatedProfilePicture = false
var selecteProfilePicture = UIImage()
@IBOutlet weak var scrollViewContainer: UIScrollView!
@IBOutlet weak var profilePictureView: UIImageView!
@IBOutlet weak var textfieldUserName: UITextField!
@IBOutlet weak var textfieldEmailAddress: UITextField!
@IBOutlet weak var textfieldPassword: UITextField!
@IBOutlet weak var buttonDateOfBirth: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.updateUI()
self.fillUserDetails()
self.configurePicker()
updatedProfilePicture = false
}
func updateUI()
{
var frame = self.view.frame
frame = self.scrollViewContainer.frame
frame.size.height = 200
self.scrollViewContainer.frame = CGRectMake(0.0, self.scrollViewContainer.frame.origin.y, 320.0, 447.0)
// self.scrollViewContainer.hidden = true
self.scrollViewContainer.contentSize = CGSizeMake(320.0, 684.0)
}
func fillUserDetails()
{
let user = PFUser.currentUser() as PFUser
self.textfieldUserName.text = user.username
self.textfieldEmailAddress.text = user.email
// self.textfieldPassword.text = "ddd"
let dob = user["dobstring"] as String
self.buttonDateOfBirth.setTitle(dob, forState: UIControlState.Normal)
let gender = user["gender"] as String
var button1 = self.view.viewWithTag(1) as UIButton
var button2 = self.view.viewWithTag(2) as UIButton
if (gender == "male")
{
button1.selected = true
button2.selected = false
}
else
{
button1.selected = false
button2.selected = true
}
let interestedIn = user["interestedin"] as String
button1 = self.view.viewWithTag(3) as UIButton
button2 = self.view.viewWithTag(4) as UIButton
if (interestedIn == "male")
{
button1.selected = true
button2.selected = false
}
else
{
button1.selected = false
button2.selected = true
}
var query = PFQuery(className: "UserPhoto")
query.whereKey("user", equalTo: user)
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
query.findObjectsInBackgroundWithBlock{
(NSArray objects, NSError error) -> Void in
if(objects.count != 0)
{
let object = objects[objects.count - 1] as PFObject
let theImage = object["imageData"] as PFFile
println(theImage)
if (theImage.isDataAvailable) {
let imageData:NSData = theImage.getData()
let image = UIImage(data: imageData)
self.profilePictureView.image = image
}
/*
var imageDownloadQueue = dispatch_queue_create("downloadimage", DISPATCH_QUEUE_PRIORITY_DEFAULT)
dispatch_async(imageDownloadQueue, {
let imageData:NSData = theImage.getData()
let image = UIImage(data: imageData)
dispatch_async(dispatch_get_main_queue(), {
self.profilePictureView.image = image
})
})
*/
}
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func chooseProfilePicture(sender: UIButton)
{
let myActionSheet = UIActionSheet()
myActionSheet.delegate = self
myActionSheet.addButtonWithTitle("Camera")
myActionSheet.addButtonWithTitle("Photo Library")
myActionSheet.addButtonWithTitle("Cancel")
myActionSheet.cancelButtonIndex = 2
myActionSheet.showInView(self.view)
}
func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int)
{
var sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.Camera
if (buttonIndex == 0)
{
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) //Camera not available
{
sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
self.displayImagepicker(sourceType)
}
else if (buttonIndex == 1)
{
sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.displayImagepicker(sourceType)
}
}
func displayImagepicker(sourceType:UIImagePickerControllerSourceType)
{
var imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!)
{
self.dismissViewControllerAnimated(true, completion: {
var mediatype:NSString = info[UIImagePickerControllerMediaType]! as NSString
if (mediatype == "public.image")
{
let originalImage = info[UIImagePickerControllerOriginalImage] as UIImage
print("%@",originalImage.size)
self.profilePictureView.image = self.resizeImage(originalImage, toSize: CGSizeMake(134.0, 144.0))
self.selecteProfilePicture = self.resizeImage(originalImage, toSize: CGSizeMake(320.0, 480.0))
self.updatedProfilePicture = true
}
})
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!)
{
picker.dismissViewControllerAnimated(true, completion: nil)
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int)
{
if (alertView.tag == 10)
{
if(buttonIndex == 1)
{
FBSession.activeSession().closeAndClearTokenInformation()
let user = PFUser.currentUser() as PFUser
PFUser.logOut()
self.tabBarController!.dismissViewControllerAnimated(true, completion: nil)
}
}
else
{
self.navigationController!.popToRootViewControllerAnimated(true)
}
}
@IBAction func changeDateOfBirth(sender: AnyObject)
{
self.textfieldUserName.resignFirstResponder()
self.textfieldEmailAddress.resignFirstResponder()
self.textfieldPassword.resignFirstResponder()
UIView.animateWithDuration(0.4, animations: {
var frame:CGRect = self.pickerContainer.frame
frame.origin.y = self.view.frame.size.height - 300.0 + 40
self.pickerContainer.frame = frame
})
}
@IBAction func selectGender(sender: UIButton)
{
if (sender.tag == 1)
{
sender.selected = true
let female = self.view.viewWithTag(2) as UIButton
female.selected = false
}
else if (sender.tag == 2)
{
sender.selected = true
let male = self.view.viewWithTag(1) as UIButton
male.selected = false
}
}
@IBAction func interestedIn(sender: UIButton)
{
if (sender.tag == 3)
{
sender.selected = true
let female = self.view.viewWithTag(4) as UIButton
female.selected = false
}
else if (sender.tag == 4)
{
sender.selected = true
let male = self.view.viewWithTag(3) as UIButton
male.selected = false
}
}
@IBAction func updateMyProfile(sender : UIButton)
{
if (checkMandatoryFieldsAreSet())
{
sender.enabled = false
var user = PFUser.currentUser()
user.username = self.textfieldUserName.text
user.password = self.textfieldPassword.text
user.email = self.textfieldEmailAddress.text
let dateOfBirth = self.buttonDateOfBirth.titleForState(UIControlState.Normal)
user["dobstring"] = dateOfBirth
var button1 = self.view.viewWithTag(1) as UIButton
var button2 = self.view.viewWithTag(2) as UIButton
user["gender"] = button1.selected ? "male" : "female"
button1 = self.view.viewWithTag(3) as UIButton
button2 = self.view.viewWithTag(4) as UIButton
user["interestedin"] = button1.selected ? "male" : "female"
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
user.saveInBackgroundWithBlock(
{
(BOOL succeeded, NSError error) -> Void in
if (error == nil)
{
if (self.updatedProfilePicture)
{
let imageName = self.textfieldUserName.text + ".jpg" as String
let userPhoto = PFObject(className: "UserPhoto")
let imageData = UIImagePNGRepresentation(self.selecteProfilePicture)
let imageFile = PFFile(name:imageName, data:imageData)
userPhoto["imageFile"] = imageName
userPhoto["imageData"] = imageFile
userPhoto["user"] = user
userPhoto.saveInBackgroundWithBlock{
(succeeded:Bool!, error:NSError!) -> Void in
if (error != nil)
{
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: "Successfully updated profile.", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
else
{
// if let errorString = error.userInfo["error"]? as NSString
// {
// println(errorString)
// }
}
sender.enabled = true
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
self.updatedProfilePicture = false
}
else
{
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: "Successfully updated profile.", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
sender.enabled = true
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
}
})
// user.signUpInBackgroundWithBlock {
/*
(succeeded: Bool!, error: NSError!) -> Void in
if !error
{
let imageName = self.userName + ".jpg" as String
let userPhoto = PFObject(className: "UserPhoto")
let imageData = UIImagePNGRepresentation(self.selecteProfilePicture)
let imageFile = PFFile(name:imageName, data:imageData)
userPhoto["imageFile"] = imageName
userPhoto["imageData"] = imageFile
userPhoto["user"] = user
userPhoto.saveInBackgroundWithBlock{
(succeeded:Bool!, error:NSError!) -> Void in
if !error
{
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: "Successfully Signed Up. Please login using your Email address and Password.", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
else
{
// if let errorString = error.userInfo["error"] as NSString
// {
// println(errorString)
// }
}
}
}
else
{
if let errorString = error.userInfo["error"] as NSString
{
println(errorString)
}
}
*/
}
}
@IBAction func logOutUser(sender: UIButton)
{
var alert:UIAlertView = UIAlertView(title: "Message", message: "Are you sure want to logout", delegate: self, cancelButtonTitle: "NO", otherButtonTitles: "YES")
alert.tag = 10
alert.show()
}
func configurePicker()
{
pickerContainer.frame = CGRectMake(0.0, 600.0, 320.0, 300.0)
pickerContainer.backgroundColor = UIColor.whiteColor()
picker.frame = CGRectMake(0.0, 20.0, 320.0, 300.0)
picker.setDate(NSDate(), animated: true)
picker.maximumDate = NSDate()
picker.datePickerMode = UIDatePickerMode.Date
pickerContainer.addSubview(picker)
var doneButton = UIButton()
doneButton.setTitle("Done", forState: UIControlState.Normal)
doneButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
doneButton.addTarget(self, action: Selector("dismissPicker"), forControlEvents: UIControlEvents.TouchUpInside)
doneButton.frame = CGRectMake(250.0, 5.0, 70.0, 37.0)
pickerContainer.addSubview(doneButton)
self.view.addSubview(pickerContainer)
}
func dismissPicker ()
{
UIView.animateWithDuration(0.4, animations: {
self.pickerContainer.frame = CGRectMake(0.0, 600.0, 320.0, 300.0)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
self.buttonDateOfBirth.setTitle(dateFormatter.stringFromDate(self.picker.date), forState: UIControlState.Normal)
})
}
func textFieldShouldReturn(textField: UITextField!) -> Bool
{
textField.resignFirstResponder()
return true
}
func checkMandatoryFieldsAreSet() -> Bool
{
var allFieldsAreSet = true
var message = ""
var button1 = self.view.viewWithTag(1) as UIButton
var button2 = self.view.viewWithTag(2) as UIButton
if (!button1.selected && !button2.selected)
{
message = "Please select your gender"
}
button1 = self.view.viewWithTag(3) as UIButton
button2 = self.view.viewWithTag(4) as UIButton
if (!button1.selected && !button2.selected)
{
message = "Please select whether you are interested in girls or boys"
}
if (message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 0)
{
var alert:UIAlertView = UIAlertView(title: "Message", message: message, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
allFieldsAreSet = false
}
return allFieldsAreSet
}
func resizeImage(original : UIImage, toSize size:CGSize) -> UIImage
{
var imageSize:CGSize = CGSizeZero
if (original.size.width < original.size.height)
{
imageSize.height = size.width * original.size.height / original.size.width
imageSize.width = size.width
}
else
{
imageSize.height = size.height
imageSize.width = size.height * original.size.width / original.size.height
}
UIGraphicsBeginImageContext(imageSize)
original.drawInRect(CGRectMake(0,0,imageSize.width,imageSize.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return resizedImage
}
//386
//460
//564
}
| mit | 279d3e159c458b5295c0cdec4cc34f71 | 32.741697 | 211 | 0.518318 | 5.988212 | false | false | false | false |
fe9lix/AccessRank | AccessRank/src/app/ViewController.swift | 1 | 2668 | import UIKit
final class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AccessRankDelegate {
@IBOutlet var tableView : UITableView!
@IBOutlet var predictionsTextView: UITextView!
private let cellIdentifier = "cellIdentifier"
private let userDefaultsKey = "accessRank"
private lazy var accessRank: AccessRank = {
let accessRank: AccessRank
if let jsonData = UserDefaults.standard.data(forKey: self.userDefaultsKey) {
accessRank = try! JSONDecoder().decode(AccessRank.self, from: jsonData)
} else {
accessRank = AccessRank(listStability: .medium)
}
accessRank.delegate = self
return accessRank
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupNotifications()
updatePredictionList()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - TableView
private func setupTableView() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TestItems.all.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
cell.textLabel?.text = TestItems.all[indexPath.row]["name"]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let id = TestItems.all[indexPath.row]["id"] else { return }
accessRank.visitItem(id)
}
// MARK: - AccessRankDelegate
func accessRankDidUpdatePredictions(_ accessRank: AccessRank) {
updatePredictionList()
}
private func updatePredictionList() {
predictionsTextView.text = accessRank.predictions
.map { TestItems.byID[$0]! }
.joined(separator: "\n")
}
// MARK: - Persistence
private func setupNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: .UIApplicationDidEnterBackground, object: nil)
}
@objc func didEnterBackground() {
saveToUserDefaults()
}
private func saveToUserDefaults() {
let encodedAccessRank = try? JSONEncoder().encode(accessRank)
UserDefaults.standard.set(encodedAccessRank, forKey: userDefaultsKey)
}
}
| mit | e25e7ec3c5d8ae89475f694ed51ca506 | 31.144578 | 146 | 0.656672 | 5.304175 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/PacketType.swift | 1 | 5295 | //
// PacketType.swift
// Bluetooth
//
// Created by Carlos Duclos on 8/9/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// The packets used on the piconet are related to the logical transports they are used in. Three logical transports with distinct packet types are defined (see Section 4 on page 97): the SCO logical transport, the eSCO logical transport, and the ACL logical transport. For each of these logical transports, 15 different packet types can be defined.
///
/// To indicate the different packets on a logical transport, the 4-bit TYPE code is used. The packet types are divided into four segments. The first segment is reserved for control packets. All control packets occupy a single time slot. The sec- ond segment is reserved for packets occupying a single time slot. The third seg- ment is reserved for packets occupying three time slots. The fourth segment is reserved for packets occupying five time slots. The slot occupancy is reflected in the segmentation and can directly be derived from the type code. Table 6.2 on page 118 summarizes the packets defined for the SCO, eSCO, and ACL logical transport types.
///
/// All packet types with a payload shall use GFSK modulation unless specified otherwise in the following sections.
///
/// ACL logical transports Enhanced Data Rate packet types are explicitly selected via LMP using the packet_type_table (ptt) parameter. eSCO Enhanced Data Rate packet types are selected when the eSCO logical transport is established.
@frozen
public enum PacketType {
/// ACL packets are used on the asynchronous logical transport. The information carried may be user data or control data.
///
/// Seven packet types are defined for Basic Rate operation: DM1, DH1, DM3, DH3, DM5, DH5 and AUX1. Six additional packets are defined for Enhanced Data Rate operation: 2-DH1, 3-DH1, 2-DH3, 3-DH3, 2-DH5 and 3-DH5.
case acl(BitMaskOptionSet<ACLPacketType>)
/// HV and DV packets are used on the synchronous SCO logical transport. The HV packets do not include a CRC and shall not be retransmitted. DV packets include a CRC on the data section, but not on the synchronous data section. The data section of DV packets shall be retransmitted. SCO packets may be routed to the synchronous I/O port. Four packets are allowed on the SCO logical transport: HV1, HV2, HV3 and DV. These packets are typically used for 64kb/s speech transmission but may be used for transparent synchronous data.
case sco(BitMaskOptionSet<SCOPacketType>)
public var rawValue: UInt16 {
switch self {
case .sco(let packetTypes):
return packetTypes.rawValue
case .acl(let packetTypes):
return packetTypes.rawValue
}
}
}
/// ACL packets are used on the asynchronous logical transport. The information carried may be user data or control data.
///
/// Seven packet types are defined for Basic Rate operation: DM1, DH1, DM3, DH3, DM5, DH5 and AUX1. Six additional packets are defined for Enhanced Data Rate operation: 2-DH1, 3-DH1, 2-DH3, 3-DH3, 2-DH5 and 3-DH5.
@frozen
public enum ACLPacketType: UInt16, BitMaskOption {
/// 2-DH1 may not be used
case packet2DH1mayNotBeUsed = 0x0002
/// 3-DH1 may not be used
case packet3DH1mayNotBeUsed = 0x0004
/// DM1 may be used
case packetDM1mayBeUsed = 0x0008
/// DH1 may be used
case packetDH1mayBeUsed = 0x0010
/// 2-DH3 may not be used
case packet2DH3mayNotBeUsed = 0x0100
/// 3-DH3 may not be used
case packet3DH3mayNotBeUsed = 0x0200
/// DM3 may be used
case packetDM3mayBeUsed = 0x0400
/// DH3 may be used
case packetDH3mayBeUsed = 0x0800
/// 2-DH5 may not be used
case packet2DH5mayBeUsed = 0x1000
/// 3-DH5 may not be used
case packet3DH5mayBeUsed = 0x2000
/// DM5 may be used
case packetDM5mayBeUsed = 0x4000
/// DH5 may be used
case packetDH5mayBeUsed = 0x8000
public static let allCases: [ACLPacketType] = [
.packet2DH1mayNotBeUsed,
.packet3DH1mayNotBeUsed,
.packetDM1mayBeUsed,
.packetDH1mayBeUsed,
.packet2DH3mayNotBeUsed,
.packet3DH3mayNotBeUsed,
.packetDM3mayBeUsed,
.packetDH3mayBeUsed,
.packet2DH5mayBeUsed,
.packet3DH5mayBeUsed,
.packetDM5mayBeUsed,
.packetDH5mayBeUsed
]
}
/// HV and DV packets are used on the synchronous SCO logical transport. The HV packets do not include a CRC and shall not be retransmitted. DV packets include a CRC on the data section, but not on the synchronous data section. The data section of DV packets shall be retransmitted. SCO packets may be routed to the synchronous I/O port. Four packets are allowed on the SCO logical transport: HV1, HV2, HV3 and DV. These packets are typically used for 64kb/s speech transmission but may be used for transparent synchronous data.
@frozen
public enum SCOPacketType: UInt16, BitMaskOption {
/// HV1
case hv1 = 0x0020
/// HV2
case hv2 = 0x0040
/// HV3
case hv3 = 0x0080
public static let allCases: [SCOPacketType] = [
.hv1,
.hv2,
.hv3
]
}
| mit | 51af9a95c530715d9436d5624e214b9e | 44.247863 | 659 | 0.709294 | 3.794982 | false | false | false | false |
stripe/stripe-ios | StripePayments/StripePayments/API Bindings/Models/Shared/STPMandateOnlineParams.swift | 1 | 2273 | //
// STPMandateOnlineParams.swift
// StripePayments
//
// Created by Cameron Sabol on 10/17/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
/// Contains details about a Mandate accepted online. - seealso: https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-mandate_data-customer_acceptance-online
public class STPMandateOnlineParams: NSObject {
/// The IP address from which the Mandate was accepted by the customer.
@objc public let ipAddress: String
/// The user agent of the browser from which the Mandate was accepted by the customer.
@objc public let userAgent: String
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
@objc internal var inferFromClient: NSNumber?
/// Initializes an STPMandateOnlineParams.
/// - Parameter ipAddress: The IP address from which the Mandate was accepted by the customer.
/// - Parameter userAgent: The user agent of the browser from which the Mandate was accepted by the customer.
/// - Returns: A new STPMandateOnlineParams instance with the specified parameters.
@objc(initWithIPAddress:userAgent:)
public init(
ipAddress: String,
userAgent: String
) {
self.ipAddress = ipAddress
self.userAgent = userAgent
super.init()
}
}
extension STPMandateOnlineParams: STPFormEncodable {
@objc internal var ipAddressField: String? {
guard inferFromClient == nil || !(inferFromClient?.boolValue ?? false) else {
return nil
}
return ipAddress
}
@objc internal var userAgentField: String? {
guard inferFromClient == nil || !(inferFromClient?.boolValue ?? false) else {
return nil
}
return userAgent
}
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:ipAddressField)): "ip_address",
NSStringFromSelector(#selector(getter:userAgentField)): "user_agent",
NSStringFromSelector(#selector(getter:inferFromClient)): "infer_from_client",
]
}
@objc
public class func rootObjectName() -> String? {
return "online"
}
}
| mit | de89d906b6698ab3f1788e04f4ad1059 | 32.411765 | 179 | 0.677817 | 4.646217 | false | false | false | false |
RigaDevDay/RigaDevDays-Swift | RigaDevDays/VenueViewController.swift | 1 | 4635 | // Copyright © 2017 RigaDevDays. All rights reserved.
import UIKit
import Firebase
import MapKit
import Kingfisher
class VenueViewController: UITableViewController {
@IBOutlet weak var venueTitle: UILabel!
@IBOutlet weak var venueMap: MKMapView!
@IBOutlet weak var venueAddress: UILabel!
@IBOutlet weak var venueDescription: UILabel!
@IBOutlet weak var venueURL: UILabel!
@IBOutlet weak var venueImage: UIImageView!
@IBOutlet weak var firstSeparatorLineHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var secondSeparatorLineHeightConstraint: NSLayoutConstraint!
var venue: Venue?
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
firstSeparatorLineHeightConstraint?.constant = 0.5
secondSeparatorLineHeightConstraint?.constant = 0.5
venueMap?.layer.cornerRadius = 10.0
venueMap?.layer.masksToBounds = true
venueImage?.layer.cornerRadius = 10.0
venueImage?.layer.masksToBounds = true
presentVenue(venue!)
}
func presentVenue(_ venue: Venue) {
title = venue.name
venueTitle.text = venue.title
if let coordinates = venue.coordinates?.components(separatedBy: ","),
let latitude = Double(coordinates[0]),
let longitude = Double(coordinates[1]) {
let venueCoordinate = CLLocationCoordinate2D.init(latitude: latitude, longitude: longitude)
let region = venueMap.regionThatFits(MKCoordinateRegionMakeWithDistance(venueCoordinate, 200, 200))
venueMap.setRegion(region, animated: true)
let point = MKPointAnnotation.init()
point.coordinate = venueCoordinate
point.title = venue.name
point.subtitle = venue.title
venueMap.addAnnotation(point)
}
if let photoURL = venue.imageUrl, photoURL.contains("http"), let imageURL = URL(string: photoURL) {
venueImage?.kf.indicatorType = .activity
venueImage?.kf.setImage(with: imageURL, options: [.transition(.fade(0.2))])
} else if let url = URL(string: Config.sharedInstance.baseURLPrefix + venue.imageUrl!) {
venueImage?.kf.indicatorType = .activity
venueImage?.kf.setImage(with: url, options: [.transition(.fade(0.2))])
}
venueAddress.text = venue.address
venueDescription.setHTMLFromString(htmlText: venue.description!)
venueURL.text = venue.web
}
// MARK: - UITableViewDelegate -
// do not remove this; table view cannot calculate proper height
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 1 {
if let url = URL.init(string: (venue?.web)!) {
UIApplication.shared.openURL(url)
}
}
}
}
extension VenueViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
let annotationView = MKPinAnnotationView.init(annotation: annotation, reuseIdentifier: "loc")
annotationView.canShowCallout = true
annotationView.rightCalloutAccessoryView = UIButton.init(type: .detailDisclosure)
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let coordinates = self.venue?.coordinates?.components(separatedBy: ","),
let latitude = Double(coordinates[0]),
let longitude = Double(coordinates[1]) {
let regionDistance:CLLocationDistance = 200
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = self.venue?.name
mapItem.openInMaps(launchOptions: options)
}
}
}
| mit | 1c87d1db8305a8305585d45a15330343 | 39.649123 | 129 | 0.680621 | 5.357225 | false | false | false | false |
MorganCabral/swiftrekt-ios-app-dev-challenge-2015 | app-dev-challenge/app-dev-challenge/WizardSprite.swift | 1 | 1681 | //
// WizardSprite.swift
// app-dev-challenge
//
// Created by Morgan Cabral on 2/8/15.
// Copyright (c) 2015 Team SwiftRekt. All rights reserved.
//
import Foundation
import SpriteKit
public class WizardSprite : SKSpriteNode {
/**
* Constructor.
*/
public init( startingPosition : CGPoint, endingPosition : CGPoint, facesRight : Bool ) {
self.startingPosition = startingPosition
self.endingPosition = endingPosition
self.facesRight = facesRight
var texture = SKTexture(imageNamed: "wizard")
var size = CGSize(width: texture.size().width, height: texture.size().height)
super.init(texture: texture, color: UIColor.whiteColor(), size: size)
// Set the position of the sprite to the specified starting position.
self.position = startingPosition
// Scale the sprite if we need to make it look to the left.
if !facesRight {
self.xScale = fabs(self.xScale) * -1
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func doInitialAnimation() {
// If we aren't already moving, indicate that we're moving now.
if( !_startedMovingToInitialPosition ) {
_startedMovingToInitialPosition = true
// Start the movement animation.
self.runAction(SKAction.moveTo(endingPosition, duration: 2.0), withKey: "wizardInitializationAnimation")
}
}
public func stopInitialAnimation() {
self.removeActionForKey("wizardInitializationAnimation")
}
var startingPosition : CGPoint
var endingPosition : CGPoint
var facesRight : Bool
private var _startedMovingToInitialPosition : Bool = false
} | mit | 0c60a517218da1ac7b9fbea6a01f3230 | 29.035714 | 110 | 0.699584 | 4.354922 | false | false | false | false |
diogot/MyWeight | MyWeight/Views/Style.swift | 1 | 2269 | //
// Style.swift
// MyWeight
//
// Created by Diogo on 09/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import UIKit
public protocol StyleProvider {
var backgroundColor: UIColor { get }
var separatorColor: UIColor { get }
var textColor: UIColor { get }
var textLightColor: UIColor { get }
var textInTintColor: UIColor { get }
var tintColor: UIColor { get }
var shadowColor: UIColor { get }
var title1: UIFont { get }
var title2: UIFont { get }
var title3: UIFont { get }
var body: UIFont { get }
var callout: UIFont { get }
var subhead: UIFont { get }
var footnote: UIFont { get }
var grid: CGFloat { get }
var animationDuration: TimeInterval { get }
}
public struct Style: StyleProvider {
public let backgroundColor: UIColor = Style.white
public let separatorColor: UIColor = Style.lightGray
public let textColor: UIColor = Style.black
public let textLightColor: UIColor = Style.gray
public let textInTintColor: UIColor = Style.lightGray
public let tintColor: UIColor = Style.teal
public let shadowColor: UIColor = Style.transparentBlack
public let title1 = UIFont.systemFont(ofSize: 42, weight: .heavy)
public let title2 = UIFont.systemFont(ofSize: 28, weight: .semibold)
public let title3 = UIFont.systemFont(ofSize: 22, weight: .bold)
public let body = UIFont.systemFont(ofSize: 20, weight: .medium)
public let callout = UIFont.systemFont(ofSize: 18, weight: .medium)
public let subhead = UIFont.systemFont(ofSize: 15, weight: .medium)
public let footnote = UIFont.systemFont(ofSize: 13, weight: .medium)
public let grid: CGFloat = 8
public let animationDuration: TimeInterval = 0.3
private static let teal = UIColor(red: 81/255, green: 203/255, blue: 212/255, alpha: 1)
private static let black = UIColor(red: 67/255, green: 70/255, blue: 75/255, alpha: 1)
private static let gray = UIColor(red: 168/255, green: 174/255, blue: 186/255, alpha: 1)
private static let lightGray = UIColor(red: 241/255, green: 243/255, blue: 246/255, alpha: 1)
private static let white = UIColor(white: 1, alpha: 1)
private static let transparentBlack = UIColor(white: 0.2, alpha: 0.9)
}
| mit | 63c1f06a1fbc6404760548b5e7be3e6a | 33.363636 | 97 | 0.689153 | 3.890223 | false | false | false | false |
cburrows/swift-protobuf | Sources/protoc-gen-swift/Google_Protobuf_DescriptorProto+Extensions.swift | 1 | 1490 | // Sources/protoc-gen-swift/Google_Protobuf_DescriptorProto+Extensions.swift - Descriptor extensions
//
// Copyright (c) 2014 - 2016 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
//
// -----------------------------------------------------------------------------
///
/// Extensions to `DescriptorProto` that provide Swift-generation-specific
/// functionality.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
import SwiftProtobuf
extension Google_Protobuf_DescriptorProto.ExtensionRange {
/// A `String` containing the Swift expression that represents this
/// extension range to be used in a `case` statement.
var swiftCaseExpression: String {
if start == end - 1 {
return "\(start)"
}
return "\(start)..<\(end)"
}
/// A `String` containing the Swift Boolean expression that tests the given
/// variable for containment within this extension range.
///
/// - Parameter variable: The name of the variable to test in the expression.
/// - Returns: A `String` containing the Boolean expression.
func swiftBooleanExpression(variable: String) -> String {
if start == end - 1 {
return "\(start) == \(variable)"
}
return "\(start) <= \(variable) && \(variable) < \(end)"
}
}
| apache-2.0 | 29ca1fe39990075a703adc7ba475320b | 34.47619 | 100 | 0.625503 | 4.837662 | false | false | false | false |
kaojohnny/CoreStore | CoreStoreDemo/CoreStoreDemo/Loggers Demo/CustomLoggerViewController.swift | 1 | 3929 | //
// CustomLoggerViewController.swift
// CoreStoreDemo
//
// Created by John Rommel Estropia on 2015/06/05.
// Copyright © 2015 John Rommel Estropia. All rights reserved.
//
import UIKit
import CoreStore
import GCDKit
// MARK: - CustomLoggerViewController
class CustomLoggerViewController: UIViewController, CoreStoreLogger {
// MARK: NSObject
deinit {
CoreStore.logger = DefaultLogger()
}
let dataStack = DataStack()
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
try! self.dataStack.addStorageAndWait(SQLiteStore(fileName: "emptyStore.sqlite"))
CoreStore.logger = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let alert = UIAlertController(
title: "Logger Demo",
message: "This demo shows how to plug-in any logging framework to CoreStore.\n\nThe view controller implements CoreStoreLogger and appends all logs to the text view.",
preferredStyle: .Alert
)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
// MARK: CoreStoreLogger
func log(level level: LogLevel, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
GCDQueue.Main.async { [weak self] in
let levelString: String
switch level {
case .Trace: levelString = "Trace"
case .Notice: levelString = "Notice"
case .Warning: levelString = "Warning"
case .Fatal: levelString = "Fatal"
}
self?.textView?.insertText("\((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ [Log:\(levelString)] \(message)\n\n")
}
}
func log(error error: CoreStoreError, message: String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
GCDQueue.Main.async { [weak self] in
self?.textView?.insertText("\((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ [Error] \(message): \(error)\n\n")
}
}
func assert(@autoclosure condition: () -> Bool, @autoclosure message: () -> String, fileName: StaticString, lineNumber: Int, functionName: StaticString) {
if condition() {
return
}
let messageString = message()
GCDQueue.Main.async { [weak self] in
self?.textView?.insertText("\((fileName.stringValue as NSString).lastPathComponent):\(lineNumber) \(functionName)\n ↪︎ [Assert] \(messageString)\n\n")
}
}
// MARK: Private
@IBOutlet dynamic weak var textView: UITextView?
@IBOutlet dynamic weak var segmentedControl: UISegmentedControl?
@IBAction dynamic func segmentedControlValueChanged(sender: AnyObject?) {
switch self.segmentedControl?.selectedSegmentIndex {
case 0?:
self.dataStack.beginAsynchronous { (transaction) -> Void in
transaction.create(Into(Palette))
}
case 1?:
_ = try? dataStack.addStorageAndWait(
SQLiteStore(
fileName: "emptyStore.sqlite",
configuration: "invalidStore"
)
)
case 2?:
self.dataStack.beginAsynchronous { (transaction) -> Void in
transaction.commit()
transaction.commit()
}
default:
return
}
}
}
| mit | a296cd157d3613a4ef82310dda7c813d | 30.079365 | 179 | 0.574821 | 5.446453 | false | false | false | false |
kimseongrim/KimSampleCode | UITableView/UITableView/MyTableViewController.swift | 1 | 3993 | //
// MyTableViewController.swift
// UITableView
//
// Created by 金成林 on 15/1/30.
// Copyright (c) 2015年 Kim. All rights reserved.
//
import UIKit
class MyTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 导航+UITableView,在push,back回来之后,当前cell仍然是选中的状态。相当于UITableView deselectRowAtIndexpath
self.clearsSelectionOnViewWillAppear = true
//下拉后刷新UITableView效果
self.refreshControl = UIRefreshControl()
self.refreshControl?.beginRefreshing()
// self.refreshControl?.endRefreshing()
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// table header,abcdefg滚动条,UITableView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 10
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
//
// cell.textLabel
// Configure the cell...
var mCell = MyTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "\(indexPath)")
println("\(indexPath)")
return mCell
// return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
func viewDidAppear() {
// self.tableView.flashScrollIndicators()
}
}
| gpl-2.0 | 2e5bc410217aa2e6b9783f2ffb0e45c7 | 30.813008 | 157 | 0.661896 | 5.582026 | false | false | false | false |
onmyway133/Then | Pod/Classes/Promise.swift | 1 | 3063 | //
// Promise.swift
// Pods
//
// Created by Khoa Pham on 12/28/15.
// Copyright © 2015 Fantageek. All rights reserved.
//
import Foundation
public final class Promise<T> {
public typealias Value = T
var result: Result<T> = .Pending
let lockQueue = dispatch_queue_create("lock_queue", DISPATCH_QUEUE_SERIAL)
var callbacks = [Callback<T>]()
public let key = NSUUID().UUIDString
public init(result: Result<T> = .Pending) {
self.result = result
}
public func then<U>(queue: dispatch_queue_t = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0),
map: Result<T> -> Result<U>?) -> Promise<U> {
let promise = Promise<U>()
register(queue: queue) { result in
promise.notify(result: map(result))
}
notify(result: result)
return promise
}
public func reject(reason reason: ErrorType) {
dispatch_sync(lockQueue) {
guard self.result.isPending() else {
return
}
self.result = .Rejected(reason: reason)
self.notify(result: self.result)
}
}
public func fulfill(value value: T) {
dispatch_sync(lockQueue) {
guard self.result.isPending() else {
return
}
self.result = .Fulfilled(value: value)
self.notify(result: self.result)
}
}
private func notify(result result: Result<T>?) {
guard let result = result where !result.isPending() else {
return
}
self.result = result
callbacks.forEach { callback in
dispatch_async(callback.queue) {
callback.completion(result)
}
}
callbacks.removeAll()
}
private func register(queue queue: dispatch_queue_t, completion: Result<T> -> Void) {
let callback = Callback(completion: completion, queue: queue)
callbacks.append(callback)
}
public class func all(promises promises: [Promise]) -> Promise<[String: T]> {
let final = Promise<[String: T]>()
let total = promises.count
var count = 0
var values = [String: T]()
promises.forEach { promise in
promise.then { result in
dispatch_sync(final.lockQueue) {
if !final.result.isPending() {
return
}
switch result {
case let .Rejected(reason):
final.reject(reason: reason)
case let .Fulfilled(value):
count++
values[promise.key] = value
if count == total {
final.fulfill(value: values)
}
default:
break
}
}
return nil
} as Promise<T>
}
return final
}
} | mit | d0b1f74c7535af295969cd12934cb0fd | 25.634783 | 101 | 0.502613 | 4.799373 | false | false | false | false |
bradleypj823/Swift-StackOverFlow | SwiftStackOverFlow/WebViewController.swift | 1 | 2397 | //
// WebViewController.swift
// SwiftStackOverFlow
//
// Created by Bradley Johnson on 6/26/14.
// Copyright (c) 2014 Bradley Johnson. All rights reserved.
//
import UIKit
class WebViewController: UIViewController,UIWebViewDelegate {
@IBOutlet var webView : UIWebView = nil
var publicKey = "5Vpg3uTqCwAssGUjZx73wg(("
var oAuthDomain = "https://stackexchange.com/oauth/login_success"
var clientID = "3197"
var oAuthURL = "https://stackexchange.com/oauth/dialog"
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
var loginURL = "\(oAuthURL)?client_id=\(clientID)&redirect_uri=\(oAuthDomain)&scope=read_inbox"
self.webView.loadRequest(NSURLRequest(URL: NSURL(string: loginURL)))
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webView(webView: UIWebView!,
shouldStartLoadWithRequest request: NSURLRequest!,
navigationType: UIWebViewNavigationType) -> Bool
{
if request {
var requestString = request.URL.description
if requestString.rangeOfString("login_success") {
if requestString.rangeOfString("expires") {
println("got it")
let components = requestString.componentsSeparatedByString("=")
let tokenComponents = components[1].componentsSeparatedByString("&")
println(tokenComponents[0])
NetworkController.sharedNetworkController.token = tokenComponents[0]
self.dismissModalViewControllerAnimated(true)
}
}
}
return true
}
@IBAction func cancelPressed(sender : AnyObject) {
self.dismissModalViewControllerAnimated(true)
}
/*
// #pragma 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.
}
*/
}
| gpl-3.0 | 290eb77850b98e030c76067c73ecdad6 | 32.760563 | 106 | 0.636629 | 5.33853 | false | false | false | false |
analuizaferrer/TrocaComigo | Example/SwapIt/CustomOverlayView.swift | 1 | 967 | //
// CustomOverlayView.swift
// Koloda
//
// Created by Eugene Andreyev on 7/27/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import UIKit
import Koloda
private let overlayRightImageName = "overlay-like"
private let overlayLeftImageName = "overlay-skip"
class CustomOverlayView: OverlayView {
@IBOutlet lazy var overlayImageView: UIImageView! = {
[unowned self] in
var imageView = UIImageView(frame: self.bounds)
self.addSubview(imageView)
return imageView
}()
override var overlayState: SwipeResultDirection? {
didSet {
switch overlayState {
case .Left? :
overlayImageView.image = UIImage(named: overlayLeftImageName)
case .Right? :
overlayImageView.image = UIImage(named: overlayRightImageName)
default:
overlayImageView.image = nil
}
}
}
}
| mit | abd1c8e4f01f0db84582877475a18fbe | 24.447368 | 78 | 0.610134 | 4.717073 | false | false | false | false |
smallhadroncollider/binc | binc/shell.swift | 1 | 480 | import Foundation
func shell(launchPath: String, arguments: [String]) -> [String]
{
let task = NSTask()
task.launchPath = launchPath
task.arguments = arguments
let pipe = NSPipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: NSUTF8StringEncoding)!
return output.componentsSeparatedByString("\n").filter({line in !line.isEmpty})
} | mit | 23beefae9a3e8559d98bfba9cc89cd00 | 27.294118 | 83 | 0.691667 | 4.705882 | false | false | false | false |
dreamsxin/swift | test/IRGen/dynamic_self_metadata.swift | 5 | 1899 | // RUN: %target-swift-frontend %s -emit-ir -parse-as-library | FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: Not a SIL test because we can't parse dynamic Self in SIL.
// <rdar://problem/16931299>
// CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }>
@inline(never) func id<T>(_ t: T) -> T {
return t
}
// CHECK-LABEL: define hidden void @_TF21dynamic_self_metadata2idurFxx
class C {
class func fromMetatype() -> Self? { return nil }
// CHECK-LABEL: define hidden i64 @_TZFC21dynamic_self_metadata1C12fromMetatypefT_GSqDS0__(%swift.type*)
// CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8
// CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: store i64 0, i64* [[CAST1]], align 8
// CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8
// CHECK: ret i64 [[LOAD]]
func fromInstance() -> Self? { return nil }
// CHECK-LABEL: define hidden i64 @_TFC21dynamic_self_metadata1C12fromInstancefT_GSqDS0__(%C21dynamic_self_metadata1C*)
// CHECK: [[ALLOCA:%.+]] = alloca [[TYPE]], align 8
// CHECK: [[CAST1:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: store i64 0, i64* [[CAST1]], align 8
// CHECK: [[CAST2:%.+]] = bitcast [[TYPE]]* [[ALLOCA]] to i64*
// CHECK: [[LOAD:%.+]] = load i64, i64* [[CAST2]], align 8
// CHECK: ret i64 [[LOAD]]
func dynamicSelfArgument() -> Self? {
return id(nil)
}
// CHECK-LABEL: define hidden i64 @_TFC21dynamic_self_metadata1C19dynamicSelfArgumentfT_GSqDS0__(%C21dynamic_self_metadata1C*)
// CHECK: [[CAST1:%.+]] = bitcast %C21dynamic_self_metadata1C* %0 to [[METATYPE:%.+]]
// CHECK: [[TYPE1:%.+]] = call %swift.type* @swift_getObjectType([[METATYPE]] [[CAST1]])
// CHECK: [[TYPE2:%.+]] = call %swift.type* @_TMaSq(%swift.type* [[TYPE1]])
// CHECK: call void @_TF21dynamic_self_metadata2idurFxx({{.*}}, %swift.type* [[TYPE2]])
}
| apache-2.0 | 0f620f277edbf82a74b614bbb7307f79 | 44.214286 | 128 | 0.613481 | 3.10802 | false | false | false | false |
hwsyy/swift_TabNav | swift_TabNav/swift_TabNav/Classes/Main/MainTabBar.swift | 1 | 996 | //
// MainTabBar.swift
// ChatBei
//
// Created by Bing Ma on 5/25/15.
// Copyright (c) 2015 iChatBei. All rights reserved.
//
import UIKit
class MainTabBar: UITabBar {
override func layoutSubviews() {
super.layoutSubviews()
setButtonsFrame()
}
let buttonCount = 4
func setButtonsFrame() {
let width = self.bounds.size.width / CGFloat(buttonCount)
let height = self.bounds.size.height
var index = 0
// MARK: UITabBarButton --> 私有API
for view in self.subviews as! [UIView] {
// 判断子视图是否是控件
// MARK: [- tip -] UITabBarButton 继承与 UIControl
if (view is UIControl) && !(view is UIButton) {
let rect = CGRectMake(CGFloat(index) * width, 0, width, height)
view.frame = rect
index++
}
}
}
}
| mit | 2d98f839752d62cfcd04f9a694475781 | 20.466667 | 79 | 0.501035 | 4.451613 | false | false | false | false |
mshhmzh/firefox-ios | SyncTests/LiveStorageClientTests.swift | 3 | 5628 | /* 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 Account
import Foundation
import FxA
import Shared
import Deferred
@testable import Sync
import XCTest
private class KeyFetchError: MaybeErrorType {
var description: String {
return "key fetch error"
}
}
private class MockBackoffStorage: BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp? = nil
func clearServerBackoff() {
self.serverBackoffUntilLocalTimestamp = nil
}
func isInBackoff(now: Timestamp) -> Timestamp? {
if let ts = self.serverBackoffUntilLocalTimestamp where now < ts {
return ts
}
return nil
}
}
class LiveStorageClientTests : LiveAccountTest {
func getKeys(kB: NSData, token: TokenServerToken) -> Deferred<Maybe<Record<KeysPayload>>> {
let endpoint = token.api_endpoint
XCTAssertTrue(endpoint.rangeOfString("services.mozilla.com") != nil, "We got a Sync server.")
let cryptoURI = NSURL(string: endpoint)
let authorizer: Authorizer = {
(r: NSMutableURLRequest) -> NSMutableURLRequest in
let helper = HawkHelper(id: token.id, key: token.key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
r.addValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization")
return r
}
let keyBundle: KeyBundle = KeyBundle.fromKB(kB)
let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0 })
let encrypter = Keys(defaultBundle: keyBundle).encrypter("crypto", encoder: encoder)
let workQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let resultQueue = dispatch_get_main_queue()
let backoff = MockBackoffStorage()
let storageClient = Sync15StorageClient(serverURI: cryptoURI!, authorizer: authorizer, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff)
let keysFetcher = storageClient.clientForCollection("crypto", encrypter: encrypter)
return keysFetcher.get("keys").map({
// Unwrap the response.
res in
if let r = res.successValue {
return Maybe(success: r.value)
}
return Maybe(failure: KeyFetchError())
})
}
func getState(user: String, password: String) -> Deferred<Maybe<FxAState>> {
let err: NSError = NSError(domain: FxAClientErrorDomain, code: 0, userInfo: nil)
return Deferred(value: Maybe<FxAState>(failure: FxAClientError.Local(err)))
}
func getTokenAndDefaultKeys() -> Deferred<Maybe<(TokenServerToken, KeyBundle)>> {
let authState = self.syncAuthState(NSDate.now())
let keysPayload: Deferred<Maybe<Record<KeysPayload>>> = authState.bind {
tokenResult in
if let (token, forKey) = tokenResult.successValue {
return self.getKeys(forKey, token: token)
}
XCTAssertEqual(tokenResult.failureValue!.description, "")
return Deferred(value: Maybe(failure: KeyFetchError()))
}
let result = Deferred<Maybe<(TokenServerToken, KeyBundle)>>()
keysPayload.upon {
res in
if let rec = res.successValue {
XCTAssert(rec.id == "keys", "GUID is correct.")
XCTAssert(rec.modified > 1000, "modified is sane.")
let payload: KeysPayload = rec.payload as KeysPayload
print("Body: \(payload.toString(false))", terminator: "\n")
XCTAssert(rec.id == "keys", "GUID inside is correct.")
if let keys = payload.defaultKeys {
// Extracting the token like this is not great, but...
result.fill(Maybe(success: (authState.value.successValue!.token, keys)))
return
}
}
result.fill(Maybe(failure: KeyFetchError()))
}
return result
}
func testLive() {
let expectation = expectationWithDescription("Waiting on value.")
let deferred = getTokenAndDefaultKeys()
deferred.upon {
res in
if let (_, _) = res.successValue {
print("Yay", terminator: "\n")
} else {
XCTAssertEqual(res.failureValue!.description, "")
}
expectation.fulfill()
}
// client: mgWl22CIzHiE
waitForExpectationsWithTimeout(20) { (error) in
XCTAssertNil(error, "\(error)")
}
}
func testStateMachine() {
let expectation = expectationWithDescription("Waiting on value.")
let authState = self.getAuthState(NSDate.now())
let d = chainDeferred(authState, f: { SyncStateMachine(prefs: MockProfilePrefs()).toReady($0) })
d.upon { result in
if let ready = result.successValue {
XCTAssertTrue(ready.collectionKeys.defaultBundle.encKey.length == 32)
XCTAssertTrue(ready.scratchpad.global != nil)
if let clients = ready.scratchpad.global?.value.engines["clients"] {
XCTAssertTrue(clients.syncID.characters.count == 12)
}
}
XCTAssertTrue(result.isSuccess)
expectation.fulfill()
}
waitForExpectationsWithTimeout(20) { (error) in
XCTAssertNil(error, "\(error)")
}
}
} | mpl-2.0 | bc473593b89ab1a6f26bfd804a3edddf | 37.033784 | 160 | 0.614783 | 4.898172 | false | false | false | false |
MillmanY/MMTransition | MMTransition/Classes/MMTransition.swift | 1 | 933 | //
// MMTransition.swift
// Pods
//
// Created by Millman YANG on 2017/4/24.
//
//
import UIKit
fileprivate var mmPresentKey = "MMPresentKey"
fileprivate var mmPushKey = "MMPushKey"
public extension MMTransition where T: UIViewController {
var present: MMPresentAnimator {
if let v = objc_getAssociatedObject(base, &mmPresentKey) {
return v as! MMPresentAnimator
}
let m = MMPresentAnimator(self.base)
objc_setAssociatedObject(base, &mmPresentKey, m, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return m
}
}
public extension MMTransition where T: UINavigationController {
var push: MMPushAnimator {
if let v = objc_getAssociatedObject(base, &mmPushKey) {
return v as! MMPushAnimator
}
let m = MMPushAnimator(self.base)
objc_setAssociatedObject(base, &mmPushKey, m, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return m
}
}
| mit | 61fcce7e0047b0b57da2a048291eb4dc | 26.441176 | 92 | 0.669882 | 3.987179 | false | false | false | false |
vkaramov/VKFingerprint | Pod/Classes/VKFingerprint.swift | 1 | 9133 | //
// VKFingerprint.swift
// SwiftyTouchId
//
// Created by Viacheslav Karamov on 02.10.15.
// Copyright © 2015 Viacheslav Karamov. All rights reserved.
//
import Foundation
import LocalAuthentication
public typealias VKKeychainCompletion = Bool -> Void;
public typealias VKKeychainCompletionWithValue = (error : NSError?, value : NSData?) -> Void;
public typealias VKKeychainCompletionWithString = (error : NSError?, value : NSString?) -> Void;
/**
Fingerprint scanner availablity state
- Unavailable: Fingerprint is not supported by the device
- Available: Fingerprint available but not configured
- Configured: Fingerprint available and configured
*/
public enum VKFingerprintState
{
case Unavailable, Available, Configured;
}
/// Simple Fingerprint Swift wrapper for iOS
public class VKFingerprint : NSObject
{
/// Human-readable label
public var label : NSString = ""
/// Access group. Access groups can be used to share keychain items among two or more applications. For applications to share a keychain item, the applications must have a common access group listed in their keychain-access-groups entitlement
public var accessGroup : NSString? = nil
/// Service associated with this item. See Security.kSecAttrService constant for details
public var service : NSString = NSBundle.mainBundle().bundleIdentifier ?? "default_service"
/**
Convenience intializer
- parameter lb: Human-readable label
- parameter touchIdEnabled: Should touchID be used. This variable is ignored when running in Simulator
- parameter accessGroup: Access group. Access groups can be used to share keychain items among two or more applications. For applications to share a keychain item, the applications must have a common access group listed in their keychain-access-groups entitlement
- parameter service: Service associated with this item. See Security.kSecAttrService constant for details. If you pass nil, NSBundle.mainBundle().bundleIdentifier value is used instead.
*/
public convenience init(label lb:NSString, touchIdEnabled:Bool, accessGroup:NSString?, service:NSString?)
{
self.init();
self.label = lb
self.accessGroup = accessGroup
#if !((arch(i386) || arch(x86_64)) && os(iOS))
self.touchIdEnabled = (.Configured == availabilityState) && touchIdEnabled
#endif
if let service = service
{
self.service = service
}
}
/// Returns Fingerprint scanner availability state
public var availabilityState : VKFingerprintState
{
let context = LAContext();
var error:NSError?
let evaluated = context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error)
if let error = error
{
NSLog("Failed to initialize fingerprint scanner: %@", error);
let laError = LAError(rawValue: error.code)!
switch laError
{
case .TouchIDNotAvailable, .PasscodeNotSet:
return .Unavailable
default:
// In iOS 8.0 & 8.1 .PasscodeNotSet might be returned for the devices which doesn't support TouchID
// To not compare with the list of devices, I've just set minimum supported version to 8.2. Profit!
return .Available
}
}
return evaluated ? .Configured :.Unavailable
}
/**
Stores value to the Keychain using the key spacified
- parameter value: Value to store
- parameter key: Key to store value for
- parameter completion: Optional completion block. Will be dispatched to the main thread
*/
public func setValue(value: NSData, forKey key: NSString, completion:VKKeychainCompletion?)
{
let keychain = VKKeychain(label: label, touchIdEnabled: (.Configured == availabilityState) && touchIdEnabled, accessGroup: accessGroup, service: service);
dispatch_async(queue) { () -> Void in
var success = true;
do
{
try keychain.set(value, key: key);
}
catch let error as NSError
{
NSLog("Failed to add value to keychain: ", error);
success = false;
}
if let completion = completion
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(success);
})
}
}
}
/**
Stores string to the Keychain using the key spacified
- parameter value: String to store
- parameter key: Key to store value for
- parameter completion: Optional completion block. Will be dispatched to the main thread
*/
public func setStringValue(value : NSString, forKey key : NSString, completion : VKKeychainCompletion?)
{
let data = value.dataUsingEncoding(NSUTF8StringEncoding)!;
setValue(data, forKey: key, completion: completion);
}
/**
Reads data from the Keychain using the key specified. Users will be prompted to hold their fingers to the touchID sensor if device has it.
- parameter key: Key to read value for
- parameter completion: Completion block. Will be dispatched to the main thread
*/
public func getValue(forKey key: NSString, completion:VKKeychainCompletionWithValue)
{
let keychain = VKKeychain(label: label, touchIdEnabled: (.Configured == availabilityState) && touchIdEnabled, accessGroup: accessGroup, service: service);
dispatch_async(queue) { () -> Void in
var data:NSData? = nil;
var error:NSError? = nil;
do
{
data = try keychain.get(key);
}
catch let err as NSError
{
error = err;
NSLog("Failed to get keychain value: ", err);
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(error: error, value: data);
})
}
}
/**
Reads string from the Keychain using the key specified. Users will be prompted to hold their fingers to the touchID sensor if device has it.
- parameter key: Key to read value for
- parameter completion: Completion block. Will be dispatched to the main thread
*/
public func getString(forKey key: NSString, completion:VKKeychainCompletionWithString)
{
getValue(forKey: key) { (error:NSError?, value:NSData?) -> Void in
let stringValue = value != nil ? NSString(data: value!, encoding: NSUTF8StringEncoding) : nil;
completion(error: error, value: stringValue);
};
}
/**
Removes value from the keychain using the key provided.
- parameter key: Key to remove value for
- parameter completion: Optional completion block. Will be dispatched to the main thread
*/
public func resetValue(forKey key:NSString, completion:VKKeychainCompletion?)
{
let keychain = VKKeychain();
#if !((arch(i386) || arch(x86_64)) && os(iOS))
keychain.touchIdEnabled = (.Configured == availabilityState) && touchIdEnabled;
#endif
keychain.service = service;
dispatch_async(queue) { () -> Void in
var success = true;
do
{
try keychain.remove(key);
}
catch let error as NSError
{
NSLog("Failed to reset keychain value: ", error);
success = false;
}
if let completion = completion
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(success);
})
}
}
}
/**
Checks if validation value is present. The users can disable and enable touch ID while your App is running, so
all touchID-protected data would be lost. There's no way to check this case directly, so the library writes special verification value to the keychain allowing the client to check if the user has disabled TouchID and then enabled
- parameter completion: Completion block. Will be dispatched to the main thread
*/
public func validateValue(completion:VKKeychainCompletion)
{
let keychain = VKKeychain();
keychain
#if !((arch(i386) || arch(x86_64)) && os(iOS))
keychain.touchIdEnabled = (.Configured == availabilityState) && touchIdEnabled;
#endif
dispatch_async(queue) { () -> Void in
let valid = keychain.hasValidationValue()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(valid);
})
}
}
private let queue = dispatch_queue_create("VKFingerprintSerialQueue", DISPATCH_QUEUE_SERIAL);
private var touchIdEnabled = false;
}
| mit | 1c9aab2f3505d818201e5925d102ee00 | 38.193133 | 270 | 0.621222 | 5.042518 | false | false | false | false |
enums/Pjango | Source/Pjango/View/PCListView.swift | 1 | 1073 | //
// PCListView.swift
// Pjango
//
// Created by 郑宇琦 on 2017/6/17.
// Copyright © 2017年 郑宇琦. All rights reserved.
//
import Foundation
open class PCListView: PCView {
override internal var _pjango_core_view_param: PCViewParam {
var param = super._pjango_core_view_param
guard let lists = listObjectSets else {
return param
}
for (list, objs) in lists {
param[list] = objs.map { (obj) -> PCViewParam in
var param: Dictionary<String, Any> = obj.toViewParam()
if let extParam = listUserField(inList: list, forModel: obj) {
extParam.forEach { (key, value) in
param[key] = value
}
}
return param
}
}
return param
}
open func listUserField(inList list: String, forModel model: PCModel) -> PCViewParam? {
return nil
}
open var listObjectSets: [String: [PCModel]]? {
return nil
}
}
| apache-2.0 | 504b209fdb5a620a42d9dab3e42957cd | 24.804878 | 91 | 0.52741 | 4.022814 | false | false | false | false |
onurersel/anim | examples/message/views/BackButton.swift | 1 | 3276 | //
// BackButton.swift
// anim
//
// Created by Onur Ersel on 2017-03-16.
// Copyright (c) 2017 Onur Ersel. All rights reserved.
import UIKit
import anim
// MARK: - Back Bar Button Item
class BackBarButtonItem: UIBarButtonItem {
weak var buttonView: BackButton!
class func create() -> BackBarButtonItem {
let view = BackButton.create()
let barButton = BackBarButtonItem(customView: view)
barButton.buttonView = view
return barButton
}
}
// MARK: - Back Button
class BackButton: UIButton {
private var arrowImageView: UIImageView!
class func create() -> BackButton {
let view = BackButton()
view.size(width: 38, height: 38)
view.layer.cornerRadius = 19
// background
view.backgroundColor = UIColor.white
// arrow
view.arrowImageView = UIImageView(image: #imageLiteral(resourceName: "back_arrow"))
view.addSubview(view.arrowImageView)
view.arrowImageView.center(to: view)
view.addTarget(view, action: #selector(view.downAction), for: .touchDown)
view.addTarget(view, action: #selector(view.upAction), for: .touchUpInside)
view.addTarget(view, action: #selector(view.upAction), for: .touchCancel)
view.addTarget(view, action: #selector(view.upAction), for: .touchUpOutside)
return view
}
// MARK: Animations
func animateArrowIn() {
arrowImageView.alpha = 0
anim { (settings) -> (animClosure) in
settings.delay = 0.5
settings.duration = 0.5
return {
self.arrowImageView.alpha = 1
}
}
arrowImageView.center.x = self.center.x + 8
anim{ (settings) -> animClosure in
settings.ease = .easeOutQuint
settings.delay = 0.5
settings.duration = 0.7
return {
self.arrowImageView.center.x = 19
}
}
}
func animateArrowOut() {
anim { (settings) -> (animClosure) in
settings.duration = 0.7
settings.ease = .easeInSine
return {
self.arrowImageView.alpha = 0
}
}
}
// MARK: Actions / Handlers
@objc
func downAction() {
anim { (settings) -> (animClosure) in
settings.ease = .easeOutBack
settings.duration = 0.1
return {
self.transform = CGAffineTransform.identity.scaledBy(x: 1.4, y: 1.4)
}
}
}
@objc
func upAction() {
anim { (settings) -> (animClosure) in
settings.ease = .easeOutBack
settings.duration = 0.16
return {
self.transform = CGAffineTransform.identity
}
}
}
deinit {
removeTarget(self, action: #selector(self.downAction), for: .touchDown)
removeTarget(self, action: #selector(self.upAction), for: .touchUpInside)
removeTarget(self, action: #selector(self.upAction), for: .touchCancel)
removeTarget(self, action: #selector(self.upAction), for: .touchUpOutside)
}
}
| mit | 9d25e3abdd0d4c127a79c8e4633577d3 | 26.07438 | 91 | 0.559219 | 4.518621 | false | false | false | false |
silence0201/Swift-Study | Learn/13.类继承/重写实例方法.playground/section-1.swift | 1 | 1178 |
import Foundation
class Person {
var name: String
var age: Int
func description() -> String {
return "\(name) 年龄是: \(age)"
}
class func printClass() ->() {
print( "Person 打印...")
}
init (name: String, age: Int) {
self.name = name
self.age = age
}
}
class Student: Person {
var school: String
convenience init() {
self.init(name: "Tony", age: 18, school: "清华大学")
}
init (name: String, age: Int, school: String) {
self.school = school
super.init(name: name, age: age)
}
override func description() -> String {
print("父类打印 \(super.description())")
return "\(name) 年龄是: \(age), 所在学校: \(school)。"
}
override class func printClass() ->() {
print( "Student 打印...")
}
}
let student1 = Student()
print("学生1:\(student1.description())")
let student2: Person = Student()
print("学生2:\(student2.description())")
let student3: Student = Student()
print("学生3:\(student3.description())")
Person.printClass()
Student.printClass()
| mit | b65339a541534c8470024118568058e7 | 18.54386 | 56 | 0.549372 | 3.725753 | false | false | false | false |
kesun421/firefox-ios | Sync/SyncTelemetryUtils.swift | 3 | 11394 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Account
import Storage
import SwiftyJSON
import SyncTelemetry
import Deferred
fileprivate let log = Logger.syncLogger
public let PrefKeySyncEvents = "sync.telemetry.events"
public enum SyncReason: String {
case startup = "startup"
case scheduled = "scheduled"
case backgrounded = "backgrounded"
case user = "user"
case syncNow = "syncNow"
case didLogin = "didLogin"
case push = "push"
}
public enum SyncPingReason: String {
case shutdown = "shutdown"
case schedule = "schedule"
case idChanged = "idchanged"
}
public protocol Stats {
func hasData() -> Bool
}
private protocol DictionaryRepresentable {
func asDictionary() -> [String: Any]
}
public struct SyncUploadStats: Stats {
var sent: Int = 0
var sentFailed: Int = 0
public func hasData() -> Bool {
return sent > 0 || sentFailed > 0
}
}
extension SyncUploadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"sent": sent,
"sentFailed": sentFailed
]
}
}
public struct SyncDownloadStats: Stats {
var applied: Int = 0
var succeeded: Int = 0
var failed: Int = 0
var newFailed: Int = 0
var reconciled: Int = 0
public func hasData() -> Bool {
return applied > 0 ||
succeeded > 0 ||
failed > 0 ||
newFailed > 0 ||
reconciled > 0
}
}
extension SyncDownloadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"applied": applied,
"succeeded": succeeded,
"failed": failed,
"newFailed": newFailed,
"reconciled": reconciled
]
}
}
public struct ValidationStats: Stats, DictionaryRepresentable {
let problems: [ValidationProblem]
let took: Int64
let checked: Int?
public func hasData() -> Bool {
return !problems.isEmpty
}
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"problems": problems.map { $0.asDictionary() },
"took": took
]
if let checked = self.checked {
dict["checked"] = checked
}
return dict
}
}
public struct ValidationProblem: DictionaryRepresentable {
let name: String
let count: Int
func asDictionary() -> [String: Any] {
return ["name": name, "count": count]
}
}
public class StatsSession {
var took: Int64 = 0
var when: Timestamp?
private var startUptimeNanos: UInt64?
public func start(when: UInt64 = Date.now()) {
self.when = when
self.startUptimeNanos = DispatchTime.now().uptimeNanoseconds
}
public func hasStarted() -> Bool {
return startUptimeNanos != nil
}
public func end() -> Self {
guard let startUptime = startUptimeNanos else {
assertionFailure("SyncOperationStats called end without first calling start!")
return self
}
// Casting to Int64 should be safe since we're using uptime since boot in both cases.
// Convert to milliseconds as stated in the sync ping format
took = (Int64(DispatchTime.now().uptimeNanoseconds) - Int64(startUptime)) / 1000000
return self
}
}
// Stats about a single engine's sync.
public class SyncEngineStatsSession: StatsSession {
public var validationStats: ValidationStats?
private(set) var uploadStats: SyncUploadStats
private(set) var downloadStats: SyncDownloadStats
public init(collection: String) {
self.uploadStats = SyncUploadStats()
self.downloadStats = SyncDownloadStats()
}
public func recordDownload(stats: SyncDownloadStats) {
self.downloadStats.applied += stats.applied
self.downloadStats.succeeded += stats.succeeded
self.downloadStats.failed += stats.failed
self.downloadStats.newFailed += stats.newFailed
self.downloadStats.reconciled += stats.reconciled
}
public func recordUpload(stats: SyncUploadStats) {
self.uploadStats.sent += stats.sent
self.uploadStats.sentFailed += stats.sentFailed
}
}
extension SyncEngineStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"took": took,
]
if downloadStats.hasData() {
dict["incoming"] = downloadStats.asDictionary()
}
if uploadStats.hasData() {
dict["outgoing"] = uploadStats.asDictionary()
}
if let validation = self.validationStats, validation.hasData() {
dict["validation"] = validation.asDictionary()
}
return dict
}
}
// Stats and metadata for a sync operation.
public class SyncOperationStatsSession: StatsSession {
public let why: SyncReason
public var uid: String?
public var deviceID: String?
fileprivate let didLogin: Bool
public init(why: SyncReason, uid: String, deviceID: String?) {
self.why = why
self.uid = uid
self.deviceID = deviceID
self.didLogin = (why == .didLogin)
}
}
extension SyncOperationStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
let whenValue = when ?? 0
return [
"when": whenValue,
"took": took,
"didLogin": didLogin,
"why": why.rawValue
]
}
}
public enum SyncPingError: MaybeErrorType {
case failedToRestoreScratchpad
public var description: String {
switch self {
case .failedToRestoreScratchpad: return "Failed to restore Scratchpad from prefs"
}
}
}
public enum SyncPingFailureReasonName: String {
case httpError = "httperror"
case unexpectedError = "unexpectederror"
case sqlError = "sqlerror"
case otherError = "othererror"
}
public protocol SyncPingFailureFormattable {
var failureReasonName: SyncPingFailureReasonName { get }
}
public struct SyncPing: SyncTelemetryPing {
public private(set) var payload: JSON
public static func from(result: SyncOperationResult,
account: FirefoxAccount,
remoteClientsAndTabs: RemoteClientsAndTabs,
prefs: Prefs,
why: SyncPingReason) -> Deferred<Maybe<SyncPing>> {
// Grab our token so we can use the hashed_fxa_uid and clientGUID from our scratchpad for
// our ping's identifiers
return account.syncAuthState.token(Date.now(), canBeExpired: false) >>== { (token, kB) in
let scratchpadPrefs = prefs.branch("sync.scratchpad")
guard let scratchpad = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKB(kB)) else {
return deferMaybe(SyncPingError.failedToRestoreScratchpad)
}
var ping: [String: Any] = [
"version": 1,
"why": why.rawValue,
"uid": token.hashedFxAUID,
"deviceID": (scratchpad.clientGUID + token.hashedFxAUID).sha256.hexEncodedString
]
// TODO: We don't cache our sync pings so if it fails, it fails. Once we add
// some kind of caching we'll want to make sure we don't dump the events if
// the ping has failed.
let pickledEvents = prefs.arrayForKey(PrefKeySyncEvents) as? [Data] ?? []
let events = pickledEvents.flatMap(Event.unpickle).map { $0.toArray() }
ping["events"] = events
prefs.setObject(nil, forKey: PrefKeySyncEvents)
return dictionaryFrom(result: result, storage: remoteClientsAndTabs, token: token) >>== { syncDict in
// TODO: Split the sync ping metadata from storing a single sync.
ping["syncs"] = [syncDict]
return deferMaybe(SyncPing(payload: JSON(ping)))
}
}
}
// Generates a single sync ping payload that is stored in the 'syncs' list in the sync ping.
private static func dictionaryFrom(result: SyncOperationResult,
storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[String: Any]>> {
return connectedDevices(fromStorage: storage, token: token) >>== { devices in
guard let stats = result.stats else {
return deferMaybe([String: Any]())
}
var dict = stats.asDictionary()
if let engineResults = result.engineResults.successValue {
dict["engines"] = SyncPing.enginePingDataFrom(engineResults: engineResults)
} else if let failure = result.engineResults.failureValue {
var errorName: SyncPingFailureReasonName
if let formattableFailure = failure as? SyncPingFailureFormattable {
errorName = formattableFailure.failureReasonName
} else {
errorName = .unexpectedError
}
dict["failureReason"] = [
"name": errorName.rawValue,
"error": "\(type(of: failure))",
]
}
dict["devices"] = devices
return deferMaybe(dict)
}
}
// Returns a list of connected devices formatted for use in the 'devices' property in the sync ping.
private static func connectedDevices(fromStorage storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[[String: Any]]>> {
func dictionaryFrom(client: RemoteClient) -> [String: Any]? {
var device = [String: Any]()
if let os = client.os {
device["os"] = os
}
if let version = client.version {
device["version"] = version
}
if let guid = client.guid {
device["id"] = (guid + token.hashedFxAUID).sha256.hexEncodedString
}
return device
}
return storage.getClients() >>== { deferMaybe($0.flatMap(dictionaryFrom)) }
}
private static func enginePingDataFrom(engineResults: EngineResults) -> [[String: Any]] {
return engineResults.map { result in
let (name, status) = result
var engine: [String: Any] = [
"name": name
]
// For complete/partial results, extract out the collect stats
// and add it to engine information. For syncs that were not able to
// start, return why and a reason.
switch status {
case .completed(let stats):
engine.merge(with: stats.asDictionary())
case .partial(let stats):
engine.merge(with: stats.asDictionary())
case .notStarted(let reason):
engine.merge(with: [
"status": reason.telemetryId
])
}
return engine
}
}
}
| mpl-2.0 | e90fc0408765d271dd884a172a086ede | 31.005618 | 123 | 0.596893 | 4.906977 | false | false | false | false |
Ricky-Choi/AppcidCocoaUtil | AppcidCocoaUtil/SimpleButton.swift | 1 | 1263 | //
// SimpleButton.swift
// PhotoGPS
//
// Created by Jaeyoung Choi on 2016. 10. 12..
// Copyright © 2016년 Appcid. All rights reserved.
//
#if os(iOS)
import UIKit
public class SimpleButton: UIButton {
public init(title: String, color: UIColor) {
super.init(frame: CGRect.zero)
tintColor = color
setTitle(title, for: .normal)
setTitleColor(color, for: .normal)
setTitleColor(UIColor.white, for: .highlighted)
setTitleColor(UIColor.lightGray, for: .disabled)
backgroundColor = UIColor.white
contentEdgeInsets = UIEdgeInsets(top: 8, left: 30, bottom: 8, right: 30)
layer.cornerRadius = 5
layer.borderWidth = 1
layer.borderColor = color.cgColor
clipsToBounds = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? tintColor : UIColor.white
}
}
override public var isEnabled: Bool {
didSet {
layer.borderColor = isEnabled ? tintColor.cgColor : UIColor.lightGray.cgColor
}
}
}
#endif
| mit | bb1ab6a548be4633f528f40accffce6f | 24.2 | 89 | 0.613492 | 4.468085 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Extensions/Sources/SwiftExtensions/Codable.swift | 1 | 3161 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
extension Decodable {
public init(json any: Any, using decoder: JSONDecoder = .init()) throws {
let data = try JSONSerialization.data(withJSONObject: any, options: .fragmentsAllowed)
self = try decoder.decode(Self.self, from: data)
}
}
extension Encodable {
public func data(using encoder: JSONEncoder = .init()) throws -> Data {
try encoder.encode(self)
}
public func json(using encoder: JSONEncoder = .init()) throws -> Any {
try data(using: encoder).json()
}
}
extension Data {
public func json() throws -> Any {
try JSONSerialization.jsonObject(with: self, options: .allowFragments)
}
}
extension Dictionary where Key == String, Value == Any {
public func json(options: JSONSerialization.WritingOptions = []) throws -> Data {
try JSONSerialization.data(withJSONObject: self, options: options)
}
}
extension Array where Element == Any {
public func json(options: JSONSerialization.WritingOptions = []) throws -> Data {
try JSONSerialization.data(withJSONObject: self, options: options)
}
}
extension Optional where Wrapped == Data {
public func json() throws -> Any {
switch self {
case nil:
return NSNull()
case let wrapped?:
return try wrapped.json()
}
}
}
extension DecodingError {
/// Provides a formatted description of a `DecodingError`, please note the result is not localized intentionally
public var formattedDescription: String {
switch self {
case .dataCorrupted(let context):
let underlyingError = (context.underlyingError as? NSError)?.debugDescription ?? ""
return "Data corrupted. \(context.debugDescription) \(underlyingError)"
case .keyNotFound(let codingKey, let context):
return "Key not found. Expected -> \(codingKey.stringValue) <- at: \(formattedPath(for: context))"
case .typeMismatch(_, let context):
return "Type mismatch. \(context.debugDescription) at: \(formattedPath(for: context))"
case .valueNotFound(_, let context):
return "Value not found. -> \(formattedPath(for: context)) <- \(context.debugDescription)"
@unknown default:
return "Unknown error while decoding"
}
}
private func formattedPath(for context: DecodingError.Context) -> String {
context.codingPath.map(\.stringValue).joined(separator: ".")
}
}
extension EncodingError {
/// Provides a formatted description of a `EncodingError`, please note the result is not localized intentionally
public var formattedDescription: String {
switch self {
case .invalidValue(_, let context):
return "Invalid value while encoding found -> \(formattedPath(for: context))"
@unknown default:
return "Unknown error while encoding"
}
}
private func formattedPath(for context: EncodingError.Context) -> String {
context.codingPath.map(\.stringValue).joined(separator: ".")
}
}
| lgpl-3.0 | 1ab2b65168ac65d964038ab0a8c8ecef | 32.617021 | 116 | 0.654114 | 4.88408 | false | false | false | false |
HJliu1123/LearningNotes-LHJ | April/HJCustomCollectionViewLayout/HJCustomCollectionViewLayout/ViewController.swift | 1 | 1678 | //
// ViewController.swift
// HJCustomCollectionViewLayout
//
// Created by liuhj on 16/4/27.
// Copyright © 2016年 liuhj. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
//懒加载
lazy var imageNames : NSMutableArray = {
var imageNames = NSMutableArray()
for i in 1...9 {
imageNames.addObject("\(i).jpg")
}
return imageNames
}()
override func viewDidLoad() {
super.viewDidLoad()
let rect = CGRectMake(0, 40, self.view.frame.size.width, 200)
let collectionView = UICollectionView(frame: rect, collectionViewLayout: HJFlowLayout())
collectionView.registerClass(HJImageCell().classForCoder, forCellWithReuseIdentifier: "Image")
collectionView.delegate = self
collectionView.dataSource = self
self.view.addSubview(collectionView)
}
// override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// self.collectionView.set
// }
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageNames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Image", forIndexPath: indexPath) as? HJImageCell
cell?.imageName = imageNames[indexPath.row] as! String
return cell!
}
}
| apache-2.0 | 9cc4680d82aebef9449791f01f8138c1 | 26.816667 | 130 | 0.648292 | 5.600671 | false | false | false | false |
calkinssean/TIY-Assignments | Day 9/TMDBJson/Movie.swift | 1 | 3535 | //
// Movie.swift
// TMDBJson
//
// Created by Sean Calkins on 2/11/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import Foundation
class Movie {
var poster_path: String
var adult: Bool
var overview: String
var release_date: String
var genre_ids: [Int]
var id: Int
var original_language : String
var title: String
var backdrop_path : String
var popularity: Double
var vote_count: Int
var video: Bool
var vote_average: Double
init(dict: JSONDictionary) {
self.poster_path = ""
self.adult = false
self.overview = ""
self.release_date = ""
self.genre_ids = []
self.id = 1
self.original_language = ""
self.title = ""
self.backdrop_path = ""
self.popularity = 1.0
self.vote_count = 0
self.video = false
self.vote_average = 0.0
if let poster_path = dict["poster_path"] as? String {
self.poster_path = poster_path
print(poster_path)
} else {
print("no bueno on poster path")
}
if let adult = dict["adult"] as? Bool {
self.adult = adult
print(adult)
} else {
print("no bueno on adult senor")
}
if let overview = dict["overview"] as? String {
self.overview = overview
print(overview)
} else {
print("your overview is heckin on you")
}
if let release_date = dict["release_date"] as? String {
self.release_date = release_date
print(release_date)
} else {
print("release_date")
}
if let genre_ids = dict["genre_ids"] as? [Int] {
self.genre_ids = genre_ids
print(genre_ids)
} else {
print("genre_ids")
}
if let id = dict["id"] as? Int {
self.id = id
print(id)
} else {
print("fix your id bruh")
}
if let original_language = dict["original_language"] as? String {
self.original_language = original_language
print(original_language)
} else {
print("no habla original_language")
}
if let title = dict["title"] as? String {
self.title = title
print(title)
} else {
print("check your title before you wreck your title")
}
if let backdrop_path = dict["backdrop_path"] as? String {
self.backdrop_path = backdrop_path
print(backdrop_path)
} else {
print("the backdrop_path has dropped off the back")
}
if let popularity = dict["popularity"] as? Double {
self.popularity = popularity
print(popularity)
} else {
print("you are not popular")
}
if let vote_count = dict["vote_count"] as? Int {
self.vote_count = vote_count
print(vote_count)
} else {
print("your vote didn't count")
}
if let video = dict["video"] as? Bool {
self.video = video
print(video)
} else {
print("there is problem with video")
}
if let vote_average = dict["vote_average"] as? Double {
self.vote_average = vote_average
print(vote_average)
} else {
print("your vote_average sucks")
}
}
} | cc0-1.0 | a63792403525b9b39763efc8fce2bde0 | 27.97541 | 73 | 0.509055 | 4.217184 | false | false | false | false |
DanielAsher/Side-Menu.iOS | MenuExample/Controller/MenuViewController.swift | 1 | 1703 | //
// Copyright © 2014 Yalantis
// Licensed under the MIT license: http://opensource.org/licenses/MIT
// Latest version can be found at http://github.com/yalantis/Side-Menu.iOS
//
import UIKit
import SideMenu
protocol MenuViewControllerDelegate: class {
func menu(menu: MenuViewController, didSelectItemAtIndex index: Int, atPoint point: CGPoint)
func menuDidCancel(menu: MenuViewController)
}
class MenuViewController: UITableViewController {
weak var delegate: MenuViewControllerDelegate?
var selectedItem = 0
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let indexPath = NSIndexPath(forRow: selectedItem, inSection: 0)
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
}
extension MenuViewController {
@IBAction
private func dismissMenu() {
delegate?.menuDidCancel(self)
}
}
extension MenuViewController: Menu {
var menuItems: [UIView] {
return [tableView.tableHeaderView!] + tableView.visibleCells as [UIView]
}
}
extension MenuViewController {
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return indexPath == tableView.indexPathForSelectedRow ? nil : indexPath
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let rect = tableView.rectForRowAtIndexPath(indexPath)
var point = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
point = tableView.convertPoint(point, toView: nil)
delegate?.menu(self, didSelectItemAtIndex: indexPath.row, atPoint:point)
}
}
| mit | d931885c1edc1c6b78b22adcdc519d83 | 32.372549 | 118 | 0.736193 | 5.035503 | false | false | false | false |
TellMeAMovieTeam/TellMeAMovie_iOSApp | TellMeAMovie/TellMeAMovie/Movie.swift | 1 | 4665 | //
// Movie.swift
// TellMeAMovie
//
// Created by Илья on 27.11.16.
// Copyright © 2016 IlyaGutnikov. All rights reserved.
//
import Foundation
import TMDBSwift
import Realm
import RealmSwift
public class RealmStringObject : Object {
dynamic var value : String = ""
}
//TODO переделать под realm
public class Movie : Object {
dynamic var movieId : Int = 0
dynamic var movieTitle : String = ""
dynamic var movieOriginalTitle : String = ""
dynamic var movieRating : Double = 0
dynamic var movieTagLine : String = ""
dynamic var movieOverview : String = ""
dynamic var moviePoster : String = ""
dynamic var movieGenre : String = ""
dynamic var movieYear : Int = 0
//для более удобного хранения в UD
var framesURLs = List<RealmStringObject>()
public func setData(movie : MovieDetailedMDB, frames : [RealmStringObject]) {
movie.id != nil ? (self.movieId = movie.id!) : (self.movieId = -1)
movie.title != nil ? (self.movieTitle = movie.title!) : (self.movieTitle = "")
movie.original_title != nil ? (self.movieOriginalTitle = movie.original_title!) : (self.movieOriginalTitle = "")
movie.vote_average != nil ? (self.movieRating = movie.vote_average!) : (self.movieRating = -1)
movie.tagline != nil ? (self.movieTagLine = movie.tagline!) : (self.movieTagLine = "")
movie.overview != nil ? (self.movieOverview = movie.overview!) : (self.movieOverview = "")
movie.poster_path != nil ? (self.moviePoster = imageBase + movie.poster_path!) : (self.moviePoster = "")
self.movieGenre = getSingleLineGenres(movie: movie)
movie.release_date != nil ? ( self.movieYear = Int((movie.release_date?.substring(to: (movie.release_date?.index((movie.release_date?.endIndex)!, offsetBy: -6))!))!)!) : (self.movieYear = 0)
frames.count != 0 ? (self.framesURLs.append(objectsIn: frames)) : (self.framesURLs = List<RealmStringObject>())
}
public func setData() {
self.movieId = -1
self.movieTitle = ""
self.movieOriginalTitle = ""
self.movieRating = -1
self.movieTagLine = ""
self.movieOverview = ""
self.moviePoster = ""
self.movieGenre = ""
self.movieYear = 0
self.framesURLs = List<RealmStringObject>()
}
public func setData(id : Int, title : String, originalTitle : String, voteAverage : Double, tagline : String, overview : String, moviePoster : String, movieGenre : String, movieYear : Int, frames : [RealmStringObject]) {
self.movieId = id
self.movieTitle = title
self.movieOriginalTitle = originalTitle
self.movieRating = voteAverage
self.movieTagLine = tagline
self.movieOverview = overview
self.moviePoster = moviePoster
self.movieGenre = movieGenre
self.movieYear = movieYear
self.framesURLs.append(objectsIn: frames)
}
}
public func saveMoviesToUD(movies : [Movie]) {
let realm = try! Realm()
let objects = List<Movie>()
movies.forEach {
objects.append($0)
}
try! realm.write {
realm.add(objects)
}
}
public func getMoviesFromRealm() -> [Movie] {
let objects = try! Realm().objects(Movie)
let array = Array(objects)
return array
}
public func removeMoviesFromRealm(movies : [Movie]) {
let objects = List<Movie>()
movies.forEach {
objects.append($0)
}
let realm = try! Realm()
try! realm.write {
realm.delete(objects)
}
}
public func removeMoviesFromRealm() {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
}
public func setMovieIdToUserDefaults(movie : Movie) {
UserDefaults.standard.set(movie.movieId, forKey : "TellMeAMovie_MovieId")
}
public func getMovieIdFromUserDefaults() -> Int {
if let movieId : Int = UserDefaults.standard.integer(forKey: "TellMeAMovie_MovieId") {
return movieId
}
return -1
}
public func getMovieFromRealm(movieId : Int) -> Movie {
if (movieId < 0) {
return Movie.init()
}
let realm = try! Realm()
var movies = realm.objects(Movie).filter("movieId = \(movieId)")
if (movies.count >= 1) {
let array = Array(movies)
print(array.count)
print(array[0].movieOriginalTitle)
return array[0]
} else {
return Movie.init()
}
}
| apache-2.0 | bd47ad759669d8185289f6ada091d631 | 26.188235 | 224 | 0.6045 | 4.029643 | false | false | false | false |
LawrenceHan/iOS-project-playground | Homepwner_swift/Homepwner/ImageStore.swift | 1 | 1716 | //
// Copyright © 2015 Big Nerd Ranch
//
import UIKit
class ImageStore {
let cache = NSCache()
func imageURLForKey(key: String) -> NSURL {
let documentsDirectories =
NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,
inDomains: .UserDomainMask)
let documentDirectory = documentsDirectories.first!
return documentDirectory.URLByAppendingPathComponent(key)
}
func setImage(image: UIImage, forKey key: String) {
cache.setObject(image, forKey: key)
// Create full URL for image
let imageURL = imageURLForKey(key)
// Turn image into JPEG data
if let data = UIImageJPEGRepresentation(image, 0.5) {
// Write it to full URL
data.writeToURL(imageURL, atomically: true)
}
}
func imageForKey(key: String) -> UIImage? {
if let existingImage = cache.objectForKey(key) as? UIImage {
return existingImage
}
else {
let imageURL = imageURLForKey(key)
guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
return nil
}
cache.setObject(imageFromDisk, forKey: key)
return imageFromDisk
}
}
func deleteImageForKey(key: String) {
cache.removeObjectForKey(key)
let imageURL = imageURLForKey(key)
do {
try NSFileManager.defaultManager().removeItemAtURL(imageURL)
}
catch let deleteError {
print("Error removing the image from disk: \(deleteError)")
}
}
}
| mit | 453a60042a9136e8b8674a1a773bc0c8 | 26.66129 | 84 | 0.574927 | 5.410095 | false | false | false | false |
ztolley/VideoStationViewer | VideoStationViewer/SettingsViewController.swift | 1 | 995 | import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var hostname: UITextField!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
private let preferences = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
let preferences = NSUserDefaults.standardUserDefaults()
if let user = preferences.stringForKey("USERID") {
self.username.text = user
}
if let hostname = preferences.stringForKey("HOSTNAME") {
self.hostname.text = hostname
}
}
@IBAction func save(sender: UIButton) {
preferences.setObject(hostname.text, forKey: "HOSTNAME")
preferences.setObject(username.text, forKey: "USERID")
if (password.text?.characters.count > 0) {
preferences.setObject(password.text, forKey: "PASSWORD")
}
preferences.synchronize()
let loadingViewController = LoadingViewController()
self.presentViewController(loadingViewController, animated: true, completion: nil)
}
}
| gpl-3.0 | ef8dc33b0c2aaf3807f726ac460b525d | 24.512821 | 84 | 0.745729 | 4.252137 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.