repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
wfleming/SwiftLint | Source/SwiftLintFramework/Rules/CyclomaticComplexityRule.swift | 2 | 5194 | //
// CyclomaticComplexityRule.swift
// SwiftLint
//
// Created by Denis Lebedev on 24/01/2016.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct CyclomaticComplexityRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityLevelsConfiguration(warning: 10, error: 20)
public init() {}
public static let description = RuleDescription(
identifier: "cyclomatic_complexity",
name: "Cyclomatic Complexity",
description: "Complexity of function bodies should be limited.",
nonTriggeringExamples: [
"func f1() {\nif true {\nfor _ in 1..5 { } }\nif false { }\n}",
"func f(code: Int) -> Int {" +
"switch code {\n case 0: fallthrough\ncase 0: return 1\ncase 0: return 1\n" +
"case 0: return 1\ncase 0: return 1\ncase 0: return 1\ncase 0: return 1\n" +
"case 0: return 1\ncase 0: return 1\ndefault: return 1}}",
"func f1() {" +
"if true {}; if true {}; if true {}; if true {}; if true {}; if true {}\n" +
"func f2() {\n" +
"if true {}; if true {}; if true {}; if true {}; if true {}\n" +
"}}",
],
triggeringExamples: [
"func f1() {\n if true {\n if true {\n if false {}\n }\n" +
" }\n if false {}\n let i = 0\n\n switch i {\n case 1: break\n" +
" case 2: break\n case 3: break\n case 4: break\n default: break\n }\n" +
" for _ in 1...5 {\n guard true else {\n return\n }\n }\n}\n"
]
)
public func validateFile(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
if !functionKinds.contains(kind) {
return []
}
let complexity = measureComplexity(file, dictionary: dictionary)
for parameter in configuration.params where complexity > parameter.value {
let offset = Int(dictionary["key.offset"] as? Int64 ?? 0)
return [StyleViolation(ruleDescription: self.dynamicType.description,
severity: parameter.severity,
location: Location(file: file, byteOffset: offset),
reason: "Function should have complexity \(configuration.warning) or less: " +
"currently complexity equals \(complexity)")]
}
return []
}
private func measureComplexity(file: File,
dictionary: [String: SourceKitRepresentable]) -> Int {
var hasSwitchStatements = false
let substructure = dictionary["key.substructure"] as? [SourceKitRepresentable] ?? []
let complexity = substructure.reduce(0) { complexity, subItem in
guard let subDict = subItem as? [String: SourceKitRepresentable],
kind = subDict["key.kind"] as? String else {
return complexity
}
if let declarationKid = SwiftDeclarationKind(rawValue: kind)
where functionKinds.contains(declarationKid) {
return complexity
}
if kind == "source.lang.swift.stmt.switch" {
hasSwitchStatements = true
}
return complexity +
Int(complexityStatements.contains(kind)) +
measureComplexity(file, dictionary: subDict)
}
if hasSwitchStatements {
return reduceSwitchComplexity(complexity, file: file, dictionary: dictionary)
}
return complexity
}
// Switch complexity is reduced by `fallthrough` cases
private func reduceSwitchComplexity(complexity: Int, file: File,
dictionary: [String: SourceKitRepresentable]) -> Int {
let bodyOffset = Int(dictionary["key.bodyoffset"] as? Int64 ?? 0)
let bodyLength = Int(dictionary["key.bodylength"] as? Int64 ?? 0)
let c = (file.contents as NSString)
.substringWithByteRange(start: bodyOffset, length: bodyLength) ?? ""
let fallthroughCount = c.componentsSeparatedByString("fallthrough").count - 1
return complexity - fallthroughCount
}
private let complexityStatements = [
"source.lang.swift.stmt.foreach",
"source.lang.swift.stmt.if",
"source.lang.swift.stmt.case",
"source.lang.swift.stmt.guard",
"source.lang.swift.stmt.for",
"source.lang.swift.stmt.repeatwhile",
"source.lang.swift.stmt.while"
]
private let functionKinds: [SwiftDeclarationKind] = [
.FunctionAccessorAddress,
.FunctionAccessorDidset,
.FunctionAccessorGetter,
.FunctionAccessorMutableaddress,
.FunctionAccessorSetter,
.FunctionAccessorWillset,
.FunctionConstructor,
.FunctionDestructor,
.FunctionFree,
.FunctionMethodClass,
.FunctionMethodInstance,
.FunctionMethodStatic,
.FunctionOperator,
.FunctionSubscript
]
}
| mit |
YouareMylovelyGirl/Sina-Weibo | 新浪微博/新浪微博/Classes/Tools(工具)/WeiBoCommon.swift | 1 | 1227 | //
// WeiBoCommon.swift
// 新浪微博
//
// Created by 阳光 on 2017/6/7.
// Copyright © 2017年 YG. All rights reserved.
//
import Foundation
import UIKit
//MARK: - 应用程序信息
//应用程序ID
let APPKey = "1659422547"
//39190169
//2715e085a21ca4f1083f3ff2544ee6cc
//------
//1659422547
//470bfdc420e5cdbcca12a60ffffba2da
//应用程序加密信息
let APPSecret = "470bfdc420e5cdbcca12a60ffffba2da"
//回调地址 - 登录完成跳转的URL, 参数以get形式拼接
let RedirectURI = "http://baidu.com"
//MARK: - 全局通知定义
//用户需要登录通知
let UserShouldLoginNotification = "UserShouldLoginNotification"
//用户登录成功通知
let UserLoginSuccessNotification = "UserLoginSuccessNotification"
//MARK: - 微博配图视图内部常量
//1. 计算配图视图的宽度
//配图视图外侧的间距
let StatusPictureViewOutterMargin = CGFloat(12)
//配图视图内部图像视图的间距
let StatusPictureViewInnerMargin = CGFloat(3)
//视图的宽度
let StatusPictureViewWidth = UIScreen.main.bounds.size.width - 2 * StatusPictureViewOutterMargin
//每个Item默认的高度
let StatusPictureItemWidth = ((StatusPictureViewWidth) - 2 * StatusPictureViewInnerMargin) / 3
| apache-2.0 |
steveholt55/metro | iOS/MetroTransitTests/Controller/DirectionsViewControllerTests.swift | 1 | 169 | //
// Copyright © 2015 Brandon Jenniges. All rights reserved.
//
import XCTest
@testable import MetroTransit
class DirectionsViewControllerTests: XCTestCase {
} | mit |
tlax/GaussSquad | GaussSquad/View/LinearEquations/Indeterminate/VLinearEquationsIndeterminateControl.swift | 1 | 3305 | import UIKit
class VLinearEquationsIndeterminateControl:UIView
{
private weak var controller:CLinearEquationsIndeterminate!
private let kButtonsWidth:CGFloat = 100
private let kButtonMargin:CGFloat = 10
private let kCornerRadius:CGFloat = 15
init(controller:CLinearEquationsIndeterminate)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let buttonCancel:UIButton = UIButton()
buttonCancel.translatesAutoresizingMaskIntoConstraints = false
buttonCancel.backgroundColor = UIColor.squadRed
buttonCancel.setTitle(
NSLocalizedString("VLinearEquationsIndeterminateControl_buttonCancel", comment:""),
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonCancel.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonCancel.titleLabel!.font = UIFont.bold(
size:13)
buttonCancel.layer.cornerRadius = kCornerRadius
buttonCancel.addTarget(
self,
action:#selector(actionCancel(sender:)),
for:UIControlEvents.touchUpInside)
let buttonSave:UIButton = UIButton()
buttonSave.translatesAutoresizingMaskIntoConstraints = false
buttonSave.backgroundColor = UIColor.squadBlue
buttonSave.setTitle(
NSLocalizedString("VLinearEquationsIndeterminateControl_buttonSave", comment:""),
for:UIControlState.normal)
buttonSave.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonSave.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonSave.titleLabel!.font = UIFont.bold(
size:13)
buttonSave.layer.cornerRadius = kCornerRadius
buttonSave.addTarget(
self,
action:#selector(actionSave(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(buttonCancel)
addSubview(buttonSave)
NSLayoutConstraint.equalsVertical(
view:buttonCancel,
toView:self,
margin:kButtonMargin)
NSLayoutConstraint.leftToLeft(
view:buttonCancel,
toView:self,
constant:kButtonMargin)
NSLayoutConstraint.width(
view:buttonCancel,
constant:kButtonsWidth)
NSLayoutConstraint.equalsVertical(
view:buttonSave,
toView:self,
margin:kButtonMargin)
NSLayoutConstraint.rightToRight(
view:buttonSave,
toView:self,
constant:-kButtonMargin)
NSLayoutConstraint.width(
view:buttonSave,
constant:kButtonsWidth)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionCancel(sender button:UIButton)
{
controller.cancel()
}
func actionSave(sender button:UIButton)
{
controller.save()
}
}
| mit |
aipeople/PokeIV | Pods/PGoApi/PGoApi/Classes/protos/Pogoprotos.Map.Pokemon.PogoprotosMapPokemon.proto.swift | 1 | 63976 | // Generated by the Protocol Buffers 3.0 compiler. DO NOT EDIT!
// Source file "POGOProtos.Map.Pokemon.proto"
// Syntax "Proto3"
import Foundation
import ProtocolBuffers
public func == (lhs: Pogoprotos.Map.Pokemon.MapPokemon, rhs: Pogoprotos.Map.Pokemon.MapPokemon) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasSpawnPointId == rhs.hasSpawnPointId) && (!lhs.hasSpawnPointId || lhs.spawnPointId == rhs.spawnPointId)
fieldCheck = fieldCheck && (lhs.hasEncounterId == rhs.hasEncounterId) && (!lhs.hasEncounterId || lhs.encounterId == rhs.encounterId)
fieldCheck = fieldCheck && (lhs.hasPokemonId == rhs.hasPokemonId) && (!lhs.hasPokemonId || lhs.pokemonId == rhs.pokemonId)
fieldCheck = fieldCheck && (lhs.hasExpirationTimestampMs == rhs.hasExpirationTimestampMs) && (!lhs.hasExpirationTimestampMs || lhs.expirationTimestampMs == rhs.expirationTimestampMs)
fieldCheck = fieldCheck && (lhs.hasLatitude == rhs.hasLatitude) && (!lhs.hasLatitude || lhs.latitude == rhs.latitude)
fieldCheck = fieldCheck && (lhs.hasLongitude == rhs.hasLongitude) && (!lhs.hasLongitude || lhs.longitude == rhs.longitude)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public func == (lhs: Pogoprotos.Map.Pokemon.NearbyPokemon, rhs: Pogoprotos.Map.Pokemon.NearbyPokemon) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasPokemonId == rhs.hasPokemonId) && (!lhs.hasPokemonId || lhs.pokemonId == rhs.pokemonId)
fieldCheck = fieldCheck && (lhs.hasDistanceInMeters == rhs.hasDistanceInMeters) && (!lhs.hasDistanceInMeters || lhs.distanceInMeters == rhs.distanceInMeters)
fieldCheck = fieldCheck && (lhs.hasEncounterId == rhs.hasEncounterId) && (!lhs.hasEncounterId || lhs.encounterId == rhs.encounterId)
fieldCheck = fieldCheck && (lhs.hasFortId == rhs.hasFortId) && (!lhs.hasFortId || lhs.fortId == rhs.fortId)
fieldCheck = fieldCheck && (lhs.hasFortImageUrl == rhs.hasFortImageUrl) && (!lhs.hasFortImageUrl || lhs.fortImageUrl == rhs.fortImageUrl)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public func == (lhs: Pogoprotos.Map.Pokemon.WildPokemon, rhs: Pogoprotos.Map.Pokemon.WildPokemon) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasEncounterId == rhs.hasEncounterId) && (!lhs.hasEncounterId || lhs.encounterId == rhs.encounterId)
fieldCheck = fieldCheck && (lhs.hasLastModifiedTimestampMs == rhs.hasLastModifiedTimestampMs) && (!lhs.hasLastModifiedTimestampMs || lhs.lastModifiedTimestampMs == rhs.lastModifiedTimestampMs)
fieldCheck = fieldCheck && (lhs.hasLatitude == rhs.hasLatitude) && (!lhs.hasLatitude || lhs.latitude == rhs.latitude)
fieldCheck = fieldCheck && (lhs.hasLongitude == rhs.hasLongitude) && (!lhs.hasLongitude || lhs.longitude == rhs.longitude)
fieldCheck = fieldCheck && (lhs.hasSpawnPointId == rhs.hasSpawnPointId) && (!lhs.hasSpawnPointId || lhs.spawnPointId == rhs.spawnPointId)
fieldCheck = fieldCheck && (lhs.hasPokemonData == rhs.hasPokemonData) && (!lhs.hasPokemonData || lhs.pokemonData == rhs.pokemonData)
fieldCheck = fieldCheck && (lhs.hasTimeTillHiddenMs == rhs.hasTimeTillHiddenMs) && (!lhs.hasTimeTillHiddenMs || lhs.timeTillHiddenMs == rhs.timeTillHiddenMs)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public extension Pogoprotos.Map.Pokemon {
public struct PogoprotosMapPokemonRoot {
public static var sharedInstance : PogoprotosMapPokemonRoot {
struct Static {
static let instance : PogoprotosMapPokemonRoot = PogoprotosMapPokemonRoot()
}
return Static.instance
}
public var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(extensionRegistry)
Pogoprotos.Enums.PogoprotosEnumsRoot.sharedInstance.registerAllExtensions(extensionRegistry)
Pogoprotos.Data.PogoprotosDataRoot.sharedInstance.registerAllExtensions(extensionRegistry)
}
public func registerAllExtensions(registry:ExtensionRegistry) {
}
}
final public class MapPokemon : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var hasSpawnPointId:Bool = false
public private(set) var spawnPointId:String = ""
public private(set) var hasEncounterId:Bool = false
public private(set) var encounterId:UInt64 = UInt64(0)
public private(set) var pokemonId:Pogoprotos.Enums.PokemonId = Pogoprotos.Enums.PokemonId.Missingno
public private(set) var hasPokemonId:Bool = false
// After this timestamp, the pokemon will be gone.
public private(set) var hasExpirationTimestampMs:Bool = false
public private(set) var expirationTimestampMs:Int64 = Int64(0)
public private(set) var hasLatitude:Bool = false
public private(set) var latitude:Double = Double(0)
public private(set) var hasLongitude:Bool = false
public private(set) var longitude:Double = Double(0)
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasSpawnPointId {
try output.writeString(1, value:spawnPointId)
}
if hasEncounterId {
try output.writeFixed64(2, value:encounterId)
}
if hasPokemonId {
try output.writeEnum(3, value:pokemonId.rawValue)
}
if hasExpirationTimestampMs {
try output.writeInt64(4, value:expirationTimestampMs)
}
if hasLatitude {
try output.writeDouble(5, value:latitude)
}
if hasLongitude {
try output.writeDouble(6, value:longitude)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasSpawnPointId {
serialize_size += spawnPointId.computeStringSize(1)
}
if hasEncounterId {
serialize_size += encounterId.computeFixed64Size(2)
}
if (hasPokemonId) {
serialize_size += pokemonId.rawValue.computeEnumSize(3)
}
if hasExpirationTimestampMs {
serialize_size += expirationTimestampMs.computeInt64Size(4)
}
if hasLatitude {
serialize_size += latitude.computeDoubleSize(5)
}
if hasLongitude {
serialize_size += longitude.computeDoubleSize(6)
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Pogoprotos.Map.Pokemon.MapPokemon> {
var mergedArray = Array<Pogoprotos.Map.Pokemon.MapPokemon>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Pogoprotos.Map.Pokemon.MapPokemon? {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeFromData(data, extensionRegistry:Pogoprotos.Map.Pokemon.PogoprotosMapPokemonRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
return Pogoprotos.Map.Pokemon.MapPokemon.classBuilder() as! Pogoprotos.Map.Pokemon.MapPokemon.Builder
}
public func getBuilder() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
return classBuilder() as! Pogoprotos.Map.Pokemon.MapPokemon.Builder
}
override public class func classBuilder() -> MessageBuilder {
return Pogoprotos.Map.Pokemon.MapPokemon.Builder()
}
override public func classBuilder() -> MessageBuilder {
return Pogoprotos.Map.Pokemon.MapPokemon.Builder()
}
public func toBuilder() throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
return try Pogoprotos.Map.Pokemon.MapPokemon.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Pogoprotos.Map.Pokemon.MapPokemon) throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder().mergeFrom(prototype)
}
override public func encode() throws -> Dictionary<String,AnyObject> {
guard isInitialized() else {
throw ProtocolBuffersError.InvalidProtocolBuffer("Uninitialized Message")
}
var jsonMap:Dictionary<String,AnyObject> = Dictionary<String,AnyObject>()
if hasSpawnPointId {
jsonMap["spawnPointId"] = spawnPointId
}
if hasEncounterId {
jsonMap["encounterId"] = "\(encounterId)"
}
if hasPokemonId {
jsonMap["pokemonId"] = pokemonId.toString()
}
if hasExpirationTimestampMs {
jsonMap["expirationTimestampMs"] = "\(expirationTimestampMs)"
}
if hasLatitude {
jsonMap["latitude"] = NSNumber(double:latitude)
}
if hasLongitude {
jsonMap["longitude"] = NSNumber(double:longitude)
}
return jsonMap
}
override class public func decode(jsonMap:Dictionary<String,AnyObject>) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder.decodeToBuilder(jsonMap).build()
}
override class public func fromJSON(data:NSData) throws -> Pogoprotos.Map.Pokemon.MapPokemon {
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder.fromJSONToBuilder(data).build()
}
override public func getDescription(indent:String) throws -> String {
var output = ""
if hasSpawnPointId {
output += "\(indent) spawnPointId: \(spawnPointId) \n"
}
if hasEncounterId {
output += "\(indent) encounterId: \(encounterId) \n"
}
if (hasPokemonId) {
output += "\(indent) pokemonId: \(pokemonId.description)\n"
}
if hasExpirationTimestampMs {
output += "\(indent) expirationTimestampMs: \(expirationTimestampMs) \n"
}
if hasLatitude {
output += "\(indent) latitude: \(latitude) \n"
}
if hasLongitude {
output += "\(indent) longitude: \(longitude) \n"
}
output += unknownFields.getDescription(indent)
return output
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasSpawnPointId {
hashCode = (hashCode &* 31) &+ spawnPointId.hashValue
}
if hasEncounterId {
hashCode = (hashCode &* 31) &+ encounterId.hashValue
}
if hasPokemonId {
hashCode = (hashCode &* 31) &+ Int(pokemonId.rawValue)
}
if hasExpirationTimestampMs {
hashCode = (hashCode &* 31) &+ expirationTimestampMs.hashValue
}
if hasLatitude {
hashCode = (hashCode &* 31) &+ latitude.hashValue
}
if hasLongitude {
hashCode = (hashCode &* 31) &+ longitude.hashValue
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Pogoprotos.Map.Pokemon.MapPokemon"
}
override public func className() -> String {
return "Pogoprotos.Map.Pokemon.MapPokemon"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Pogoprotos.Map.Pokemon.MapPokemon.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Pogoprotos.Map.Pokemon.MapPokemon = Pogoprotos.Map.Pokemon.MapPokemon()
public func getMessage() -> Pogoprotos.Map.Pokemon.MapPokemon {
return builderResult
}
required override public init () {
super.init()
}
public var hasSpawnPointId:Bool {
get {
return builderResult.hasSpawnPointId
}
}
public var spawnPointId:String {
get {
return builderResult.spawnPointId
}
set (value) {
builderResult.hasSpawnPointId = true
builderResult.spawnPointId = value
}
}
public func setSpawnPointId(value:String) -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
self.spawnPointId = value
return self
}
public func clearSpawnPointId() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder{
builderResult.hasSpawnPointId = false
builderResult.spawnPointId = ""
return self
}
public var hasEncounterId:Bool {
get {
return builderResult.hasEncounterId
}
}
public var encounterId:UInt64 {
get {
return builderResult.encounterId
}
set (value) {
builderResult.hasEncounterId = true
builderResult.encounterId = value
}
}
public func setEncounterId(value:UInt64) -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
self.encounterId = value
return self
}
public func clearEncounterId() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder{
builderResult.hasEncounterId = false
builderResult.encounterId = UInt64(0)
return self
}
public var hasPokemonId:Bool{
get {
return builderResult.hasPokemonId
}
}
public var pokemonId:Pogoprotos.Enums.PokemonId {
get {
return builderResult.pokemonId
}
set (value) {
builderResult.hasPokemonId = true
builderResult.pokemonId = value
}
}
public func setPokemonId(value:Pogoprotos.Enums.PokemonId) -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
self.pokemonId = value
return self
}
public func clearPokemonId() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
builderResult.hasPokemonId = false
builderResult.pokemonId = .Missingno
return self
}
public var hasExpirationTimestampMs:Bool {
get {
return builderResult.hasExpirationTimestampMs
}
}
public var expirationTimestampMs:Int64 {
get {
return builderResult.expirationTimestampMs
}
set (value) {
builderResult.hasExpirationTimestampMs = true
builderResult.expirationTimestampMs = value
}
}
public func setExpirationTimestampMs(value:Int64) -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
self.expirationTimestampMs = value
return self
}
public func clearExpirationTimestampMs() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder{
builderResult.hasExpirationTimestampMs = false
builderResult.expirationTimestampMs = Int64(0)
return self
}
public var hasLatitude:Bool {
get {
return builderResult.hasLatitude
}
}
public var latitude:Double {
get {
return builderResult.latitude
}
set (value) {
builderResult.hasLatitude = true
builderResult.latitude = value
}
}
public func setLatitude(value:Double) -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
self.latitude = value
return self
}
public func clearLatitude() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder{
builderResult.hasLatitude = false
builderResult.latitude = Double(0)
return self
}
public var hasLongitude:Bool {
get {
return builderResult.hasLongitude
}
}
public var longitude:Double {
get {
return builderResult.longitude
}
set (value) {
builderResult.hasLongitude = true
builderResult.longitude = value
}
}
public func setLongitude(value:Double) -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
self.longitude = value
return self
}
public func clearLongitude() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder{
builderResult.hasLongitude = false
builderResult.longitude = Double(0)
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
override public func clear() -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
builderResult = Pogoprotos.Map.Pokemon.MapPokemon()
return self
}
override public func clone() throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
return try Pogoprotos.Map.Pokemon.MapPokemon.builderWithPrototype(builderResult)
}
override public func build() throws -> Pogoprotos.Map.Pokemon.MapPokemon {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Pogoprotos.Map.Pokemon.MapPokemon {
let returnMe:Pogoprotos.Map.Pokemon.MapPokemon = builderResult
return returnMe
}
public func mergeFrom(other:Pogoprotos.Map.Pokemon.MapPokemon) throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
if other == Pogoprotos.Map.Pokemon.MapPokemon() {
return self
}
if other.hasSpawnPointId {
spawnPointId = other.spawnPointId
}
if other.hasEncounterId {
encounterId = other.encounterId
}
if other.hasPokemonId {
pokemonId = other.pokemonId
}
if other.hasExpirationTimestampMs {
expirationTimestampMs = other.expirationTimestampMs
}
if other.hasLatitude {
latitude = other.latitude
}
if other.hasLongitude {
longitude = other.longitude
}
try mergeUnknownFields(other.unknownFields)
return self
}
override public func mergeFromCodedInputStream(input:CodedInputStream) throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
override public func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let protobufTag = try input.readTag()
switch protobufTag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10:
spawnPointId = try input.readString()
case 17:
encounterId = try input.readFixed64()
case 24:
let valueIntpokemonId = try input.readEnum()
if let enumspokemonId = Pogoprotos.Enums.PokemonId(rawValue:valueIntpokemonId){
pokemonId = enumspokemonId
} else {
try unknownFieldsBuilder.mergeVarintField(3, value:Int64(valueIntpokemonId))
}
case 32:
expirationTimestampMs = try input.readInt64()
case 41:
latitude = try input.readDouble()
case 49:
longitude = try input.readDouble()
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
override class public func decodeToBuilder(jsonMap:Dictionary<String,AnyObject>) throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
let resultDecodedBuilder = Pogoprotos.Map.Pokemon.MapPokemon.Builder()
if let jsonValueSpawnPointId = jsonMap["spawnPointId"] as? String {
resultDecodedBuilder.spawnPointId = jsonValueSpawnPointId
}
if let jsonValueEncounterId = jsonMap["encounterId"] as? String {
resultDecodedBuilder.encounterId = UInt64(jsonValueEncounterId)!
}
if let jsonValuePokemonId = jsonMap["pokemonId"] as? String {
resultDecodedBuilder.pokemonId = try Pogoprotos.Enums.PokemonId.fromString(jsonValuePokemonId)
}
if let jsonValueExpirationTimestampMs = jsonMap["expirationTimestampMs"] as? String {
resultDecodedBuilder.expirationTimestampMs = Int64(jsonValueExpirationTimestampMs)!
}
if let jsonValueLatitude = jsonMap["latitude"] as? NSNumber {
resultDecodedBuilder.latitude = jsonValueLatitude.doubleValue
}
if let jsonValueLongitude = jsonMap["longitude"] as? NSNumber {
resultDecodedBuilder.longitude = jsonValueLongitude.doubleValue
}
return resultDecodedBuilder
}
override class public func fromJSONToBuilder(data:NSData) throws -> Pogoprotos.Map.Pokemon.MapPokemon.Builder {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
guard let jsDataCast = jsonData as? Dictionary<String,AnyObject> else {
throw ProtocolBuffersError.InvalidProtocolBuffer("Invalid JSON data")
}
return try Pogoprotos.Map.Pokemon.MapPokemon.Builder.decodeToBuilder(jsDataCast)
}
}
}
final public class NearbyPokemon : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var pokemonId:Pogoprotos.Enums.PokemonId = Pogoprotos.Enums.PokemonId.Missingno
public private(set) var hasPokemonId:Bool = false
public private(set) var hasDistanceInMeters:Bool = false
public private(set) var distanceInMeters:Float = Float(0)
public private(set) var hasEncounterId:Bool = false
public private(set) var encounterId:UInt64 = UInt64(0)
public private(set) var hasFortId:Bool = false
public private(set) var fortId:String = ""
public private(set) var hasFortImageUrl:Bool = false
public private(set) var fortImageUrl:String = ""
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasPokemonId {
try output.writeEnum(1, value:pokemonId.rawValue)
}
if hasDistanceInMeters {
try output.writeFloat(2, value:distanceInMeters)
}
if hasEncounterId {
try output.writeFixed64(3, value:encounterId)
}
if hasFortId {
try output.writeString(4, value:fortId)
}
if hasFortImageUrl {
try output.writeString(5, value:fortImageUrl)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if (hasPokemonId) {
serialize_size += pokemonId.rawValue.computeEnumSize(1)
}
if hasDistanceInMeters {
serialize_size += distanceInMeters.computeFloatSize(2)
}
if hasEncounterId {
serialize_size += encounterId.computeFixed64Size(3)
}
if hasFortId {
serialize_size += fortId.computeStringSize(4)
}
if hasFortImageUrl {
serialize_size += fortImageUrl.computeStringSize(5)
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Pogoprotos.Map.Pokemon.NearbyPokemon> {
var mergedArray = Array<Pogoprotos.Map.Pokemon.NearbyPokemon>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon? {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeFromData(data, extensionRegistry:Pogoprotos.Map.Pokemon.PogoprotosMapPokemonRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
return Pogoprotos.Map.Pokemon.NearbyPokemon.classBuilder() as! Pogoprotos.Map.Pokemon.NearbyPokemon.Builder
}
public func getBuilder() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
return classBuilder() as! Pogoprotos.Map.Pokemon.NearbyPokemon.Builder
}
override public class func classBuilder() -> MessageBuilder {
return Pogoprotos.Map.Pokemon.NearbyPokemon.Builder()
}
override public func classBuilder() -> MessageBuilder {
return Pogoprotos.Map.Pokemon.NearbyPokemon.Builder()
}
public func toBuilder() throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Pogoprotos.Map.Pokemon.NearbyPokemon) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder().mergeFrom(prototype)
}
override public func encode() throws -> Dictionary<String,AnyObject> {
guard isInitialized() else {
throw ProtocolBuffersError.InvalidProtocolBuffer("Uninitialized Message")
}
var jsonMap:Dictionary<String,AnyObject> = Dictionary<String,AnyObject>()
if hasPokemonId {
jsonMap["pokemonId"] = pokemonId.toString()
}
if hasDistanceInMeters {
jsonMap["distanceInMeters"] = NSNumber(float:distanceInMeters)
}
if hasEncounterId {
jsonMap["encounterId"] = "\(encounterId)"
}
if hasFortId {
jsonMap["fortId"] = fortId
}
if hasFortImageUrl {
jsonMap["fortImageUrl"] = fortImageUrl
}
return jsonMap
}
override class public func decode(jsonMap:Dictionary<String,AnyObject>) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder.decodeToBuilder(jsonMap).build()
}
override class public func fromJSON(data:NSData) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder.fromJSONToBuilder(data).build()
}
override public func getDescription(indent:String) throws -> String {
var output = ""
if (hasPokemonId) {
output += "\(indent) pokemonId: \(pokemonId.description)\n"
}
if hasDistanceInMeters {
output += "\(indent) distanceInMeters: \(distanceInMeters) \n"
}
if hasEncounterId {
output += "\(indent) encounterId: \(encounterId) \n"
}
if hasFortId {
output += "\(indent) fortId: \(fortId) \n"
}
if hasFortImageUrl {
output += "\(indent) fortImageUrl: \(fortImageUrl) \n"
}
output += unknownFields.getDescription(indent)
return output
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasPokemonId {
hashCode = (hashCode &* 31) &+ Int(pokemonId.rawValue)
}
if hasDistanceInMeters {
hashCode = (hashCode &* 31) &+ distanceInMeters.hashValue
}
if hasEncounterId {
hashCode = (hashCode &* 31) &+ encounterId.hashValue
}
if hasFortId {
hashCode = (hashCode &* 31) &+ fortId.hashValue
}
if hasFortImageUrl {
hashCode = (hashCode &* 31) &+ fortImageUrl.hashValue
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Pogoprotos.Map.Pokemon.NearbyPokemon"
}
override public func className() -> String {
return "Pogoprotos.Map.Pokemon.NearbyPokemon"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Pogoprotos.Map.Pokemon.NearbyPokemon.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Pogoprotos.Map.Pokemon.NearbyPokemon = Pogoprotos.Map.Pokemon.NearbyPokemon()
public func getMessage() -> Pogoprotos.Map.Pokemon.NearbyPokemon {
return builderResult
}
required override public init () {
super.init()
}
public var hasPokemonId:Bool{
get {
return builderResult.hasPokemonId
}
}
public var pokemonId:Pogoprotos.Enums.PokemonId {
get {
return builderResult.pokemonId
}
set (value) {
builderResult.hasPokemonId = true
builderResult.pokemonId = value
}
}
public func setPokemonId(value:Pogoprotos.Enums.PokemonId) -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
self.pokemonId = value
return self
}
public func clearPokemonId() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
builderResult.hasPokemonId = false
builderResult.pokemonId = .Missingno
return self
}
public var hasDistanceInMeters:Bool {
get {
return builderResult.hasDistanceInMeters
}
}
public var distanceInMeters:Float {
get {
return builderResult.distanceInMeters
}
set (value) {
builderResult.hasDistanceInMeters = true
builderResult.distanceInMeters = value
}
}
public func setDistanceInMeters(value:Float) -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
self.distanceInMeters = value
return self
}
public func clearDistanceInMeters() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder{
builderResult.hasDistanceInMeters = false
builderResult.distanceInMeters = Float(0)
return self
}
public var hasEncounterId:Bool {
get {
return builderResult.hasEncounterId
}
}
public var encounterId:UInt64 {
get {
return builderResult.encounterId
}
set (value) {
builderResult.hasEncounterId = true
builderResult.encounterId = value
}
}
public func setEncounterId(value:UInt64) -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
self.encounterId = value
return self
}
public func clearEncounterId() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder{
builderResult.hasEncounterId = false
builderResult.encounterId = UInt64(0)
return self
}
public var hasFortId:Bool {
get {
return builderResult.hasFortId
}
}
public var fortId:String {
get {
return builderResult.fortId
}
set (value) {
builderResult.hasFortId = true
builderResult.fortId = value
}
}
public func setFortId(value:String) -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
self.fortId = value
return self
}
public func clearFortId() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder{
builderResult.hasFortId = false
builderResult.fortId = ""
return self
}
public var hasFortImageUrl:Bool {
get {
return builderResult.hasFortImageUrl
}
}
public var fortImageUrl:String {
get {
return builderResult.fortImageUrl
}
set (value) {
builderResult.hasFortImageUrl = true
builderResult.fortImageUrl = value
}
}
public func setFortImageUrl(value:String) -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
self.fortImageUrl = value
return self
}
public func clearFortImageUrl() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder{
builderResult.hasFortImageUrl = false
builderResult.fortImageUrl = ""
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
override public func clear() -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
builderResult = Pogoprotos.Map.Pokemon.NearbyPokemon()
return self
}
override public func clone() throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
return try Pogoprotos.Map.Pokemon.NearbyPokemon.builderWithPrototype(builderResult)
}
override public func build() throws -> Pogoprotos.Map.Pokemon.NearbyPokemon {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Pogoprotos.Map.Pokemon.NearbyPokemon {
let returnMe:Pogoprotos.Map.Pokemon.NearbyPokemon = builderResult
return returnMe
}
public func mergeFrom(other:Pogoprotos.Map.Pokemon.NearbyPokemon) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
if other == Pogoprotos.Map.Pokemon.NearbyPokemon() {
return self
}
if other.hasPokemonId {
pokemonId = other.pokemonId
}
if other.hasDistanceInMeters {
distanceInMeters = other.distanceInMeters
}
if other.hasEncounterId {
encounterId = other.encounterId
}
if other.hasFortId {
fortId = other.fortId
}
if other.hasFortImageUrl {
fortImageUrl = other.fortImageUrl
}
try mergeUnknownFields(other.unknownFields)
return self
}
override public func mergeFromCodedInputStream(input:CodedInputStream) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
override public func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let protobufTag = try input.readTag()
switch protobufTag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 8:
let valueIntpokemonId = try input.readEnum()
if let enumspokemonId = Pogoprotos.Enums.PokemonId(rawValue:valueIntpokemonId){
pokemonId = enumspokemonId
} else {
try unknownFieldsBuilder.mergeVarintField(1, value:Int64(valueIntpokemonId))
}
case 21:
distanceInMeters = try input.readFloat()
case 25:
encounterId = try input.readFixed64()
case 34:
fortId = try input.readString()
case 42:
fortImageUrl = try input.readString()
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
override class public func decodeToBuilder(jsonMap:Dictionary<String,AnyObject>) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
let resultDecodedBuilder = Pogoprotos.Map.Pokemon.NearbyPokemon.Builder()
if let jsonValuePokemonId = jsonMap["pokemonId"] as? String {
resultDecodedBuilder.pokemonId = try Pogoprotos.Enums.PokemonId.fromString(jsonValuePokemonId)
}
if let jsonValueDistanceInMeters = jsonMap["distanceInMeters"] as? NSNumber {
resultDecodedBuilder.distanceInMeters = jsonValueDistanceInMeters.floatValue
}
if let jsonValueEncounterId = jsonMap["encounterId"] as? String {
resultDecodedBuilder.encounterId = UInt64(jsonValueEncounterId)!
}
if let jsonValueFortId = jsonMap["fortId"] as? String {
resultDecodedBuilder.fortId = jsonValueFortId
}
if let jsonValueFortImageUrl = jsonMap["fortImageUrl"] as? String {
resultDecodedBuilder.fortImageUrl = jsonValueFortImageUrl
}
return resultDecodedBuilder
}
override class public func fromJSONToBuilder(data:NSData) throws -> Pogoprotos.Map.Pokemon.NearbyPokemon.Builder {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
guard let jsDataCast = jsonData as? Dictionary<String,AnyObject> else {
throw ProtocolBuffersError.InvalidProtocolBuffer("Invalid JSON data")
}
return try Pogoprotos.Map.Pokemon.NearbyPokemon.Builder.decodeToBuilder(jsDataCast)
}
}
}
final public class WildPokemon : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var hasEncounterId:Bool = false
public private(set) var encounterId:UInt64 = UInt64(0)
public private(set) var hasLastModifiedTimestampMs:Bool = false
public private(set) var lastModifiedTimestampMs:Int64 = Int64(0)
public private(set) var hasLatitude:Bool = false
public private(set) var latitude:Double = Double(0)
public private(set) var hasLongitude:Bool = false
public private(set) var longitude:Double = Double(0)
public private(set) var hasSpawnPointId:Bool = false
public private(set) var spawnPointId:String = ""
public private(set) var hasPokemonData:Bool = false
public private(set) var pokemonData:Pogoprotos.Data.PokemonData!
public private(set) var hasTimeTillHiddenMs:Bool = false
public private(set) var timeTillHiddenMs:Int32 = Int32(0)
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasEncounterId {
try output.writeFixed64(1, value:encounterId)
}
if hasLastModifiedTimestampMs {
try output.writeInt64(2, value:lastModifiedTimestampMs)
}
if hasLatitude {
try output.writeDouble(3, value:latitude)
}
if hasLongitude {
try output.writeDouble(4, value:longitude)
}
if hasSpawnPointId {
try output.writeString(5, value:spawnPointId)
}
if hasPokemonData {
try output.writeMessage(7, value:pokemonData)
}
if hasTimeTillHiddenMs {
try output.writeInt32(11, value:timeTillHiddenMs)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasEncounterId {
serialize_size += encounterId.computeFixed64Size(1)
}
if hasLastModifiedTimestampMs {
serialize_size += lastModifiedTimestampMs.computeInt64Size(2)
}
if hasLatitude {
serialize_size += latitude.computeDoubleSize(3)
}
if hasLongitude {
serialize_size += longitude.computeDoubleSize(4)
}
if hasSpawnPointId {
serialize_size += spawnPointId.computeStringSize(5)
}
if hasPokemonData {
if let varSizepokemonData = pokemonData?.computeMessageSize(7) {
serialize_size += varSizepokemonData
}
}
if hasTimeTillHiddenMs {
serialize_size += timeTillHiddenMs.computeInt32Size(11)
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Pogoprotos.Map.Pokemon.WildPokemon> {
var mergedArray = Array<Pogoprotos.Map.Pokemon.WildPokemon>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Pogoprotos.Map.Pokemon.WildPokemon? {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeFromData(data, extensionRegistry:Pogoprotos.Map.Pokemon.PogoprotosMapPokemonRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
return Pogoprotos.Map.Pokemon.WildPokemon.classBuilder() as! Pogoprotos.Map.Pokemon.WildPokemon.Builder
}
public func getBuilder() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
return classBuilder() as! Pogoprotos.Map.Pokemon.WildPokemon.Builder
}
override public class func classBuilder() -> MessageBuilder {
return Pogoprotos.Map.Pokemon.WildPokemon.Builder()
}
override public func classBuilder() -> MessageBuilder {
return Pogoprotos.Map.Pokemon.WildPokemon.Builder()
}
public func toBuilder() throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
return try Pogoprotos.Map.Pokemon.WildPokemon.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Pogoprotos.Map.Pokemon.WildPokemon) throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder().mergeFrom(prototype)
}
override public func encode() throws -> Dictionary<String,AnyObject> {
guard isInitialized() else {
throw ProtocolBuffersError.InvalidProtocolBuffer("Uninitialized Message")
}
var jsonMap:Dictionary<String,AnyObject> = Dictionary<String,AnyObject>()
if hasEncounterId {
jsonMap["encounterId"] = "\(encounterId)"
}
if hasLastModifiedTimestampMs {
jsonMap["lastModifiedTimestampMs"] = "\(lastModifiedTimestampMs)"
}
if hasLatitude {
jsonMap["latitude"] = NSNumber(double:latitude)
}
if hasLongitude {
jsonMap["longitude"] = NSNumber(double:longitude)
}
if hasSpawnPointId {
jsonMap["spawnPointId"] = spawnPointId
}
if hasPokemonData {
jsonMap["pokemonData"] = try pokemonData.encode()
}
if hasTimeTillHiddenMs {
jsonMap["timeTillHiddenMs"] = NSNumber(int:timeTillHiddenMs)
}
return jsonMap
}
override class public func decode(jsonMap:Dictionary<String,AnyObject>) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder.decodeToBuilder(jsonMap).build()
}
override class public func fromJSON(data:NSData) throws -> Pogoprotos.Map.Pokemon.WildPokemon {
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder.fromJSONToBuilder(data).build()
}
override public func getDescription(indent:String) throws -> String {
var output = ""
if hasEncounterId {
output += "\(indent) encounterId: \(encounterId) \n"
}
if hasLastModifiedTimestampMs {
output += "\(indent) lastModifiedTimestampMs: \(lastModifiedTimestampMs) \n"
}
if hasLatitude {
output += "\(indent) latitude: \(latitude) \n"
}
if hasLongitude {
output += "\(indent) longitude: \(longitude) \n"
}
if hasSpawnPointId {
output += "\(indent) spawnPointId: \(spawnPointId) \n"
}
if hasPokemonData {
output += "\(indent) pokemonData {\n"
if let outDescPokemonData = pokemonData {
output += try outDescPokemonData.getDescription("\(indent) ")
}
output += "\(indent) }\n"
}
if hasTimeTillHiddenMs {
output += "\(indent) timeTillHiddenMs: \(timeTillHiddenMs) \n"
}
output += unknownFields.getDescription(indent)
return output
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasEncounterId {
hashCode = (hashCode &* 31) &+ encounterId.hashValue
}
if hasLastModifiedTimestampMs {
hashCode = (hashCode &* 31) &+ lastModifiedTimestampMs.hashValue
}
if hasLatitude {
hashCode = (hashCode &* 31) &+ latitude.hashValue
}
if hasLongitude {
hashCode = (hashCode &* 31) &+ longitude.hashValue
}
if hasSpawnPointId {
hashCode = (hashCode &* 31) &+ spawnPointId.hashValue
}
if hasPokemonData {
if let hashValuepokemonData = pokemonData?.hashValue {
hashCode = (hashCode &* 31) &+ hashValuepokemonData
}
}
if hasTimeTillHiddenMs {
hashCode = (hashCode &* 31) &+ timeTillHiddenMs.hashValue
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Pogoprotos.Map.Pokemon.WildPokemon"
}
override public func className() -> String {
return "Pogoprotos.Map.Pokemon.WildPokemon"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Pogoprotos.Map.Pokemon.WildPokemon.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Pogoprotos.Map.Pokemon.WildPokemon = Pogoprotos.Map.Pokemon.WildPokemon()
public func getMessage() -> Pogoprotos.Map.Pokemon.WildPokemon {
return builderResult
}
required override public init () {
super.init()
}
public var hasEncounterId:Bool {
get {
return builderResult.hasEncounterId
}
}
public var encounterId:UInt64 {
get {
return builderResult.encounterId
}
set (value) {
builderResult.hasEncounterId = true
builderResult.encounterId = value
}
}
public func setEncounterId(value:UInt64) -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
self.encounterId = value
return self
}
public func clearEncounterId() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder{
builderResult.hasEncounterId = false
builderResult.encounterId = UInt64(0)
return self
}
public var hasLastModifiedTimestampMs:Bool {
get {
return builderResult.hasLastModifiedTimestampMs
}
}
public var lastModifiedTimestampMs:Int64 {
get {
return builderResult.lastModifiedTimestampMs
}
set (value) {
builderResult.hasLastModifiedTimestampMs = true
builderResult.lastModifiedTimestampMs = value
}
}
public func setLastModifiedTimestampMs(value:Int64) -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
self.lastModifiedTimestampMs = value
return self
}
public func clearLastModifiedTimestampMs() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder{
builderResult.hasLastModifiedTimestampMs = false
builderResult.lastModifiedTimestampMs = Int64(0)
return self
}
public var hasLatitude:Bool {
get {
return builderResult.hasLatitude
}
}
public var latitude:Double {
get {
return builderResult.latitude
}
set (value) {
builderResult.hasLatitude = true
builderResult.latitude = value
}
}
public func setLatitude(value:Double) -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
self.latitude = value
return self
}
public func clearLatitude() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder{
builderResult.hasLatitude = false
builderResult.latitude = Double(0)
return self
}
public var hasLongitude:Bool {
get {
return builderResult.hasLongitude
}
}
public var longitude:Double {
get {
return builderResult.longitude
}
set (value) {
builderResult.hasLongitude = true
builderResult.longitude = value
}
}
public func setLongitude(value:Double) -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
self.longitude = value
return self
}
public func clearLongitude() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder{
builderResult.hasLongitude = false
builderResult.longitude = Double(0)
return self
}
public var hasSpawnPointId:Bool {
get {
return builderResult.hasSpawnPointId
}
}
public var spawnPointId:String {
get {
return builderResult.spawnPointId
}
set (value) {
builderResult.hasSpawnPointId = true
builderResult.spawnPointId = value
}
}
public func setSpawnPointId(value:String) -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
self.spawnPointId = value
return self
}
public func clearSpawnPointId() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder{
builderResult.hasSpawnPointId = false
builderResult.spawnPointId = ""
return self
}
public var hasPokemonData:Bool {
get {
return builderResult.hasPokemonData
}
}
public var pokemonData:Pogoprotos.Data.PokemonData! {
get {
if pokemonDataBuilder_ != nil {
builderResult.pokemonData = pokemonDataBuilder_.getMessage()
}
return builderResult.pokemonData
}
set (value) {
builderResult.hasPokemonData = true
builderResult.pokemonData = value
}
}
private var pokemonDataBuilder_:Pogoprotos.Data.PokemonData.Builder! {
didSet {
builderResult.hasPokemonData = true
}
}
public func getPokemonDataBuilder() -> Pogoprotos.Data.PokemonData.Builder {
if pokemonDataBuilder_ == nil {
pokemonDataBuilder_ = Pogoprotos.Data.PokemonData.Builder()
builderResult.pokemonData = pokemonDataBuilder_.getMessage()
if pokemonData != nil {
try! pokemonDataBuilder_.mergeFrom(pokemonData)
}
}
return pokemonDataBuilder_
}
public func setPokemonData(value:Pogoprotos.Data.PokemonData!) -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
self.pokemonData = value
return self
}
public func mergePokemonData(value:Pogoprotos.Data.PokemonData) throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
if builderResult.hasPokemonData {
builderResult.pokemonData = try Pogoprotos.Data.PokemonData.builderWithPrototype(builderResult.pokemonData).mergeFrom(value).buildPartial()
} else {
builderResult.pokemonData = value
}
builderResult.hasPokemonData = true
return self
}
public func clearPokemonData() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
pokemonDataBuilder_ = nil
builderResult.hasPokemonData = false
builderResult.pokemonData = nil
return self
}
public var hasTimeTillHiddenMs:Bool {
get {
return builderResult.hasTimeTillHiddenMs
}
}
public var timeTillHiddenMs:Int32 {
get {
return builderResult.timeTillHiddenMs
}
set (value) {
builderResult.hasTimeTillHiddenMs = true
builderResult.timeTillHiddenMs = value
}
}
public func setTimeTillHiddenMs(value:Int32) -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
self.timeTillHiddenMs = value
return self
}
public func clearTimeTillHiddenMs() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder{
builderResult.hasTimeTillHiddenMs = false
builderResult.timeTillHiddenMs = Int32(0)
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
override public func clear() -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
builderResult = Pogoprotos.Map.Pokemon.WildPokemon()
return self
}
override public func clone() throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
return try Pogoprotos.Map.Pokemon.WildPokemon.builderWithPrototype(builderResult)
}
override public func build() throws -> Pogoprotos.Map.Pokemon.WildPokemon {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Pogoprotos.Map.Pokemon.WildPokemon {
let returnMe:Pogoprotos.Map.Pokemon.WildPokemon = builderResult
return returnMe
}
public func mergeFrom(other:Pogoprotos.Map.Pokemon.WildPokemon) throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
if other == Pogoprotos.Map.Pokemon.WildPokemon() {
return self
}
if other.hasEncounterId {
encounterId = other.encounterId
}
if other.hasLastModifiedTimestampMs {
lastModifiedTimestampMs = other.lastModifiedTimestampMs
}
if other.hasLatitude {
latitude = other.latitude
}
if other.hasLongitude {
longitude = other.longitude
}
if other.hasSpawnPointId {
spawnPointId = other.spawnPointId
}
if (other.hasPokemonData) {
try mergePokemonData(other.pokemonData)
}
if other.hasTimeTillHiddenMs {
timeTillHiddenMs = other.timeTillHiddenMs
}
try mergeUnknownFields(other.unknownFields)
return self
}
override public func mergeFromCodedInputStream(input:CodedInputStream) throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
override public func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let protobufTag = try input.readTag()
switch protobufTag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 9:
encounterId = try input.readFixed64()
case 16:
lastModifiedTimestampMs = try input.readInt64()
case 25:
latitude = try input.readDouble()
case 33:
longitude = try input.readDouble()
case 42:
spawnPointId = try input.readString()
case 58:
let subBuilder:Pogoprotos.Data.PokemonData.Builder = Pogoprotos.Data.PokemonData.Builder()
if hasPokemonData {
try subBuilder.mergeFrom(pokemonData)
}
try input.readMessage(subBuilder, extensionRegistry:extensionRegistry)
pokemonData = subBuilder.buildPartial()
case 88:
timeTillHiddenMs = try input.readInt32()
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
override class public func decodeToBuilder(jsonMap:Dictionary<String,AnyObject>) throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
let resultDecodedBuilder = Pogoprotos.Map.Pokemon.WildPokemon.Builder()
if let jsonValueEncounterId = jsonMap["encounterId"] as? String {
resultDecodedBuilder.encounterId = UInt64(jsonValueEncounterId)!
}
if let jsonValueLastModifiedTimestampMs = jsonMap["lastModifiedTimestampMs"] as? String {
resultDecodedBuilder.lastModifiedTimestampMs = Int64(jsonValueLastModifiedTimestampMs)!
}
if let jsonValueLatitude = jsonMap["latitude"] as? NSNumber {
resultDecodedBuilder.latitude = jsonValueLatitude.doubleValue
}
if let jsonValueLongitude = jsonMap["longitude"] as? NSNumber {
resultDecodedBuilder.longitude = jsonValueLongitude.doubleValue
}
if let jsonValueSpawnPointId = jsonMap["spawnPointId"] as? String {
resultDecodedBuilder.spawnPointId = jsonValueSpawnPointId
}
if let jsonValuePokemonData = jsonMap["pokemonData"] as? Dictionary<String,AnyObject> {
resultDecodedBuilder.pokemonData = try Pogoprotos.Data.PokemonData.Builder.decodeToBuilder(jsonValuePokemonData).build()
}
if let jsonValueTimeTillHiddenMs = jsonMap["timeTillHiddenMs"] as? NSNumber {
resultDecodedBuilder.timeTillHiddenMs = jsonValueTimeTillHiddenMs.intValue
}
return resultDecodedBuilder
}
override class public func fromJSONToBuilder(data:NSData) throws -> Pogoprotos.Map.Pokemon.WildPokemon.Builder {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
guard let jsDataCast = jsonData as? Dictionary<String,AnyObject> else {
throw ProtocolBuffersError.InvalidProtocolBuffer("Invalid JSON data")
}
return try Pogoprotos.Map.Pokemon.WildPokemon.Builder.decodeToBuilder(jsDataCast)
}
}
}
}
// @@protoc_insertion_point(global_scope)
| gpl-3.0 |
Book11/sinaWeibo | SinaWeibo02/SinaWeibo02UITests/SinaWeibo02UITests.swift | 1 | 1245 | //
// SinaWeibo02UITests.swift
// SinaWeibo02UITests
//
// Created by Macx on 16/4/13.
// Copyright © 2016年 Macx. All rights reserved.
//
import XCTest
class SinaWeibo02UITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
RiBj1993/CodeRoute | TableViewController.swift | 1 | 3124 | //
// TableViewController.swift
// LoginForm
//
// Created by SwiftR on 06/03/2017.
// Copyright © 2017 vishalsonawane. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func 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 |
jiamao130/DouYuSwift | DouYuBroad/DouYuBroad/Home/Controller/AmuseViewController.swift | 1 | 1271 | //
// AmuseViewController.swift
// DouYuBroad
//
// Created by 贾卯 on 2017/8/14.
// Copyright © 2017年 贾卯. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200
class AmuseViewController: BaseAnchorController {
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
}
extension AmuseViewController{
override func setupUI() {
super.setupUI()
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
extension AmuseViewController{
override func loadData(){
baseVM = amuseVM
amuseVM.loadAmuseData {
self.collectionView.reloadData()
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
self.loadDataFinished()
}
}
}
| mit |
nicolaschriste/MoreFoundation | MoreFoundation/Applicable.swift | 1 | 1879 | /// Copyright (c) 2017-18 Nicolas Christe
///
/// 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
/// Syntaxic sugar for class missing constructor
/// example:
/// ```
/// let dateFormatter = DateFormatter().apply {
/// $0.dateStyle = .long
/// }
/// ```
public protocol Applicable {}
// MARK: - Extension for Any
public extension Applicable where Self: Any {
func apply(_ block: (inout Self) throws -> Void) rethrows -> Self {
var mutableSelf = self
try block(&mutableSelf)
return mutableSelf
}
}
// MARK: - Extension for AnyObject
public extension Applicable where Self: AnyObject {
func apply(_ block: (Self) throws -> Void) rethrows -> Self {
try block(self)
return self
}
}
// MARK: - Add apply common types
extension NSObject: Applicable {}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/25840-swift-valuedecl-overwritetype.swift | 11 | 433 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
if{{{func d}a}enum S<T where B:a{class m
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/01806-swift-typechecker-validatedecl.swift | 11 | 521 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func a: a {
protocol f : a {
typealias b : ih ml]
enum b : Range<d>(f<U, j: Sequence, U) as a<e
protocol a {
r : T! {
}
struct d
| apache-2.0 |
wikimedia/wikipedia-ios | WMF Framework/ColumnarCollectionViewLayoutMetrics.swift | 4 | 4328 | public struct ColumnarCollectionViewLayoutMetrics {
public static let defaultItemLayoutMargins = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15) // individual cells on each explore card
public static let defaultExploreItemLayoutMargins = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15) // explore card cells
let boundsSize: CGSize
let layoutMargins: UIEdgeInsets
let countOfColumns: Int
let itemLayoutMargins: UIEdgeInsets
let readableWidth: CGFloat
let interSectionSpacing: CGFloat
let interColumnSpacing: CGFloat
let interItemSpacing: CGFloat
var shouldMatchColumnHeights = false
public static func exploreViewMetrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
let useTwoColumns = boundsSize.width >= 600 || (boundsSize.width > boundsSize.height && readableWidth >= 500)
let countOfColumns = useTwoColumns ? 2 : 1
let interColumnSpacing: CGFloat = useTwoColumns ? 20 : 0
let interItemSpacing: CGFloat = 35
let interSectionSpacing: CGFloat = useTwoColumns ? 20 : 0
let layoutMarginsForMetrics: UIEdgeInsets
let itemLayoutMargins: UIEdgeInsets
let defaultItemMargins = ColumnarCollectionViewLayoutMetrics.defaultExploreItemLayoutMargins
let topAndBottomMargin: CGFloat = 30 // space between top of navigation bar and first section
if useTwoColumns {
let itemMarginWidth = max(defaultItemMargins.left, defaultItemMargins.right)
let marginWidth = max(max(max(layoutMargins.left, layoutMargins.right), round(0.5 * (boundsSize.width - (readableWidth * CGFloat(countOfColumns))))), itemMarginWidth)
layoutMarginsForMetrics = UIEdgeInsets(top: topAndBottomMargin, left: marginWidth - itemMarginWidth, bottom: topAndBottomMargin, right: marginWidth - itemMarginWidth)
itemLayoutMargins = UIEdgeInsets(top: defaultItemMargins.top, left: itemMarginWidth, bottom: defaultItemMargins.bottom, right: itemMarginWidth)
} else {
let marginWidth = max(layoutMargins.left, layoutMargins.right)
itemLayoutMargins = UIEdgeInsets(top: defaultItemMargins.top, left: marginWidth, bottom: defaultItemMargins.bottom, right: marginWidth)
layoutMarginsForMetrics = UIEdgeInsets(top: topAndBottomMargin, left: 0, bottom: topAndBottomMargin, right: 0)
}
return ColumnarCollectionViewLayoutMetrics(boundsSize: boundsSize, layoutMargins: layoutMarginsForMetrics, countOfColumns: countOfColumns, itemLayoutMargins: itemLayoutMargins, readableWidth: readableWidth, interSectionSpacing: interSectionSpacing, interColumnSpacing: interColumnSpacing, interItemSpacing: interItemSpacing, shouldMatchColumnHeights: false)
}
public static func tableViewMetrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets, interSectionSpacing: CGFloat = 0, interItemSpacing: CGFloat = 0) -> ColumnarCollectionViewLayoutMetrics {
let marginWidth = max(max(layoutMargins.left, layoutMargins.right), round(0.5 * (boundsSize.width - readableWidth)))
var itemLayoutMargins = ColumnarCollectionViewLayoutMetrics.defaultItemLayoutMargins
itemLayoutMargins.left = max(marginWidth, itemLayoutMargins.left)
itemLayoutMargins.right = max(marginWidth, itemLayoutMargins.right)
return ColumnarCollectionViewLayoutMetrics(boundsSize: boundsSize, layoutMargins: .zero, countOfColumns: 1, itemLayoutMargins: itemLayoutMargins, readableWidth: readableWidth, interSectionSpacing: interSectionSpacing, interColumnSpacing: 0, interItemSpacing: interItemSpacing, shouldMatchColumnHeights: false)
}
public static func exploreCardMetrics(with boundsSize: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
let itemLayoutMargins = ColumnarCollectionViewLayoutMetrics.defaultItemLayoutMargins
return ColumnarCollectionViewLayoutMetrics(boundsSize: boundsSize, layoutMargins: layoutMargins, countOfColumns: 1, itemLayoutMargins: itemLayoutMargins, readableWidth: readableWidth, interSectionSpacing: 0, interColumnSpacing: 0, interItemSpacing: 0, shouldMatchColumnHeights: false)
}
}
| mit |
exercism/xswift | exercises/twelve-days/Sources/TwelveDays/TwelveDaysExample.swift | 1 | 1404 | struct TwelveDaysSong {
private static let ordinals = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]
private static let gifts = ["a Partridge in a Pear Tree", "two Turtle Doves", "three French Hens", "four Calling Birds", "five Gold Rings", "six Geese-a-Laying", "seven Swans-a-Swimming", "eight Maids-a-Milking", "nine Ladies Dancing", "ten Lords-a-Leaping", "eleven Pipers Piping", "twelve Drummers Drumming"]
static func verse(_ verseNumber: Int) -> String {
let ordinal = ordinals[verseNumber - 1]
var verse = "On the \(ordinal) day of Christmas my true love gave to me: "
verse += gifts(forNumber: verseNumber)
return verse
}
static func verses(_ start: Int, _ end: Int) -> String {
var verses = [String]()
for i in start...end {
verses.append(verse(i))
}
return verses.joined(separator: "\n")
}
static func sing() -> String {
return verses(1, 12)
}
private static func gifts(forNumber number: Int) -> String {
let gift = gifts[number - 1]
if number == 1 {
return "\(gift)."
} else if number == 2 {
return "\(gift), and \(gifts(forNumber: number - 1))"
} else {
return "\(gift), \(gifts(forNumber: number - 1))"
}
}
}
| mit |
DungntVccorp/Game | game-server/Sources/game-server/OperationKeepAlive.swift | 1 | 698 | //
// OperationKeepAlive.swift
// P
//
// Created by Nguyen Dung on 5/3/17.
//
//
class OperationKeepAlive : ConcurrentOperation{
override func TcpExcute() -> (Int, replyMsg: GSProtocolMessage?) {
var rep = Pcomm_KeepAlive.Reply()
rep.apiReply.time = 1234
rep.apiReply.type = 0
do{
let data = try rep.serializedData()
let msg = GSProtocolMessage()
msg.headCodeId = GSProtocolMessageType.headCode.profile
msg.subCodeId = GSProtocolMessageType.subCode.profile_KeepAlive
msg.protoContent = data
return (0,msg)
}catch{
return (-1,nil)
}
}
}
| mit |
Benoitcn/Upli | Upli/Upli/SetUpProfileStep3.swift | 1 | 1167 | //
// SetUpProfileStep3.swift
// Upli
//
// Created by 王毅 on 15/5/12.
// Copyright (c) 2015年 Ted. All rights reserved.
//
import UIKit
class SetUpProfileStep3 {
var titleLabel: String
var pickval:NSArray
class func allSetUpProfileStep3() -> [SetUpProfileStep3] {
var setUpProfileStep3s = [SetUpProfileStep3]()
if let URL = NSBundle.mainBundle().URLForResource("SetUpProfileStep3Item", withExtension: "plist") {
if let sessionsFromPlist = NSArray(contentsOfURL: URL) {
for dictionary in sessionsFromPlist {
let setUpProfileStep3 = SetUpProfileStep3(dictionary: dictionary as! NSDictionary)
setUpProfileStep3s.append(setUpProfileStep3)
}
}
}
return setUpProfileStep3s
}
init(title: String,pickval:NSArray) {
self.titleLabel = title
self.pickval=pickval
}
convenience init(dictionary: NSDictionary) {
let title = dictionary["Title"] as? String
let pickval=dictionary["Pick"]as? NSArray
self.init(title: title!,pickval:pickval!)
}
}
| apache-2.0 |
IvanVorobei/Sparrow | sparrow/device/SPDevice.swift | 1 | 1361 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
struct SPDevice {
static var isIphone: Bool {
return UIDevice.current.isIphone()
}
static var isIpad: Bool {
return UIDevice.current.isIpad()
}
}
| mit |
m-alani/contests | hackerrank/Pangrams.swift | 1 | 659 | //
// Pangrams.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/pangrams
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
import Foundation
// Get the input
let input = Array(String(readLine()!)!.lowercased().characters)
// Solve the mystery
var alphabet = Set("abcdefghijklmnopqrstuvwxyz".characters)
var output = "not pangram"
for letter in input {
alphabet.remove(letter)
if (alphabet.count == 0) {
output = "pangram"
break
}
}
// Print the output
print(output)
| mit |
AttilaTheFun/SwaggerParser | Sources/APIKeySchema.swift | 1 | 571 |
public struct APIKeySchema {
public let headerName: String
public let keyLocation: APIKeyLocation
}
struct APIKeySchemaBuilder: Codable {
let headerName: String
let keyLocation: APIKeyLocation
enum CodingKeys: String, CodingKey {
case headerName = "name"
case keyLocation = "in"
}
}
extension APIKeySchemaBuilder: Builder {
typealias Building = APIKeySchema
func build(_ swagger: SwaggerBuilder) throws -> APIKeySchema {
return APIKeySchema(headerName: self.headerName, keyLocation: self.keyLocation)
}
}
| mit |
maxbritto/cours-ios11-swift4 | swift_4_cours_complet.playground/Pages/Lazy.xcplaygroundpage/Contents.swift | 1 | 847 | //: [< Sommaire](Sommaire)
/*:
# Propriétés Lazy
---
### Maxime Britto - Swift 4
*/
struct Player {
var firstname:String
var lastname:String
var score = 0
lazy var fullname = firstname + " " + lastname
var fullname_computed: String {
return firstname + " " + lastname
}
lazy var fullname_computed_lazy: String = {
return firstname + " " + lastname
}()
init(firstname:String, lastname:String) {
self.firstname = firstname
self.lastname = lastname
}
}
var p1 = Player(firstname: "Arya", lastname: "Stark")
print(p1.fullname)
print(p1.fullname_computed)
print("fullname_computed_lazy : " + p1.fullname_computed_lazy)
p1.firstname = "Eddard"
print(p1.fullname_computed)
print("fullname_computed_lazy : " + p1.fullname_computed_lazy)
/*:
[< Sommaire](Sommaire)
*/
| apache-2.0 |
BarbaraBoeters/barbaraboeters-project | barbaraboeters-project/AppDelegate.swift | 1 | 935 | //
// AppDelegate.swift
// barbaraboeters-project
//
// Establishes the connection to the different frameworks (Firebase, IQKeyboardManagerSwift, CoreLocation)
// Source: https://github.com/hackiftekhar/IQKeyboardManager
//
// Created by Barbara Boeters on 09-01-17.
// Copyright © 2017 Barbara Boeters. All rights reserved.
//
import UIKit
import Firebase
import IQKeyboardManagerSwift
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
IQKeyboardManager.sharedManager().enable = true
FIRApp.configure()
FIRDatabase.database().persistenceEnabled = true
locationManager.requestAlwaysAuthorization()
return true
}
}
| bsd-2-clause |
beckjing/contacts | contacts/contacts/contact/View/JYCContactOperationTableViewCell/JYCContactOperationTableViewCell.swift | 1 | 522 | //
// JYCContactOperationTableViewCell.swift
// contacts
//
// Created by yuecheng on 23/06/2017.
// Copyright © 2017 yuecheng. All rights reserved.
//
import UIKit
class JYCContactOperationTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
mbeloded/beaconDemo | PassKitApp/PassKitApp/Classes/UI/Category/CategoryView.swift | 1 | 3589 | //
// CategoryView.swift
// PassKitApp
//
// Created by Alexandr Chernyy on 10/3/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import UIKit
var cellIdentBanner = "CategoryBannerCell"
var cellIdentBannerDetails = "CategoryBannerDetailsCell"
class CategoryView: UIView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView:UITableView!
@IBOutlet var bannnerView:BannerView!
var owner:UIViewController!
var mall_id:String!
var category_id:String!
var items:Array<AnyObject> = []
func setupView(mall_id_:String, category_id_:String)
{
mall_id = mall_id_
category_id = category_id_
bannnerView.setupView(mall_id_)
items = CoreDataManager.sharedManager.loadData(RequestType.STORE, key:category_id)
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
var item = items[indexPath.row] as StoreModel
var height:CGFloat = 0.0
if(item.isSelected)
{
height = 239.0
} else {
height = 118.0
}
return height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var item = items[indexPath.row] as StoreModel
var banners:Array<AnyObject> = CoreDataManager.sharedManager.loadData(RequestType.BANNER, key: item.banner_id)
var banner:BannerModel!
if(banners.count > 0)
{
banner = banners[0] as BannerModel
}
var url:String = banner.image
var parsed_url:NSString = url.stringByReplacingOccurrencesOfString("%20", withString: " ", options: nil, range: nil)
var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(parsed_url.lastPathComponent)");
println(pngPath)
var cell:UITableViewCell!
if(item.isSelected)
{
cell = tableView.dequeueReusableCellWithIdentifier(cellIdentBannerDetails) as CategoryBannerDetailsCell!
if (cell == nil) {
cell = CategoryBannerDetailsCell(style:.Default, reuseIdentifier: cellIdentBannerDetails)
}
(cell as CategoryBannerDetailsCell).bannerView.image = UIImage(named: pngPath)
(cell as CategoryBannerDetailsCell).titleLabel.text = item.name
(cell as CategoryBannerDetailsCell).detailsLabel.text = item.details
} else {
cell = tableView.dequeueReusableCellWithIdentifier(cellIdentBanner) as CategoryBannerCell!
if (cell == nil) {
cell = CategoryBannerCell(style:.Default, reuseIdentifier: cellIdentBanner)
}
(cell as CategoryBannerCell).bannerView.image = UIImage(named: pngPath)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
var item = items[indexPath.row] as StoreModel
if(item.isSelected)
{
item.isSelected = false
} else {
item.isSelected = true
}
tableView.reloadData()
// tableView.reloadRowsAtIndexPaths(indexPath, withRowAnimation: UITableViewRowAnimation.Automatic)
//owner?.performSegueWithIdentifier("showItems", sender: owner)
}
}
| gpl-2.0 |
Fibiola/cat-years | CAT yearsTests/CAT_yearsTests.swift | 1 | 919 | //
// CAT_yearsTests.swift
// CAT yearsTests
//
// Created by Natasa Pristovsek on 16/09/14.
// Copyright (c) 2014 Natasa Pristovsek. All rights reserved.
//
import UIKit
import XCTest
class CAT_yearsTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
byss/KBAPISupport | KBAPISupport/Core/Internal/InputStream+readAll.swift | 1 | 1398 | //
// InputStream+readAll.swift
// CPCommon
//
// Created by Kirill Bystrov on 9/18/18.
//
import Foundation
internal extension InputStream {
private enum Error: Swift.Error {
case unknownReadFailure;
}
internal func readAll (_ dataCallback: (UnsafeRawPointer, Int) throws -> ()) throws {
var buffer = vm_address_t (0);
guard (vm_allocate (mach_task_self_, &buffer, vm_page_size, VM_FLAGS_ANYWHERE) == KERN_SUCCESS) else {
return;
}
defer {
vm_deallocate (mach_task_self_, buffer, vm_page_size);
}
guard let bufferPointer = UnsafeMutablePointer <UInt8> (bitPattern: buffer) else {
return;
}
while (self.hasBytesAvailable) {
switch (self.read (bufferPointer, maxLength: .streamPassthroughBufferSize)) {
case 0:
return;
case -1:
throw self.streamError ?? Error.unknownReadFailure;
case (let readResult):
try dataCallback (UnsafeRawPointer (bufferPointer), readResult);
}
}
}
}
fileprivate extension Int {
fileprivate static let streamPassthroughBufferSize = Int (bitPattern: vm_page_size);
}
#if arch (i386) || arch (arm) || arch (arm64_32)
fileprivate extension UnsafeMutablePointer where Pointee == UInt8 {
fileprivate init? (bitPattern: vm_size_t) {
self.init (bitPattern: Int (bitPattern: bitPattern));
}
}
fileprivate extension Int {
fileprivate init (bitPattern: vm_size_t) {
self.init (bitPattern);
}
}
#endif
| mit |
dougbeal/Cartography | Cartography/LayoutProxy.swift | 4 | 5418 | //
// LayoutProxy.swift
// Cartography
//
// Created by Robert Böhnke on 17/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
import Foundation
public struct LayoutProxy {
/// The width of the view.
public var width: Dimension {
return Dimension(context, view, .Width)
}
/// The height of the view.
public var height: Dimension {
return Dimension(context, view, .Height)
}
/// The size of the view. This property affects both `width` and `height`.
public var size: Size {
return Size(context, [
Dimension(context, view, .Width),
Dimension(context, view, .Height)
])
}
/// The top edge of the view.
public var top: Edge {
return Edge(context, view, .Top)
}
/// The right edge of the view.
public var right: Edge {
return Edge(context, view, .Right)
}
/// The bottom edge of the view.
public var bottom: Edge {
return Edge(context, view, .Bottom)
}
/// The left edge of the view.
public var left: Edge {
return Edge(context, view, .Left)
}
/// All edges of the view. This property affects `top`, `bottom`, `leading`
/// and `trailing`.
public var edges: Edges {
return Edges(context, [
Edge(context, view, .Top),
Edge(context, view, .Leading),
Edge(context, view, .Bottom),
Edge(context, view, .Trailing)
])
}
/// The leading edge of the view.
public var leading: Edge {
return Edge(context, view, .Leading)
}
/// The trailing edge of the view.
public var trailing: Edge {
return Edge(context, view, .Trailing)
}
/// The horizontal center of the view.
public var centerX: Edge {
return Edge(context, view, .CenterX)
}
/// The vertical center of the view.
public var centerY: Edge {
return Edge(context, view, .CenterY)
}
/// The center point of the view. This property affects `centerX` and
/// `centerY`.
public var center: Point {
return Point(context, [
Edge(context, view, .CenterX),
Edge(context, view, .CenterY)
])
}
/// The baseline of the view.
public var baseline: Edge {
return Edge(context, view, .Baseline)
}
#if os(iOS) || os(tvOS)
/// The first baseline of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var firstBaseline: Edge {
return Edge(context, view, .FirstBaseline)
}
/// All edges of the view with their respective margins. This property
/// affects `topMargin`, `bottomMargin`, `leadingMargin` and
/// `trailingMargin`.
@available(iOS, introduced=8.0)
public var edgesWithinMargins: Edges {
return Edges(context, [
Edge(context, view, .TopMargin),
Edge(context, view, .LeadingMargin),
Edge(context, view, .BottomMargin),
Edge(context, view, .TrailingMargin)
])
}
/// The left margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var leftMargin: Edge {
return Edge(context, view, .LeftMargin)
}
/// The right margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var rightMargin: Edge {
return Edge(context, view, .RightMargin)
}
/// The top margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var topMargin: Edge {
return Edge(context, view, .TopMargin)
}
/// The bottom margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var bottomMargin: Edge {
return Edge(context, view, .BottomMargin)
}
/// The leading margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var leadingMargin: Edge {
return Edge(context, view, .LeadingMargin)
}
/// The trailing margin of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var trailingMargin: Edge {
return Edge(context, view, .TrailingMargin)
}
/// The horizontal center within the margins of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var centerXWithinMargins: Edge {
return Edge(context, view, .CenterXWithinMargins)
}
/// The vertical center within the margins of the view. iOS exclusive.
@available(iOS, introduced=8.0)
public var centerYWithinMargins: Edge {
return Edge(context, view, .CenterYWithinMargins)
}
/// The center point within the margins of the view. This property affects
/// `centerXWithinMargins` and `centerYWithinMargins`. iOS exclusive.
@available(iOS, introduced=8.0)
public var centerWithinMargins: Point {
return Point(context, [
Edge(context, view, .CenterXWithinMargins),
Edge(context, view, .CenterYWithinMargins)
])
}
#endif
internal let context: Context
internal let view: View
/// The superview of the view, if it exists.
public var superview: LayoutProxy? {
if let superview = view.superview {
return LayoutProxy(context, superview)
} else {
return nil
}
}
init(_ context: Context, _ view: View) {
self.context = context
self.view = view
}
}
| mit |
babarqb/HackingWithSwift | project6a/Project2/ViewController.swift | 48 | 1952 | //
// ViewController.swift
// Project2
//
// Created by Hudzilla on 13/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import GameplayKit
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
var countries = [String]()
var correctAnswer = 0
var score = 0
override func viewDidLoad() {
super.viewDidLoad()
countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]
button1.layer.borderWidth = 1
button2.layer.borderWidth = 1
button3.layer.borderWidth = 1
button1.layer.borderColor = UIColor.lightGrayColor().CGColor
button2.layer.borderColor = UIColor.lightGrayColor().CGColor
button3.layer.borderColor = UIColor.lightGrayColor().CGColor
askQuestion(nil)
}
func askQuestion(action: UIAlertAction!) {
countries = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(countries) as! [String]
button1.setImage(UIImage(named: countries[0]), forState: .Normal)
button2.setImage(UIImage(named: countries[1]), forState: .Normal)
button3.setImage(UIImage(named: countries[2]), forState: .Normal)
correctAnswer = GKRandomSource.sharedRandom().nextIntWithUpperBound(3)
title = countries[correctAnswer].uppercaseString
}
@IBAction func buttonTapped(sender: UIButton) {
var title: String
if sender.tag == correctAnswer {
title = "Correct"
++score
} else {
title = "Wrong"
--score
}
let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "Continue", style: .Default, handler: askQuestion))
presentViewController(ac, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| unlicense |
mindforce/Projector | Projector/ProjectTabBarController.swift | 1 | 918 | //
// ProjectTabBarController.swift
// RedmineProject-3.0
//
// Created by Volodymyr Tymofiychuk on 15.01.15.
// Copyright (c) 2015 Volodymyr Tymofiychuk. All rights reserved.
//
import UIKit
class ProjectTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 |
Monnoroch/Cuckoo | Generator/Source/CuckooGeneratorFramework/Tokens/Kinds.swift | 1 | 635 | //
// Kinds.swift
// CuckooGenerator
//
// Created by Filip Dolnik on 30.05.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public enum Kinds: String {
case ProtocolDeclaration = "source.lang.swift.decl.protocol"
case InstanceMethod = "source.lang.swift.decl.function.method.instance"
case MethodParameter = "source.lang.swift.decl.var.parameter"
case ClassDeclaration = "source.lang.swift.decl.class"
case ExtensionDeclaration = "source.lang.swift.decl.extension"
case InstanceVariable = "source.lang.swift.decl.var.instance"
case Mark = "source.lang.swift.syntaxtype.comment.mark"
}
| mit |
valentinbercot/VBPerfectArchitecture | Sources/VBPerfectStoreDatabase.swift | 1 | 262 | //
// VBPerfectStoreDatabase.swift
// VBPerfectArchitecture
//
// Created by Valentin Bercot on 13/02/2017.
//
//
/**
Defines a `VBPerfectStore` requirements.
- authors: Valentin Bercot
*/
public protocol VBPerfectStoreDatabase: VBPerfectStore
{
}
| apache-2.0 |
lennet/proNotes | app/proNotes/Document/PageView/Movable/MovableImageView.swift | 1 | 2707 | //
// MovableImageView.swift
// proNotes
//
// Created by Leo Thomas on 06/12/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
class MovableImageView: MovableView, ImageSettingsDelegate {
weak var imageView: UIImageView?
var imageLayer: ImageLayer? {
get {
return movableLayer as? ImageLayer
}
}
override init(frame: CGRect, movableLayer: MovableLayer, renderMode: Bool = false) {
super.init(frame: frame, movableLayer: movableLayer, renderMode: renderMode)
proportionalResize = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
proportionalResize = true
}
func setUpImageView() {
clipsToBounds = true
let imageView = UIImageView()
imageView.image = imageLayer?.image
addSubview(imageView)
self.imageView = imageView
}
override func setUpSettingsViewController() {
ImageSettingsViewController.delegate = self
SettingsViewController.sharedInstance?.currentType = .image
}
// MARK: - ImageSettingsDelegate
func removeImage() {
removeFromSuperview()
movableLayer?.removeFromPage()
SettingsViewController.sharedInstance?.currentType = .pageInfo
}
func getImage() -> UIImage? {
return imageLayer?.image
}
override func undoAction(_ oldObject: Any?) {
guard let image = oldObject as? UIImage else {
super.undoAction(oldObject)
return
}
updateImage(image)
if SettingsViewController.sharedInstance?.currentType == .image {
SettingsViewController.sharedInstance?.currentChildViewController?.update()
}
}
func updateImage(_ image: UIImage) {
guard imageView != nil else {
return
}
if let oldImage = imageLayer?.image {
if movableLayer != nil && movableLayer?.docPage != nil {
DocumentInstance.sharedInstance.registerUndoAction(oldImage, pageIndex: movableLayer!.docPage.index, layerIndex: movableLayer!.index)
}
}
let heightRatio = imageView!.bounds.height / imageView!.image!.size.height
let widthRatio = imageView!.bounds.width / imageView!.image!.size.width
imageView?.image = image
imageLayer?.image = image
frame.size.height = (image.size.height * heightRatio) + controlLength
frame.size.width = (image.size.width * widthRatio) + controlLength
movableLayer?.size = frame.size
layoutIfNeeded()
setNeedsDisplay()
saveChanges()
}
}
| mit |
vmouta/GitHubSpy | GitHubSpy/AppDelegate.swift | 1 | 2860 | /**
* @name AppDelegate.swift
* @partof GitHubSpy
* @description
* @author Vasco Mouta
* @created 17/12/15
*
* Copyright (c) 2015 zucred AG All rights reserved.
* This material, including documentation and any related
* computer programs, is protected by copyright controlled by
* zucred AG. All rights are reserved. Copying,
* including reproducing, storing, adapting or translating, any
* or all of this material requires the prior written consent of
* zucred AG. This material also contains confidential
* information which may not be disclosed to others without the
* prior written consent of zucred AG.
*/
import UIKit
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Testing Proposes
//if let path = Realm.Configuration.defaultConfiguration.path {
// try! NSFileManager().removeItemAtPath(path)
//}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
BareFeetWare/BFWControls | BFWControls/Modules/Styled/Model/UIFont+Chain.swift | 1 | 723 | //
// UIFont+Chain.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 1/5/19.
// Copyright © 2019 BareFeetWare. All rights reserved.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
public extension UIFont {
// MARK: - Convenience Init
convenience init(familyName: String, size: CGFloat) {
self.init(descriptor: UIFontDescriptor(fontAttributes: [.family : familyName]), size: size)
}
// MARK: - Instance Variables and Functions
var bold: UIFont {
return addingSymbolicTraits(.traitBold)
}
func resized(by multiplier: CGFloat) -> UIFont {
return withSize(pointSize * multiplier)
}
}
| mit |
RaviDesai/RSDRestServices | Pod/Classes/APIRequest.swift | 2 | 2349 | //
// APIRequest.swift
//
// Created by Ravi Desai on 6/10/15.
// Copyright (c) 2015 RSD. All rights reserved.
//
import Foundation
public class APIRequest<U: APIResponseParserProtocol> {
private var baseURL: NSURL?
private var endpoint: APIEndpoint
private var bodyEncoder: APIBodyEncoderProtocol?
private var additionalHeaders: [String: String]?
public private(set) var responseParser: U
public init(baseURL: NSURL?, endpoint: APIEndpoint, bodyEncoder: APIBodyEncoderProtocol?, responseParser: U, additionalHeaders: [String: String]?) {
self.baseURL = baseURL
self.endpoint = endpoint
self.bodyEncoder = bodyEncoder
self.additionalHeaders = additionalHeaders
self.responseParser = responseParser
}
public func URL() -> NSURL? {
return self.endpoint.URL(self.baseURL)
}
public func acceptTypes() -> String? {
return self.responseParser.acceptTypes?.joinWithSeparator(", ")
}
public func method() -> String {
return self.endpoint.method()
}
public func contentType() -> String? {
return self.bodyEncoder?.contentType()
}
public func body() -> NSData? {
return self.bodyEncoder?.body()
}
public func makeRequest() -> NSMutableURLRequest? {
var result: NSMutableURLRequest?
if let url = self.URL() {
let mutableRequest = NSMutableURLRequest(URL: url)
mutableRequest.HTTPMethod = self.method()
if let data = body() {
mutableRequest.HTTPBody = data;
NSURLProtocol.setProperty(data.copy(), forKey: "PostedData", inRequest: mutableRequest)
}
if let headers = self.additionalHeaders {
for header in headers {
mutableRequest.setValue(header.1, forHTTPHeaderField: header.0);
}
}
if let acceptTypes = self.acceptTypes() {
mutableRequest.setValue(acceptTypes, forHTTPHeaderField: "Accept")
}
if let contentType = self.contentType() {
mutableRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
}
result = mutableRequest
}
return result
}
} | mit |
Gericop/iCar | iCar/RefillDetailsViewController.swift | 1 | 2551 | //
// RefillDetailsViewController.swift
// iCar
//
// Created by Gergely Kőrössy on 09/12/15.
// Copyright © 2015 Gergely Kőrössy. All rights reserved.
//
import UIKit
import MapKit
class RefillDetailsViewController: UIViewController {
@IBOutlet weak var quantityField: UITextField!
@IBOutlet weak var unitPriceField: UITextField!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var typeField: UITextField!
@IBOutlet weak var odometerField: UITextField!
@IBOutlet weak var carField: UITextField!
@IBOutlet weak var locationMapView: MKMapView!
var refillLog : RefillLog?
override func viewDidLoad() {
super.viewDidLoad()
if let log = refillLog {
quantityField.text = String(log.refillQnty!)
unitPriceField.text = String(log.unitPrice!)
typeField.text = log.type
odometerField.text = String(log.odometer!) + "km"
refreshTotalPrice()
let car = log.car as! Car
carField.text = "\(car.name!) [\(car.licensePlate!)]"
/*let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .MediumStyle
navigationItem.prompt = dateFormatter.stringFromDate(log.time!)*/
// setting map
let mapAnnotation = MapPointAnnotation()
let coords = CLLocationCoordinate2DMake(CLLocationDegrees(log.lat!), CLLocationDegrees(log.lon!))
mapAnnotation.setCoordinate(coords)
locationMapView.addAnnotation(mapAnnotation)
locationMapView.centerCoordinate = coords
}
}
func refreshTotalPrice() {
let quantityStr = quantityField.text
let unitPriceStr = unitPriceField.text
if quantityStr != "" && unitPriceStr != "" {
let quantity = Double(quantityStr!) ?? 0
let unitPrice = Double(unitPriceStr!) ?? 0
totalLabel.text = "\(quantity * unitPrice)"
}
}
// 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?) {
//if segue.identifier != "AddRefillLog" {
let detailsVC = segue.destinationViewController as! RefillEditorViewController
detailsVC.refillLog = refillLog
//}
}
}
| apache-2.0 |
JustOneLastDance/SpeechSounds | SoundsToText/SoundsToText/AppDelegate.swift | 1 | 2178 | //
// AppDelegate.swift
// SoundsToText
//
// Created by JustinChou on 16/10/25.
// Copyright © 2016年 JustinChou. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/01129-swift-functiontype-get.swift | 1 | 332 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func < {
{
}
{
{
}
}
{
}
class e: f{ { }
{
}
{
}
{
}
{
{
}
{
{
{
}
}
}
}
func f<r> ( ) -> (r r -> r -> r {
{
}
{
{
}
}
{
}
}
}
{
}
{
{
}
}
protocol i : d { func d
| mit |
DaveChambers/SuperCrack | SuperCrack!/MemPegStripView.swift | 1 | 630 | //
// MemPegStripView.swift
// MastermindJune
//
// Created by Dave Chambers on 27/06/2017.
// Copyright © 2017 Dave Chambers. All rights reserved.
//
import UIKit
class MemPegStripView: UIView {
private var memPegs: [MemoryPeg]
private var column: Int
func getCol() -> Int {
return column
}
required init(memPegs: [MemoryPeg], col: Int) {
self.memPegs = memPegs
self.column = col
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func getPegs() -> [MemoryPeg] {
return self.memPegs
}
}
| mit |
xuzhou524/Convenient-Swift | View/RootCalendarTableViewCell.swift | 1 | 1432 | //
// RootCalendarTableViewCell.swift
// Convenient-Swift
//
// Created by gozap on 16/7/18.
// Copyright © 2016年 xuzhou. All rights reserved.
//
import UIKit
class RootCalendarTableViewCell: UITableViewCell {
var calendar : LBCalendar!
var calendarContentView : LBCalendarContentView?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.sebViewS()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.sebViewS()
}
func sebViewS(){
calendarContentView = LBCalendarContentView()
calendarContentView?.backgroundColor = XZSwiftColor.white
self.contentView.addSubview(calendarContentView!)
calendarContentView?.snp.makeConstraints({ (make) in
make.left.top.right.bottom.equalTo(self.contentView)
});
self.calendar = LBCalendar.init()
//self.calendar?.calendarAppearance().calendar().firstWeekday = 1 //Sunday ==1,Saturday == 7
self.calendar?.calendarAppearance().dayRectangularRatio = 9.00 / 10.00
self.calendar?.contentView = calendarContentView
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
Zacharyg88/Alien-Adventure-3 | Alien Adventure/BoostItemValue.swift | 3 | 500 | //
// BoostItemValue.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func boostItemValue(inventory: [UDItem]) -> [UDItem] {
return [UDItem]()
}
}
// If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 4"
| mit |
jkolb/midnightbacon | MidnightBacon/Modules/Messages/MessagesFlowController.swift | 1 | 1735 | //
// MessagesController.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// 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 Common
public class MessagesFlowController : NavigationFlowController {
private var messagesViewController: MessagesViewController!
public override func viewControllerDidLoad() {
messagesViewController = buildRootViewController()
pushViewController(messagesViewController, animated: false)
}
private func buildRootViewController() -> MessagesViewController {
let viewController = MessagesViewController()
viewController.title = "Messages"
return viewController
}
}
| mit |
ronaldbroens/jenkinsapp | Shared/Datamodel.swift | 1 | 667 | //
// JenkinsJob.swift
// JenkinsApp
//
// Created by Ronald Broens on 07/02/15.
// Copyright (c) 2015 Ronald Broens. All rights reserved.
//
import Foundation
struct JenkinsJob
{
var Name : String
var Url : String
var Color : String
}
struct JenkinsDetailInfo
{
var LastBuild : JenkinsBuildReference
var Color : String
var Builds : Array<JenkinsBuildReference>
}
struct JenkinsBuildReference
{
var Url : String
var Number : Int
}
struct JenkinsBuild
{
var Building : Bool
var FullDisplayName : String
var Duration : Int
var EstimatedDuration : Int
var StartTime : NSDate
var ExpectedEndTime : NSDate
} | apache-2.0 |
monktoninc/rebar-ios-samples | Rebar-Template/projectfiles/ViewController.swift | 1 | 508 | //
// ViewController.swift
// RebarApp
//
// Created by Harold Smith on 10/16/17.
// Copyright © 2017 Monkton, Inc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
ali-zahedi/AZViewer | AZViewer/AZImageLoader.swift | 1 | 3061 | //
// ImageLoader.swift
//
//
// Created by Ali Zahedi on 8/5/1395 AP.
// Copyright © 1395 Ali Zahedi. All rights reserved.
//
import Foundation
import UIKit
public class AZImageLoader {
var cache = NSCache<AnyObject, AnyObject>()
public static let shared = AZImageLoader()
private init() {} //This prevents others from using the default '()' initializer for this class.
public func imageForUrl(urlString: String, completionHandler:@escaping (_ image: UIImage?, _ url: String) -> ()) {
let fileManager = FileManager.default
var check_currect_image: Bool = false
if fileManager.fileExists(atPath: self.getFileLocation(urlString: urlString).path) {
let image = UIImage(contentsOfFile: self.getFileLocation(urlString: urlString).path)
if image != nil {
check_currect_image = true
completionHandler(image, urlString)
}
}
if (!check_currect_image) {
func problemLoad(){
print("problem load url: \(urlString)")
completionHandler(UIImage(), urlString)
}
guard let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let url = URL(string: escapedAddress) else {
problemLoad()
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else {
problemLoad()
return
}
DispatchQueue.main.async() { () -> Void in
if let data = UIImagePNGRepresentation(image) {
try? data.write(to: self.getFileLocation(urlString: urlString), options: [])
completionHandler(image, urlString)
}
}
}.resume()
}
}
func getFileLocation(urlString: String) -> URL{
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let dataPath = documentsURL.appendingPathComponent("cache")
do {
try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("Error creating directory: \(error.localizedDescription)")
}
let nameOfFile: String = urlString.components(separatedBy: "/").last!
return dataPath.appendingPathComponent(nameOfFile)
}
}
| apache-2.0 |
PlutoMa/SwiftProjects | 018.Spotlight Search/SpotlightSearch/SpotlightSearch/AppDelegate.swift | 1 | 1485 | //
// AppDelegate.swift
// SpotlightSearch
//
// Created by Dareway on 2017/11/1.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let navi = UINavigationController.init(rootViewController: ViewController())
window = UIWindow.init(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = navi
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
let identifier = userActivity.userInfo?["kCSSearchableItemActivityIdentifier"] as! String
NotificationCenter.default.post(name: notificationName, object: self, userInfo: ["id":identifier])
return true
}
}
| mit |
yonaskolb/SwagGen | Specs/PetstoreTest/generated/Swift/Sources/Requests/Fake/TestEndpointParameters.swift | 1 | 6897 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
extension PetstoreTest.Fake {
/** Fake endpoint for testing various parameters
假端點
偽のエンドポイント
가짜 엔드 포인트
*/
public enum TestEndpointParameters {
public static let service = APIService<Response>(id: "testEndpointParameters", tag: "fake", method: "POST", path: "/fake", hasBody: true, isUpload: true, securityRequirements: [SecurityRequirement(type: "http_basic_test", scopes: [])])
public final class Request: APIRequest<Response> {
public struct Options {
/** None */
public var number: Double
/** None */
public var double: Double
/** None */
public var patternWithoutDelimiter: String
/** None */
public var byte: File
/** None */
public var binary: File?
/** None */
public var callback: String?
/** None */
public var date: DateDay?
/** None */
public var dateTime: DateTime?
/** None */
public var float: Float?
/** None */
public var int32: Int?
/** None */
public var int64: Int?
/** None */
public var integer: Int?
/** None */
public var password: String?
/** None */
public var string: String?
public init(number: Double, double: Double, patternWithoutDelimiter: String, byte: File, binary: File? = nil, callback: String? = nil, date: DateDay? = nil, dateTime: DateTime? = nil, float: Float? = nil, int32: Int? = nil, int64: Int? = nil, integer: Int? = nil, password: String? = nil, string: String? = nil) {
self.number = number
self.double = double
self.patternWithoutDelimiter = patternWithoutDelimiter
self.byte = byte
self.binary = binary
self.callback = callback
self.date = date
self.dateTime = dateTime
self.float = float
self.int32 = int32
self.int64 = int64
self.integer = integer
self.password = password
self.string = string
}
}
public var options: Options
public init(options: Options) {
self.options = options
super.init(service: TestEndpointParameters.service)
}
/// convenience initialiser so an Option doesn't have to be created
public convenience init(number: Double, double: Double, patternWithoutDelimiter: String, byte: File, binary: File? = nil, callback: String? = nil, date: DateDay? = nil, dateTime: DateTime? = nil, float: Float? = nil, int32: Int? = nil, int64: Int? = nil, integer: Int? = nil, password: String? = nil, string: String? = nil) {
let options = Options(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, callback: callback, date: date, dateTime: dateTime, float: float, int32: int32, int64: int64, integer: integer, password: password, string: string)
self.init(options: options)
}
public override var formParameters: [String: Any] {
var params: [String: Any] = [:]
params["number"] = options.number
params["double"] = options.double
params["pattern_without_delimiter"] = options.patternWithoutDelimiter
params["byte"] = options.byte.encode()
if let binary = options.binary?.encode() {
params["binary"] = binary
}
if let callback = options.callback {
params["callback"] = callback
}
if let date = options.date?.encode() {
params["date"] = date
}
if let dateTime = options.dateTime?.encode() {
params["dateTime"] = dateTime
}
if let float = options.float {
params["float"] = float
}
if let int32 = options.int32 {
params["int32"] = int32
}
if let int64 = options.int64 {
params["int64"] = int64
}
if let integer = options.integer {
params["integer"] = integer
}
if let password = options.password {
params["password"] = password
}
if let string = options.string {
params["string"] = string
}
return params
}
}
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = Void
/** Invalid username supplied */
case status400
/** User not found */
case status404
public var success: Void? {
switch self {
default: return nil
}
}
public var response: Any {
switch self {
default: return ()
}
}
public var statusCode: Int {
switch self {
case .status400: return 400
case .status404: return 404
}
}
public var successful: Bool {
switch self {
case .status400: return false
case .status404: return false
}
}
public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws {
switch statusCode {
case 400: self = .status400
case 404: self = .status404
default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data)
}
}
public var description: String {
return "\(statusCode) \(successful ? "success" : "failure")"
}
public var debugDescription: String {
var string = description
let responseString = "\(response)"
if responseString != "()" {
string += "\n\(responseString)"
}
return string
}
}
}
}
| mit |
weihongjiang/PROJECTTOWN | Town/Town/AppDelegate.swift | 1 | 3376 | //
// AppDelegate.swift
// Town
//
// Created by john.wei on 15/6/4.
// Copyright (c) 2015年 whj. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//var centerController:JACenterViewController!
// var leftController:JALeftViewController!
// var rightController:JARightViewController!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var panelController = JASidePanelController()
var centerController = JACenterViewController()
var navController = UINavigationController(rootViewController:centerController)
navController.navigationBar.tintColor = UIColor.whiteColor()
navController.navigationBar.barTintColor = UIColor(red: 0, green: 176/255.0, blue: 232/255, alpha: 1.0)
let titleAtrr: NSDictionary = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName)
navController.navigationBar.titleTextAttributes = titleAtrr as? Dictionary
panelController.leftPanel = JALeftViewController()
panelController.rightPanel = JARightViewController()
panelController.centerPanel = navController
var tabbarController = UITabBarController()
self.window!.rootViewController = panelController
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:.
}
}
| apache-2.0 |
shafiullakhan/Swift-Paper | Swift-Paper/Swift-Paper/ViewController.swift | 1 | 13123 | //
// ViewController.swift
// Swift-Paper
//
// Created by Shaf on 8/5/15.
// Copyright (c) 2015 Shaffiulla. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIGestureRecognizerDelegate,UITableViewDataSource,UITableViewDelegate,PaperBubleDelegate {
private var toogle = true;
private var bubble:PaperBuble?;
private var addfrd,noti,msg: UIImageView?;
var baseController = BaseCollection(collectionViewLayout: SmallLayout())
var slide: Int = 0
var mainView:UIView?
var topImage,reflected: UIImageView?
var galleryImages = ["one.jpg", "two.jpg", "three.png", "five.jpg", "one.jpg"]
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
//
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.baseController.collectionView?.frame = UIScreen.mainScreen().bounds;
self.view.addSubview(self.baseController.collectionView!)
// Init mainView
addMainView();
// ImageView on top
addTopImage();
// Reflect imageView
addReflectImage();
// Add Card Details
addCardDetails();
// First Load
changeSlide();
let timer = NSTimer(timeInterval: 5.0, target: self, selector: "changeSlide", userInfo: nil, repeats: true)
// notificaiton friedns and messsage
addNotificationTabs();
}
func addMainView(){
self.mainView = UIView(frame: self.view.bounds)
self.mainView?.clipsToBounds = true
self.mainView?.layer.cornerRadius = 4
self.view.insertSubview(self.mainView!, belowSubview: self.baseController.collectionView!)
}
func addTopImage(){
self.topImage = UIImageView(frame: CGRectMake(0, 0, self.view.frame.size.width, AppDelegate.sharedDelegate().itemHeight-256))
self.topImage?.contentMode = UIViewContentMode.ScaleAspectFill;
self.mainView?.addSubview(self.topImage!)
// Gradient to top image
var gradient = CAGradientLayer();
gradient.frame = self.topImage!.bounds;
gradient.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).CGColor,UIColor(white: 0, alpha: 0).CGColor];
self.topImage!.layer.insertSublayer(gradient, atIndex: 0);
// Content perfect pixel
var perfectPixelContent = UIView(frame: CGRectMake(0, 0, CGRectGetWidth(self.topImage!.bounds), 1));
perfectPixelContent.backgroundColor = UIColor(white: 1, alpha: 0.2);
self.topImage!.addSubview(perfectPixelContent);
}
func addReflectImage(){
self.reflected = UIImageView(frame: CGRectMake(0, CGRectGetHeight(self.topImage!.bounds), self.view.frame.size.width, self.view.frame.size.height/2))
self.mainView?.addSubview(self.reflected!)
self.reflected!.transform = CGAffineTransformMakeScale(1.0, -1.0);
// Gradient to reflected image
var gradientReflected = CAGradientLayer();
gradientReflected.frame = self.reflected!.bounds;
gradientReflected.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 1).CGColor,UIColor(white: 0, alpha: 0).CGColor];
self.reflected!.layer.insertSublayer(gradientReflected, atIndex: 0);
}
func addCardDetails(){
// Label logo
var logo = UILabel(frame: CGRectMake(15, 12, 100, 0))
logo.backgroundColor = UIColor.clearColor();
logo.textColor = UIColor.whiteColor();
logo.font = UIFont(name: "Helvetica-Bold", size: 22);
logo.text = "MMPaper";
logo.sizeToFit();
// Label Shadow
logo.clipsToBounds = false;
logo.layer.shadowOffset = CGSizeMake(0, 0);
logo.layer.shadowColor = UIColor.blackColor().CGColor;
logo.layer.shadowRadius = 1.0;
logo.layer.shadowOpacity = 0.6;
self.mainView?.addSubview(logo);
// Label Title
var title = UILabel(frame: CGRectMake(15, logo.frame.origin.y + CGRectGetHeight(logo.frame) + 8, 290, 0))
title.backgroundColor = UIColor.clearColor();
title.textColor = UIColor.whiteColor();
title.font = UIFont(name: "Helvetica-Bold", size: 13);
title.text = "Mukesh Mandora";
title.sizeToFit();
// Label Shadow
title.clipsToBounds = false;
title.layer.shadowOffset = CGSizeMake(0, 0);
title.layer.shadowColor = UIColor.blackColor().CGColor;
title.layer.shadowRadius = 1.0;
title.layer.shadowOpacity = 0.6;
self.mainView?.addSubview(title);
// Label SubTitle
var subTitle = UILabel(frame: CGRectMake(15, title.frame.origin.y + CGRectGetHeight(title.frame), 290, 0))
subTitle.backgroundColor = UIColor.clearColor();
subTitle.textColor = UIColor.whiteColor();
subTitle.font = UIFont(name: "Helvetica", size: 13);
subTitle.text = "Inspired from Paper by Facebook";
subTitle.lineBreakMode = .ByWordWrapping;
subTitle.numberOfLines = 0;
subTitle.sizeToFit();
// Label Shadow
subTitle.clipsToBounds = false;
subTitle.layer.shadowOffset = CGSizeMake(0, 0);
subTitle.layer.shadowColor = UIColor.blackColor().CGColor;
subTitle.layer.shadowRadius = 1.0;
subTitle.layer.shadowOpacity = 0.6;
self.mainView?.addSubview(subTitle);
}
func addNotificationTabs(){
noti=UIImageView(frame: CGRectMake(self.view.frame.size.width-50, 20, 25, 25));
noti!.image = UIImage(named: "Tones-50")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
noti!.tintColor=UIColor.whiteColor();
noti?.userInteractionEnabled = true;
self.view.addSubview(noti!)
addfrd=UIImageView(frame: CGRectMake(noti!.frame.origin.x-50, 20, 25, 25));
addfrd!.image=UIImage(named: "Group-50")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
addfrd!.tintColor=UIColor.whiteColor();
addfrd?.userInteractionEnabled = true;
self.view.addSubview(addfrd!)
msg=UIImageView(frame: CGRectMake(addfrd!.frame.origin.x-50, 20, 25, 25));
msg!.image=UIImage(named: "Talk-50")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate);
msg!.tintColor=UIColor.whiteColor();
msg?.userInteractionEnabled = true;
self.view.addSubview(msg!)
var tapNoti=UITapGestureRecognizer(target: self, action: "tapBubble:");
tapNoti.delegate=self;
noti?.addGestureRecognizer(tapNoti);
noti!.tag = 1;
var tapFrd=UITapGestureRecognizer(target: self, action: "tapBubble:");
tapFrd.delegate=self;
addfrd?.addGestureRecognizer(tapFrd);
addfrd!.tag = 2;
var tapChat=UITapGestureRecognizer(target: self, action: "tapBubble:");
tapChat.delegate=self;
msg?.addGestureRecognizer(tapChat);
msg!.tag = 3;
}
//MARK: Gesture Action
func tapBubble(sender: UIGestureRecognizer){
let tag = sender.view?.tag;
if tag == 1{
self.toogleHelpAction(self)
}
else if tag == 2{
actionBut2(self)
}
else{
actionbut3(self)
}
}
func toogleHelpAction(sender: AnyObject){
if(bubble==nil && toogle==true){
toogle=false;
bubble=PaperBuble(frame: CGRectMake(8, noti!.center.y+20, self.view.frame.size.width-16, self.view.frame.size.height), attachedView: noti!);
bubble!.delegate = self
bubble!.button1=noti;
bubble!.tableView!.delegate=self;
bubble!.tableView!.dataSource=self;
self.view.addSubview(bubble!)
bubble?.popBubble()
}
else{
if(bubble!.button1==noti){
toogle=true;
bubble?.pushBubble()
bubble=nil;
}
else{
bubble!.button1=noti;
bubble?.updateArrow()
bubble?.shapeLayer?.removeFromSuperlayer()
}
}
if bubble != nil{
bubble!.tableView!.reloadData()
}
}
func actionBut2(sender: AnyObject){
if(bubble==nil && toogle==true){
toogle=false;
bubble=PaperBuble(frame: CGRectMake(8, addfrd!.center.y+20, self.view.frame.size.width-16, self.view.frame.size.height), attachedView: addfrd!);
bubble!.delegate = self
bubble!.button1=addfrd;
bubble!.tableView!.delegate=self;
bubble!.tableView!.dataSource=self;
self.view.addSubview(bubble!)
bubble?.popBubble()
}
else{
if(bubble!.button1==addfrd){
toogle=true;
bubble?.pushBubble()
bubble=nil;
}
else{
bubble!.button1=addfrd;
bubble?.updateArrow()
bubble?.shapeLayer?.removeFromSuperlayer()
}
}
if bubble != nil{
bubble!.tableView!.reloadData()
}
}
func actionbut3(sender: AnyObject){
if(bubble==nil && toogle==true){
toogle=false;
bubble=PaperBuble(frame: CGRectMake(8, msg!.center.y+20, self.view.frame.size.width-16, self.view.frame.size.height), attachedView: msg!);
bubble!.delegate = self
bubble!.button1=msg;
bubble!.tableView!.delegate=self;
bubble!.tableView!.dataSource=self;
self.view.addSubview(bubble!)
bubble?.popBubble()
}
else{
if(bubble!.button1==msg){
toogle=true;
bubble?.pushBubble()
bubble=nil;
}
else{
bubble!.button1=msg;
bubble?.updateArrow()
bubble?.shapeLayer?.removeFromSuperlayer()
}
}
if bubble != nil{
bubble!.tableView!.reloadData()
}
}
func dismissBubble(){
toogle=true;
bubble=nil;
}
//MARK: Timer Action
func changeSlide(){
if slide > (galleryImages.count - 1){
slide = 0
}
let toImage = UIImage(named: galleryImages[slide])
UIView.transitionWithView(self.mainView!,
duration: 0.6,
options: UIViewAnimationOptions.TransitionCrossDissolve | UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.topImage?.image = toImage;
self.reflected?.image = toImage;
}, completion: nil)
slide++
}
//MARK: TableViewData Source
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30;
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
var view = UIView(frame: CGRectMake(0, 10, tableView.frame.size.width, 30))
view.backgroundColor = UIColor.whiteColor()
/* Create custom view to display section header... */
var result : UInt32 = 0
NSScanner(string: "0xe94c5e").scanHexInt(&result);
var label = UILabel(frame: CGRectMake(18, 10, 300, 20))
label.textAlignment = .Left
label.textColor = UIColor.blackColor();
label.font = UIFont(name: "HelveticaNeue", size: 20)
if(bubble!.button1==noti!){
label.text="Notification";
}
else if (bubble!.button1==addfrd!){
label.text="Friend Request";
}
else{
label.text="Chats";
}
label.textColor = UIColor.lightGrayColor();
view.addSubview(label)
view.backgroundColor = UIColor.whiteColor()
view.layer.cornerRadius = 5.0
view.clipsToBounds = false;
view.layer.masksToBounds = false
return view
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let simpleTableIdentifier = "SimpleTableCell"
var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as? UITableViewCell
if cell == nil{
cell = UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
}
cell?.backgroundColor = UIColor.clearColor()
return cell!;
}
}
| mit |
psturm-swift/FoundationTools | Sources/DictionaryTools.swift | 1 | 2941 | /*
Copyright (c) 2016 Patrick Sturm <psturm.mail@googlemail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
public func buildDictionary<K : Hashable, V, S: Sequence>(from sequence: S) -> [K:V] where S.Iterator.Element == (K, V) {
var dictionary: [K:V] = [:]
for (key, value) in sequence {
dictionary.updateValue(value, forKey: key)
}
return dictionary
}
fileprivate func _map<K: Hashable, Vs, Vt>(dictionary: [K:Vs], transform: (Vs) throws -> (Vt)) rethrows -> [K:Vt] {
return buildDictionary(from: try dictionary.lazy.map { ($0.0, try transform($0.1)) })
}
public func map<K: Hashable, Vs, Vt>(dictionary: [K:Vs], transform: (Vs) throws -> (Vt)) rethrows -> [K:Vt] {
return try _map(dictionary: dictionary, transform: transform)
}
fileprivate func _map<Ks : Hashable, Vs, Kt : Hashable, Vt>(dictionary: [Ks:Vs], transform: (Ks, Vs) throws -> (Kt, Vt)) rethrows -> [Kt:Vt] {
return buildDictionary(from: try dictionary.lazy.map { item in try transform(item.0, item.1) })
}
public func map<Ks : Hashable, Vs, Kt : Hashable, Vt>(dictionary: [Ks:Vs], transform: (Ks, Vs) throws -> (Kt, Vt)) rethrows -> [Kt:Vt] {
return try _map(dictionary: dictionary, transform: transform)
}
public func invert<K : Hashable, V: Hashable>(dictionary: [K:V]) -> [V:K] {
return map(dictionary: dictionary) { (key, value) in (value, key) }
}
public extension Dictionary {
func mapDictionary<KeyT: Hashable, ValueT>(_ transform: (Key, Value) throws -> (KeyT, ValueT)) rethrows -> [KeyT:ValueT] {
return try _map(dictionary: self, transform: transform)
}
func mapValues<ValueT>(_ transform: (Value) throws -> (ValueT)) rethrows -> [Key:ValueT] {
return try _map(dictionary: self, transform: transform)
}
}
public extension Dictionary where Value: Hashable {
func inverted() -> [Value:Key] {
return invert(dictionary: self)
}
}
| mit |
dreamsxin/swift | test/Parse/operators.swift | 3 | 2640 | // RUN: %target-parse-verify-swift -parse-stdlib
// This disables importing the stdlib intentionally.
infix operator == {
associativity left
precedence 110
}
infix operator & {
associativity left
precedence 150
}
infix operator => {
associativity right
precedence 100
}
struct Man {}
struct TheDevil {}
struct God {}
struct Five {}
struct Six {}
struct Seven {}
struct ManIsFive {}
struct TheDevilIsSix {}
struct GodIsSeven {}
struct TheDevilIsSixThenGodIsSeven {}
func == (x: Man, y: Five) -> ManIsFive {}
func == (x: TheDevil, y: Six) -> TheDevilIsSix {}
func == (x: God, y: Seven) -> GodIsSeven {}
func => (x: TheDevilIsSix, y: GodIsSeven) -> TheDevilIsSixThenGodIsSeven {}
func => (x: ManIsFive, y: TheDevilIsSixThenGodIsSeven) {}
func test1() {
Man() == Five() => TheDevil() == Six() => God() == Seven()
}
postfix operator *!* {}
prefix operator *!* {}
struct LOOK {}
struct LOOKBang {
func exclaim() {}
}
postfix func *!* (x: LOOK) -> LOOKBang {}
prefix func *!* (x: LOOKBang) {}
func test2() {
*!*LOOK()*!*
}
// This should be parsed as (x*!*).exclaim()
LOOK()*!*.exclaim()
prefix operator ^ {}
infix operator ^ {}
postfix operator ^ {}
postfix func ^ (x: God) -> TheDevil {}
prefix func ^ (x: TheDevil) -> God {}
func ^ (x: TheDevil, y: God) -> Man {}
var _ : TheDevil = God()^
var _ : God = ^TheDevil()
var _ : Man = TheDevil() ^ God()
var _ : Man = God()^ ^ ^TheDevil()
let _ = God()^TheDevil() // expected-error{{cannot convert value of type 'God' to expected argument type 'TheDevil'}}
postfix func ^ (x: Man) -> () -> God {
return { return God() }
}
var _ : God = Man()^() // expected-error{{cannot convert value of type 'Man' to expected argument type 'TheDevil'}}
func &(x : Man, y : Man) -> Man { return x } // forgive amp_prefix token
prefix operator ⚽️ {}
prefix func ⚽️(x: Man) { }
infix operator ?? {
associativity right
precedence 100
}
func ??(x: Man, y: TheDevil) -> TheDevil {
return y
}
func test3(a: Man, b: Man, c: TheDevil) -> TheDevil {
return a ?? b ?? c
}
// <rdar://problem/17821399> We don't parse infix operators bound on both
// sides that begin with ! or ? correctly yet.
infix operator !! {}
func !!(x: Man, y: Man) {}
let foo = Man()
let bar = TheDevil()
foo!!foo // expected-error{{cannot force unwrap value of non-optional type 'Man'}} {{4-5=}} expected-error{{consecutive statements}} {{6-6=;}}
// expected-warning @-1 {{expression of type 'Man' is unused}}
foo??bar // expected-error{{broken standard library}} expected-error{{consecutive statements}} {{6-6=;}}
// expected-warning @-1 {{expression of type 'TheDevil' is unused}}
| apache-2.0 |
geraugu/monitora_ios | monitora/monitora/ViewController.swift | 1 | 512 | //
// ViewController.swift
// monitora
//
// Created by Geraldo Augusto on 12/29/14.
// Copyright (c) 2014 Gamfig Corp. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/25489-swift-valuedecl-getinterfacetype.swift | 1 | 441 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func a}class a
enum Sh{
class d:a}struct n
| apache-2.0 |
rnystrom/GitHawk | Local Pods/GitHubAPI/GitHubAPI/Processing.swift | 1 | 1118 | //
// Processing.swift
// GitHubAPI
//
// Created by Ryan Nystrom on 3/3/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
internal func processResponse<T: Request>(
request: T,
input: Any? = nil,
response: HTTPURLResponse? = nil,
error: Error? = nil
) -> Result<T.ResponseType> {
guard error == nil else {
return .failure(error)
}
guard let input = input as? T.ResponseType.InputType else {
return .failure(ClientError.mismatchedInput)
}
do {
let output = try T.ResponseType(input: input, response: response)
return .success(output)
} catch {
return .failure(error)
}
}
internal func asyncProcessResponse<T: Request>(
request: T,
input: Any?,
response: HTTPURLResponse?,
error: Error?,
completion: @escaping (Result<T.ResponseType>) -> Void
) {
DispatchQueue.global().async {
let result = processResponse(request: request, input: input, response: response, error: error)
DispatchQueue.main.async {
completion(result)
}
}
}
| mit |
kd2012/KDZB | KDLive/KDLiveTests/KDLiveTests.swift | 1 | 968 | //
// KDLiveTests.swift
// KDLiveTests
//
// Created by 杜兴光 on 2017/2/18.
// Copyright © 2017年 Duxingguang. All rights reserved.
//
import XCTest
@testable import KDLive
class KDLiveTests: 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 testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/26497-swift-diagnosticengine-emitdiagnostic.swift | 1 | 434 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class A<T where g:s{class A{let e=(
| apache-2.0 |
335g/TwitterAPIKit | Sources/APIs/MutesAPI.swift | 1 | 5352 | //
// Mutes.swift
// TwitterAPIKit
//
// Created by Yoshiki Kudo on 2015/07/07.
// Copyright © 2015年 Yoshiki Kudo. All rights reserved.
//
import Foundation
import APIKit
// MARK: Request
public protocol MutesRequestType: TwitterAPIRequestType {}
public protocol MutesGetRequestType: MutesRequestType {}
public protocol MutesPostRequestType: MutesRequestType {}
public extension MutesRequestType {
public var baseURL: NSURL {
return NSURL(string: "https://api.twitter.com/1.1/mutes/users")!
}
}
public extension MutesGetRequestType {
public var method: APIKit.HTTPMethod {
return .GET
}
}
public extension MutesPostRequestType {
public var method: APIKit.HTTPMethod {
return .POST
}
}
// MARK: API
public enum TwitterMutes {
///
/// https://dev.twitter.com/rest/reference/get/mutes/users/ids
///
public struct Ids: MutesGetRequestType {
public typealias Response = UserIDs
public let client: OAuthAPIClient
public var path: String {
return "/ids.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
cursorStr: String = "-1"){
self.client = client
self._parameters = ["cursor": cursorStr]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Ids.Response {
guard let
dictionary = object as? [String: AnyObject],
ids = UserIDs(dictionary: dictionary) else {
throw DecodeError.Fail
}
return ids
}
}
///
/// https://dev.twitter.com/rest/reference/get/mutes/users/list
///
public struct List: MutesGetRequestType {
public typealias Response = UsersList
public let client: OAuthAPIClient
public var path: String {
return "/list.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
cursorStr: String = "-1",
includeEntities: Bool = false,
skipStatus: Bool = true){
self.client = client
self._parameters = [
"cursor": cursorStr,
"include_entities": includeEntities,
"skip_status": skipStatus
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> List.Response {
guard let
dictionary = object as? [String: AnyObject],
list = UsersList(dictionary: dictionary) else {
throw DecodeError.Fail
}
return list
}
}
///
/// https://dev.twitter.com/rest/reference/post/mutes/users/create
///
public struct Create: MutesPostRequestType, SingleUserResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/create.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
user: User){
self.client = client
self._parameters = [user.key: user.obj]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Users {
return try userFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/post/mutes/users/destroy
///
public struct Destroy: MutesPostRequestType, SingleUserResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/destory.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest {
let url = self.baseURL.absoluteString + self.path
let header = client.authHeader(self.method, url, parameters, false)
URLRequest.setValue(header, forHTTPHeaderField: "Authorization")
return URLRequest
}
public init(
_ client: OAuthAPIClient,
user: User){
self.client = client
self._parameters = [user.key: user.obj]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Users {
return try userFromObject(object, URLResponse)
}
}
} | mit |
IndisputableLabs/Swifthereum | Swifthereum/Classes/Web3/Network/Resource.swift | 1 | 2092 | //
// Resource.swift
// Crisp
//
// Created by Ronald Mannak on 1/11/17.
// Copyright © 2017 A Puzzle A Day. All rights reserved.
//
import Foundation
public enum HttpMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case head = "HEAD"
}
public enum ParameterEncoding {
case json
/// Only use for GET, DELETE, and HEAD methods
case url
/// Only use for POST, PUT, PATCH methods
case body
public func contentType() -> String {
switch self {
case .json:
return "application/json"
case .url, .body:
return "application/x-www-form-urlencoded"
}
}
}
public struct Resource<A: Decodable> {
public let server: Server
public let method: String // E.g. "eth_sign"
public let headers: JSONDictionary?
public let parameters: Decodable? // E.g. ["0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "0xdeadbeaf"]
public let httpMethod: HttpMethod
public let encoding: ParameterEncoding
/**
Called by NetworkService to parse the data returned from the server. Depending on the kind of data we expect (e.g. JSON vs an image) we can set a suitable closure in the init.
*/
public let parse: (Data) throws -> A?
}
extension Resource {
public init(server: Server, method: String, parameters: Decodable? = nil, headers: JSONDictionary? = nil, httpMethod: HttpMethod = .post, encoding: ParameterEncoding = .json) {
self.server = server
self.method = method
self.headers = headers
self.parameters = parameters
self.httpMethod = httpMethod
self.encoding = encoding
parse = { data in
let encodedData = try JSONDecoder().decode(A.self, from: data)
return encodedData
}
}
public init(server: Server, method: Method) {
self.init(server: server, method: method.method, parameters: method.parameters)
}
}
| mit |
Thinkfly/EnglishLearner | EnglishLearner/EnglishLearner/Constant.swift | 1 | 339 | //
// Constant.swift
// EnglishLearner
//
// Created by app on 15/6/11.
// Copyright (c) 2015年 thinkfly. All rights reserved.
//
import UIKit
struct Constant {
static let screenWidth : CGFloat = UIScreen.mainScreen().applicationFrame.maxX
static let screenHeight : CGFloat = UIScreen.mainScreen().applicationFrame.maxY
}
| apache-2.0 |
kaushaldeo/Olympics | Olympics/Models/Discipline+CoreDataProperties.swift | 1 | 649 | //
// Discipline+CoreDataProperties.swift
// Olympics
//
// Created by Kaushal Deo on 8/4/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Discipline {
@NSManaged var alias: String?
@NSManaged var identifier: String?
@NSManaged var name: String?
@NSManaged var play: Bool
@NSManaged var status: Bool
@NSManaged var events: NSSet?
@NSManaged var sport: Sport?
@NSManaged var athletes: NSSet?
}
| apache-2.0 |
3pillarlabs/ios-horizontalmenu | Sources/SelectionController.swift | 1 | 4144 | //
// SelectionController.swift
// TPGHorizontalMenu
//
// Created by Horatiu Potra on 02/03/2017.
// Copyright © 2017 3Pillar Global. All rights reserved.
//
import UIKit
protocol SelectionControllerDelegate: class {
func selectionController(selectionController: SelectionController, didSelect index:Int)
}
/// An object which is reponsible with the control of menu items highlighting and selection.
class SelectionController {
unowned var menuDataSource: MenuDataSource
weak var delegate: SelectionControllerDelegate?
private var gestures: [UITapGestureRecognizer] = []
private var controls: [UIControl] = []
private var highlightedItem: Highlightable? {
didSet {
if var oldValue = oldValue {
oldValue.isHighlighted = false
}
if var highlightedItem = highlightedItem {
highlightedItem.isHighlighted = true
}
}
}
private var selectedItem: Selectable? {
didSet {
if var oldValue = oldValue {
oldValue.isSelected = false
}
if var selectedItem = selectedItem {
selectedItem.isSelected = true
}
}
}
init(menuDataSource: MenuDataSource) {
self.menuDataSource = menuDataSource
}
func resetItemsHandling() {
clearTargets()
addTargets()
}
func selectItem(at index: Int) {
guard menuDataSource.items.isValid(index: index) else { return }
let item = menuDataSource.items[index]
select(view: item.view)
}
// MARK: Actions
@objc private func viewDidTouchUpInside(_ sender: Any) {
var targetIndex: Int?
var targetView: UIView?
switch sender {
case let view as UIView:
targetIndex = index(for: view)
targetView = view
case let gesture as UIGestureRecognizer:
targetIndex = index(for: gesture.view)
targetView = gesture.view
default:
break
}
select(view: targetView)
if let index = targetIndex {
delegate?.selectionController(selectionController: self, didSelect: index)
}
}
@objc private func gestureDidChangeState(_ gesture: UIGestureRecognizer) {
switch gesture.state {
case .began:
highlight(view: gesture.view)
case .ended:
viewDidTouchUpInside(gesture)
fallthrough
case .failed:
fallthrough
case .cancelled:
highlightedItem = nil
default:
break
}
}
// MARK: Private functionality
private func index(for view: UIView?) -> Int? {
guard let view = view else { return nil }
return menuDataSource.items.index(where: { $0.view == view })
}
private func clearTargets() {
for gesture in gestures {
gesture.removeTarget(self, action: nil)
}
gestures = []
for control in controls {
control.removeTarget(self, action: nil, for: .allEvents)
}
controls = []
}
private func addTargets() {
for item in menuDataSource.items {
item.view.isExclusiveTouch = true
if let itemControl = item.view as? UIControl {
itemControl.addTarget(self, action: #selector(viewDidTouchUpInside(_:)), for: .touchUpInside)
} else {
let gesture = SelectGestureRecognizer(target: self, action: #selector(gestureDidChangeState(_:)))
item.view.isUserInteractionEnabled = true
item.view.addGestureRecognizer(gesture)
}
}
}
private func highlight(view: UIView?) {
if let highlightableView = view as? Highlightable {
highlightedItem = highlightableView
}
}
private func select(view: UIView?) {
if let selectableView = view as? Selectable {
selectedItem = selectableView
}
}
}
| mit |
toddkramer/Archiver | Sources/CGRect+ArchiveRepresentable.swift | 1 | 1856 | //
// CGRect+ArchiveRepresentable.swift
//
// Copyright (c) 2016 Todd Kramer (http://www.tekramer.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreGraphics
extension CGRect: ArchiveRepresentable {
private struct Key {
static let origin = "origin"
static let size = "size"
}
public var archiveValue: Archive {
return [
Key.origin: origin.archiveValue,
Key.size: size.archiveValue
]
}
public init(archive: Archive) {
guard let origin = archive[Key.origin] as? Archive,
let size = archive[Key.size] as? Archive else {
self = .zero
return
}
self.origin = CGPoint(archive: origin)
self.size = CGSize(archive: size)
}
}
| mit |
tottakai/RxSwift | Tests/RxCocoaTests/NSControl+RxTests.swift | 8 | 761 | //
// NSControl+RxTests.swift
// Tests
//
// Created by mrahmiao on 1/1/16.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Cocoa
import XCTest
class NSControlTests : RxTest {
}
extension NSControlTests {
func testEnabled_False() {
let subject = NSButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
Observable.just(false).subscribe(subject.rx.isEnabled).dispose()
XCTAssertTrue(subject.isEnabled == false)
}
func testEnabled_True() {
let subject = NSButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
Observable.just(true).subscribe(subject.rx.isEnabled).dispose()
XCTAssertTrue(subject.isEnabled == true)
}
}
| mit |
zhuhaow/soca | soca/Socket/Adapter/SecureHTTPAdapter.swift | 1 | 468 | //
// SecureHTTPAdapter.swift
// Soca
//
// Created by Zhuhao Wang on 2/22/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import Foundation
class SecureHTTPAdapter : HTTPAdapter {
override func socketDidConnectToHost(host: String, onPort port: UInt16) {
socket._socket.startTLS([kCFStreamSSLPeerName: self.serverHost])
// socket.startTLS([NSObject: AnyObject]())
super.socketDidConnectToHost(host, onPort: port)
}
} | mit |
jpsim/DeckRocket | Source/Mac/Deckset/DecksetWindow.swift | 1 | 2988 | //
// DecksetWindow.swift
// DeckRocket
//
// Created by JP Simard on 4/8/15.
// Copyright (c) 2015 JP Simard. All rights reserved.
//
struct DecksetWindow {
// MARK: Properties
private let sbWindow: NSObject
/// The window's `DecksetDocument`.
var document: DecksetDocument {
return DecksetDocument(sbDocument: sbWindow.value(forKey: "document")! as AnyObject)
}
/// The title of the window.
var name: String {
return sbWindow.value(forKey: "name") as! String
}
/// The unique identifier of the window.
var id: Int {
return sbWindow.value(forKey: "id") as! Int
}
/// Set the unique identifier of the window.
func setID(value: Int) {
return sbWindow.setValue(value, forKey: "id")
}
/// The index of the window, ordered front to back.
var index: Int {
return sbWindow.value(forKey: "index") as! Int
}
/// Set the index of the window, ordered front to back.
func setIndex(value: Int) {
return sbWindow.setValue(value, forKey: "index")
}
/// The bounding rectangle of the window.
var bounds: NSRect {
return sbWindow.value(forKey: "bounds") as! NSRect
}
/// Set the bounding rectangle of the window.
func setBounds(value: NSRect) {
return sbWindow.setValue(NSValue(rect: value), forKey: "bounds")
}
/// Does the window have a close button?
var closeable: Bool {
return sbWindow.value(forKey: "closeable") as! Bool
}
/// Does the window have a minimize button?
var miniaturizable: Bool {
return sbWindow.value(forKey: "miniaturizable") as! Bool
}
/// Is the window minimized right now?
var miniaturized: Bool {
return sbWindow.value(forKey: "miniaturized") as! Bool
}
/// Minimize or unminimize the window.
func setMiniaturized(value: Bool) {
return sbWindow.setValue(value, forKey: "miniaturized")
}
/// Can the window be resized?
var resizable: Bool {
return sbWindow.value(forKey: "resizable") as! Bool
}
/// Is the window visible right now?
var visible: Bool {
return sbWindow.value(forKey: "visible") as! Bool
}
/// Show or hide the window.
func setVisible(value: Bool) {
return sbWindow.setValue(value, forKey: "visible")
}
/// Does the window have a zoom button?
var zoomable: Bool {
return sbWindow.value(forKey: "zoomable") as! Bool
}
/// Is the window zoomed right now?
var zoomed: Bool {
return sbWindow.value(forKey: "zoomed") as! Bool
}
/// Zoom or unzoom the window.
func setZoomed(value: Bool) {
return sbWindow.setValue(value, forKey: "zoomed")
}
// MARK: Initializers
init(sbWindow: NSObject) {
self.sbWindow = sbWindow
}
// MARK: Functions
/// Close a document.
func close() {
// TODO: Implement this
// sbWindow.close()
}
}
| mit |
Electrode-iOS/ELRouter | ELRouter/AssociatedData.swift | 2 | 447 | //
// AssociatedData.swift
// ELRouter
//
// Created by Brandon Sneed on 4/15/16.
// Copyright © 2016 theholygrail.io. All rights reserved.
//
import Foundation
/**
The AssociatedData protocol is used for conformance on passing data
through a chain of routes.
*/
@objc
public protocol AssociatedData { }
/**
Allows NSURL to be passed through as AssociateData for inspection by the
route chain.
*/
extension NSURL: AssociatedData { }
| mit |
basheersubei/swift-t | turbine/code/export/math.swift | 2 | 2903 | /*
* Copyright 2013 University of Chicago and Argonne National Laboratory
*
* 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
*/
// Mathematical functions
#ifndef MATH_SWIFT
#define MATH_SWIFT
float PI = 3.14159265358979323846;
float E = 2.7182818284590452354;
@pure @builtin_op=FLOOR
(float o) floor (float i) "turbine" "0.0.2" "floor";
@pure @builtin_op=CEIL
(float o) ceil (float i) "turbine" "0.0.2" "ceil";
@pure @builtin_op=ROUND
(float o) round (float i) "turbine" "0.0.2" "round";
@pure @builtin_op=LOG
(float o) log (float i) "turbine" "0.0.2" "log_e";
@pure @builtin_op=EXP
(float o) exp (float i) "turbine" "0.0.2" "exp";
@pure @builtin_op=SQRT
(float o) sqrt (float i) "turbine" "0.0.2" "sqrt";
@pure @builtin_op=IS_NAN
(boolean o) is_nan (float i) "turbine" "0.0.2" "is_nan";
@pure @builtin_op=IS_NAN
(boolean o) isNaN (float i) "turbine" "0.0.2" "is_nan";
@pure @builtin_op=ABS_INT
(int o) abs_integer (int i) "turbine" "0.0.2" "abs_integer";
@pure @builtin_op=ABS_INT
(int o) abs (int i) "turbine" "0.0.2" "abs_integer";
@pure @builtin_op=ABS_FLOAT
(float o) abs_float (float i) "turbine" "0.0.2" "abs_float";
@pure @builtin_op=ABS_FLOAT
(float o) abs (float i) "turbine" "0.0.2" "abs_float";
@pure
(float o) cbrt (float i) {
o = pow(i, 1.0/3.0);
}
@pure @builtin_op=LOG
(float o) ln (float x) "turbine" "0.7.0" "log_e";
@pure
(float o) log10 (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::log10 <<x>> ]"
];
@pure
(float o) log (float x, float base) "turbine" "0.7.0" [
"set <<o>> [ expr {log(<<x>>)/log(<<base>>)} ]"
];
@pure
(float o) sin (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::sin <<x>> ]"
];
@pure
(float o) cos (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::cos <<x>> ]"
];
@pure
(float o) tan (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::tan <<x>> ]"
];
@pure
(float o) asin (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::asin <<x>> ]"
];
@pure
(float o) acos (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::acos <<x>> ]"
];
@pure
(float o) atan (float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::atan <<x>> ]"
];
@pure
(float o) atan2 (float y, float x) "turbine" "0.7.0" [
"set <<o>> [ ::tcl::mathfunc::atan2 <<y>> <<x>> ]"
];
#endif
| apache-2.0 |
jwolkovitzs/AMScrollingNavbar | Source/ScrollingNavigationController.swift | 1 | 25011 | import UIKit
/**
Scrolling Navigation Bar delegate protocol
*/
@objc public protocol ScrollingNavigationControllerDelegate: NSObjectProtocol {
/// Called when the state of the navigation bar changes
///
/// - Parameters:
/// - controller: the ScrollingNavigationController
/// - state: the new state
@objc optional func scrollingNavigationController(_ controller: ScrollingNavigationController, didChangeState state: NavigationBarState)
/// Called when the state of the navigation bar is about to change
///
/// - Parameters:
/// - controller: the ScrollingNavigationController
/// - state: the new state
@objc optional func scrollingNavigationController(_ controller: ScrollingNavigationController, willChangeState state: NavigationBarState)
}
/**
The state of the navigation bar
- collapsed: the navigation bar is fully collapsed
- expanded: the navigation bar is fully visible
- scrolling: the navigation bar is transitioning to either `Collapsed` or `Scrolling`
*/
@objc public enum NavigationBarState: Int {
case collapsed, expanded, scrolling
}
/**
The direction of scrolling that the navigation bar should be collapsed.
The raw value determines the sign of content offset depending of collapse direction.
- scrollUp: scrolling up direction
- scrollDown: scrolling down direction
*/
@objc public enum NavigationBarCollapseDirection: Int {
case scrollUp = -1
case scrollDown = 1
}
/**
The direction of scrolling that a followe should follow when the navbar is collapsing.
The raw value determines the sign of content offset depending of collapse direction.
- scrollUp: scrolling up direction
- scrollDown: scrolling down direction
*/
@objc public enum NavigationBarFollowerCollapseDirection: Int {
case scrollUp = -1
case scrollDown = 1
}
/**
Wraps a view that follows the navigation bar, providing the direction that the view should follow
*/
@objcMembers
open class NavigationBarFollower: NSObject {
public weak var view: UIView?
public var direction = NavigationBarFollowerCollapseDirection.scrollUp
public init(view: UIView, direction: NavigationBarFollowerCollapseDirection = .scrollUp) {
self.view = view
self.direction = direction
}
}
/**
A custom `UINavigationController` that enables the scrolling of the navigation bar alongside the
scrolling of an observed content view
*/
@objcMembers
open class ScrollingNavigationController: UINavigationController, UIGestureRecognizerDelegate {
/**
Returns the `NavigationBarState` of the navigation bar
*/
open var state: NavigationBarState {
get {
if navigationBar.frame.origin.y <= -navbarFullHeight {
return .collapsed
} else if navigationBar.frame.origin.y >= statusBarHeight {
return .expanded
} else {
return .scrolling
}
}
}
/**
Determines whether the navbar should scroll when the content inside the scrollview fits
the view's size. Defaults to `false`
*/
open var shouldScrollWhenContentFits = false
/**
Determines if the navbar should expand once the application becomes active after entering background
Defaults to `true`
*/
open var expandOnActive = true
/**
Determines if the navbar scrolling is enabled.
Defaults to `true`
*/
open var scrollingEnabled = true
/**
The delegate for the scrolling navbar controller
*/
open weak var scrollingNavbarDelegate: ScrollingNavigationControllerDelegate?
/**
An array of `NavigationBarFollower`s that will follow the navbar
*/
open var followers: [NavigationBarFollower] = []
/**
Determines if the top content inset should be updated with the navbar's delta movement. This should be enabled when dealing with table views with floating headers.
It can however cause issues in certain configurations. If the issues arise, set this to false
Defaults to `true`
*/
open var shouldUpdateContentInset = true
/**
Determines if the navigation bar should scroll while following a UITableView that is in edit mode.
Defaults to `false`
*/
open var shouldScrollWhenTableViewIsEditing = false
/// Holds the percentage of the navigation bar that is hidde. At 0 the navigation bar is fully visible, at 1 fully hidden. CGFloat with values from 0 to 1
open var percentage: CGFloat {
get {
return (navigationBar.frame.origin.y - statusBarHeight) / (-navbarFullHeight - statusBarHeight)
}
}
/// Stores some metadata of a UITabBar if one is passed in the followers array
internal struct TabBarMock {
var isTranslucent: Bool = false
var origin: CGPoint = .zero
init(origin: CGPoint, translucent: Bool) {
self.origin = origin
self.isTranslucent = translucent
}
}
open fileprivate(set) var gestureRecognizer: UIPanGestureRecognizer?
fileprivate var sourceTabBar: TabBarMock?
fileprivate var previousOrientation: UIDeviceOrientation = UIDevice.current.orientation
var delayDistance: CGFloat = 0
var maxDelay: CGFloat = 0
var scrollableView: UIView?
var lastContentOffset = CGFloat(0.0)
var scrollSpeedFactor: CGFloat = 1
var collapseDirectionFactor: CGFloat = 1 // Used to determine the sign of content offset depending of collapse direction
var previousState: NavigationBarState = .expanded // Used to mark the state before the app goes in background
/**
Start scrolling
Enables the scrolling by observing a view
- parameter scrollableView: The view with the scrolling content that will be observed
- parameter delay: The delay expressed in points that determines the scrolling resistance. Defaults to `0`
- parameter scrollSpeedFactor : This factor determines the speed of the scrolling content toward the navigation bar animation
- parameter collapseDirection : The direction of scrolling that the navigation bar should be collapsed
- parameter followers: An array of `NavigationBarFollower`s that will follow the navbar. The wrapper holds the direction that the view will follow
*/
open func followScrollView(_ scrollableView: UIView, delay: Double = 0, scrollSpeedFactor: Double = 1, collapseDirection: NavigationBarCollapseDirection = .scrollDown, followers: [NavigationBarFollower] = []) {
guard self.scrollableView == nil else {
// Restore previous state. UIKit restores the navbar to its full height on view changes (e.g. during a modal presentation), so we need to restore the status once UIKit is done
switch previousState {
case .collapsed:
hideNavbar(animated: false)
case .expanded:
showNavbar(animated: false)
default: break
}
return
}
self.scrollableView = scrollableView
gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ScrollingNavigationController.handlePan(_:)))
gestureRecognizer?.maximumNumberOfTouches = 1
gestureRecognizer?.delegate = self
gestureRecognizer?.cancelsTouchesInView = false
scrollableView.addGestureRecognizer(gestureRecognizer!)
previousOrientation = UIDevice.current.orientation
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.willResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.didBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.didRotate(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ScrollingNavigationController.windowDidBecomeVisible(_:)), name: UIWindow.didBecomeVisibleNotification, object: nil)
maxDelay = CGFloat(delay)
delayDistance = CGFloat(delay)
scrollingEnabled = true
// Save TabBar state (the state is changed during the transition and restored on compeltion)
if let tab = followers.map({ $0.view }).first(where: { $0 is UITabBar }) as? UITabBar {
self.sourceTabBar = TabBarMock(origin: CGPoint(x: tab.frame.origin.x, y: CGFloat(round(tab.frame.origin.y))), translucent: tab.isTranslucent)
}
self.followers = followers
self.scrollSpeedFactor = CGFloat(scrollSpeedFactor)
self.collapseDirectionFactor = CGFloat(collapseDirection.rawValue)
}
/**
Hide the navigation bar
- parameter animated: If true the scrolling is animated. Defaults to `true`
- parameter duration: Optional animation duration. Defaults to 0.1
*/
open func hideNavbar(animated: Bool = true, duration: TimeInterval = 0.1) {
guard let _ = self.scrollableView, let visibleViewController = self.visibleViewController else { return }
guard state == .expanded else {
updateNavbarAlpha()
return
}
gestureRecognizer?.isEnabled = false
let animations = {
self.scrollWithDelta(self.fullNavbarHeight, ignoreDelay: true)
visibleViewController.view.setNeedsLayout()
if self.navigationBar.isTranslucent {
let currentOffset = self.contentOffset
self.scrollView()?.contentOffset = CGPoint(x: currentOffset.x, y: currentOffset.y + self.navbarHeight)
}
}
if animated {
UIView.animate(withDuration: duration, animations: animations) { _ in
self.gestureRecognizer?.isEnabled = true
}
} else {
animations()
gestureRecognizer?.isEnabled = true
}
}
/**
Show the navigation bar
- parameter animated: If true the scrolling is animated. Defaults to `true`
- parameter duration: Optional animation duration. Defaults to 0.1
*/
open func showNavbar(animated: Bool = true, duration: TimeInterval = 0.1) {
guard let _ = self.scrollableView, let visibleViewController = self.visibleViewController else { return }
guard state == .collapsed else {
updateNavbarAlpha()
return
}
gestureRecognizer?.isEnabled = false
let animations = {
self.lastContentOffset = 0
self.scrollWithDelta(-self.fullNavbarHeight, ignoreDelay: true)
visibleViewController.view.setNeedsLayout()
if self.navigationBar.isTranslucent {
let currentOffset = self.contentOffset
self.scrollView()?.contentOffset = CGPoint(x: currentOffset.x, y: currentOffset.y - self.navbarHeight)
}
}
if animated {
UIView.animate(withDuration: duration, animations: animations) { _ in
self.gestureRecognizer?.isEnabled = true
}
} else {
animations()
gestureRecognizer?.isEnabled = true
}
}
/**
Stop observing the view and reset the navigation bar
- parameter showingNavbar: If true the navbar is show, otherwise it remains in its current state. Defaults to `true`
*/
open func stopFollowingScrollView(showingNavbar: Bool = true) {
if showingNavbar {
showNavbar(animated: true)
}
if let gesture = gestureRecognizer {
scrollableView?.removeGestureRecognizer(gesture)
}
scrollableView = .none
gestureRecognizer = .none
scrollingNavbarDelegate = .none
scrollingEnabled = false
let center = NotificationCenter.default
center.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
center.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}
// MARK: - Gesture recognizer
func handlePan(_ gesture: UIPanGestureRecognizer) {
if let tableView = scrollableView as? UITableView, !shouldScrollWhenTableViewIsEditing && tableView.isEditing {
return
}
if let superview = scrollableView?.superview {
let translation = gesture.translation(in: superview)
let delta = (lastContentOffset - translation.y) / scrollSpeedFactor
if !checkSearchController(delta) {
lastContentOffset = translation.y
return
}
if gesture.state != .failed {
lastContentOffset = translation.y
if shouldScrollWithDelta(delta) {
scrollWithDelta(delta)
}
}
}
if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed {
checkForPartialScroll()
lastContentOffset = 0
}
}
// MARK: - Fullscreen handling
func windowDidBecomeVisible(_ notification: Notification) {
showNavbar()
}
// MARK: - Rotation handler
func didRotate(_ notification: Notification) {
let newOrientation = UIDevice.current.orientation
// Show the navbar if the orantation is the same (the app just got back from background) or if there is a switch between portrait and landscape (and vice versa)
if (previousOrientation == newOrientation) || (previousOrientation.isPortrait && newOrientation.isLandscape) || (previousOrientation.isLandscape && newOrientation.isPortrait) {
showNavbar()
}
previousOrientation = newOrientation
}
/**
UIContentContainer protocol method.
Will show the navigation bar upon rotation or changes in the trait sizes.
*/
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
showNavbar()
}
// MARK: - Notification handler
func didBecomeActive(_ notification: Notification) {
if expandOnActive {
showNavbar(animated: false)
} else {
if previousState == .collapsed {
hideNavbar(animated: false)
}
}
}
func willResignActive(_ notification: Notification) {
previousState = state
}
/// Handles when the status bar changes
func willChangeStatusBar() {
showNavbar(animated: true)
}
// MARK: - Scrolling functions
private func shouldScrollWithDelta(_ delta: CGFloat) -> Bool {
let scrollDelta = delta
// Do not hide too early
if contentOffset.y < ((navigationBar.isTranslucent ? -fullNavbarHeight : 0) + scrollDelta) {
return false
}
// Check for rubberbanding
if scrollDelta < 0 {
if let scrollableView = scrollableView , contentOffset.y + scrollableView.frame.size.height > contentSize.height && scrollableView.frame.size.height < contentSize.height {
// Only if the content is big enough
return false
}
}
return true
}
private func scrollWithDelta(_ delta: CGFloat, ignoreDelay: Bool = false) {
var scrollDelta = delta
let frame = navigationBar.frame
// View scrolling up, hide the navbar
if scrollDelta > 0 {
// Update the delay
if !ignoreDelay {
delayDistance -= scrollDelta
// Skip if the delay is not over yet
if delayDistance > 0 {
return
}
}
// No need to scroll if the content fits
if !shouldScrollWhenContentFits && state != .collapsed &&
(scrollableView?.frame.size.height)! >= contentSize.height {
return
}
// Compute the bar position
if frame.origin.y - scrollDelta < -navbarFullHeight {
scrollDelta = frame.origin.y + navbarFullHeight
}
// Detect when the bar is completely collapsed
if frame.origin.y <= -navbarFullHeight {
delayDistance = maxDelay
}
}
if scrollDelta < 0 {
// Update the delay
if !ignoreDelay {
delayDistance += scrollDelta
// Skip if the delay is not over yet
if delayDistance > 0 && maxDelay < contentOffset.y {
return
}
}
// Compute the bar position
if frame.origin.y - scrollDelta > statusBarHeight {
scrollDelta = frame.origin.y - statusBarHeight
}
// Detect when the bar is completely expanded
if frame.origin.y >= statusBarHeight {
delayDistance = maxDelay
}
}
updateSizing(scrollDelta)
updateNavbarAlpha()
restoreContentOffset(scrollDelta)
updateFollowers()
updateContentInset(scrollDelta)
let newState = state
if newState != previousState {
scrollingNavbarDelegate?.scrollingNavigationController?(self, willChangeState: newState)
navigationBar.isUserInteractionEnabled = (newState == .expanded)
}
previousState = newState
}
/// Adjust the top inset (useful when a table view has floating headers, see issue #219
private func updateContentInset(_ delta: CGFloat) {
if self.shouldUpdateContentInset, let contentInset = scrollView()?.contentInset, let scrollInset = scrollView()?.scrollIndicatorInsets {
scrollView()?.contentInset = UIEdgeInsets(top: contentInset.top - delta, left: contentInset.left, bottom: contentInset.bottom, right: contentInset.right)
scrollView()?.scrollIndicatorInsets = UIEdgeInsets(top: scrollInset.top - delta, left: scrollInset.left, bottom: scrollInset.bottom, right: scrollInset.right)
}
}
private func updateFollowers() {
followers.forEach {
guard let tabBar = $0.view as? UITabBar else {
let height = $0.view?.frame.height ?? 0
var safeArea: CGFloat = 0
if #available(iOS 11.0, *) {
// Account for the safe area for footers and toolbars at the bottom of the screen
safeArea = ($0.direction == .scrollDown) ? (topViewController?.view.safeAreaInsets.bottom ?? 0) : 0
}
switch $0.direction {
case .scrollDown:
$0.view?.transform = CGAffineTransform(translationX: 0, y: percentage * (height + safeArea))
case .scrollUp:
$0.view?.transform = CGAffineTransform(translationX: 0, y: -(statusBarHeight - navigationBar.frame.origin.y))
}
return
}
tabBar.isTranslucent = true
tabBar.transform = CGAffineTransform(translationX: 0, y: percentage * tabBar.frame.height)
// Set the bar to its original state if it's in its original position
if let originalTabBar = sourceTabBar, originalTabBar.origin.y == round(tabBar.frame.origin.y) {
tabBar.isTranslucent = originalTabBar.isTranslucent
}
}
}
private func updateSizing(_ delta: CGFloat) {
guard let topViewController = self.topViewController else { return }
var frame = navigationBar.frame
// Move the navigation bar
frame.origin = CGPoint(x: frame.origin.x, y: frame.origin.y - delta)
navigationBar.frame = frame
// Resize the view if the navigation bar is not translucent
if !navigationBar.isTranslucent {
let navBarY = navigationBar.frame.origin.y + navigationBar.frame.size.height
frame = topViewController.view.frame
frame.origin = CGPoint(x: frame.origin.x, y: navBarY)
frame.size = CGSize(width: frame.size.width, height: view.frame.size.height - (navBarY) - tabBarOffset)
topViewController.view.frame = frame
}
}
private func restoreContentOffset(_ delta: CGFloat) {
if navigationBar.isTranslucent || delta == 0 {
return
}
// Hold the scroll steady until the navbar appears/disappears
if let scrollView = scrollView() {
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y - delta), animated: false)
}
}
private func checkForPartialScroll() {
let frame = navigationBar.frame
var duration = TimeInterval(0)
var delta = CGFloat(0.0)
// Scroll back down
let threshold = statusBarHeight - (frame.size.height / 2)
if navigationBar.frame.origin.y >= threshold {
delta = frame.origin.y - statusBarHeight
let distance = delta / (frame.size.height / 2)
duration = TimeInterval(abs(distance * 0.2))
scrollingNavbarDelegate?.scrollingNavigationController?(self, willChangeState: state)
} else {
// Scroll up
delta = frame.origin.y + navbarFullHeight
let distance = delta / (frame.size.height / 2)
duration = TimeInterval(abs(distance * 0.2))
scrollingNavbarDelegate?.scrollingNavigationController?(self, willChangeState: state)
}
delayDistance = maxDelay
UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: {
self.updateSizing(delta)
self.updateFollowers()
self.updateNavbarAlpha()
self.updateContentInset(delta)
}, completion: { _ in
self.navigationBar.isUserInteractionEnabled = (self.state == .expanded)
self.scrollingNavbarDelegate?.scrollingNavigationController?(self, didChangeState: self.state)
})
}
private func updateNavbarAlpha() {
guard let navigationItem = topViewController?.navigationItem else { return }
let frame = navigationBar.frame
// Change the alpha channel of every item on the navbr
let alpha = 1 - percentage
// Hide all the possible titles
navigationItem.titleView?.alpha = alpha
navigationBar.tintColor = navigationBar.tintColor.withAlphaComponent(alpha)
navigationItem.leftBarButtonItem?.tintColor = navigationItem.leftBarButtonItem?.tintColor?.withAlphaComponent(alpha)
navigationItem.rightBarButtonItem?.tintColor = navigationItem.rightBarButtonItem?.tintColor?.withAlphaComponent(alpha)
navigationItem.leftBarButtonItems?.forEach { $0.tintColor = $0.tintColor?.withAlphaComponent(alpha) }
navigationItem.rightBarButtonItems?.forEach { $0.tintColor = $0.tintColor?.withAlphaComponent(alpha) }
if let titleColor = navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] as? UIColor {
navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] = titleColor.withAlphaComponent(alpha)
} else {
let blackAlpha = UIColor.black.withAlphaComponent(alpha)
if navigationBar.titleTextAttributes == nil {
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: blackAlpha]
} else {
navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] = blackAlpha
}
}
// Hide all possible button items and navigation items
func shouldHideView(_ view: UIView) -> Bool {
let className = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
var viewNames = ["UINavigationButton", "UINavigationItemView", "UIImageView", "UISegmentedControl"]
if #available(iOS 11.0, *) {
viewNames.append(navigationBar.prefersLargeTitles ? "UINavigationBarLargeTitleView" : "UINavigationBarContentView")
} else {
viewNames.append("UINavigationBarContentView")
}
return viewNames.contains(className)
}
func setAlphaOfSubviews(view: UIView, alpha: CGFloat) {
if let label = view as? UILabel {
label.textColor = label.textColor.withAlphaComponent(alpha)
} else if let label = view as? UITextField {
label.textColor = label.textColor?.withAlphaComponent(alpha)
} else if view.classForCoder == NSClassFromString("_UINavigationBarContentView") {
// do nothing
} else {
view.alpha = alpha
}
view.subviews.forEach { setAlphaOfSubviews(view: $0, alpha: alpha) }
}
navigationBar.subviews
.filter(shouldHideView)
.forEach { setAlphaOfSubviews(view: $0, alpha: alpha) }
// Hide the left items
navigationItem.leftBarButtonItem?.customView?.alpha = alpha
navigationItem.leftBarButtonItems?.forEach { $0.customView?.alpha = alpha }
// Hide the right items
navigationItem.rightBarButtonItem?.customView?.alpha = alpha
navigationItem.rightBarButtonItems?.forEach { $0.customView?.alpha = alpha }
}
private func checkSearchController(_ delta: CGFloat) -> Bool {
if #available(iOS 11.0, *) {
if let searchController = topViewController?.navigationItem.searchController, delta > 0 {
if searchController.searchBar.frame.height != 0 {
return false
}
}
}
return true
}
// MARK: - UIGestureRecognizerDelegate
/**
UIGestureRecognizerDelegate function. Begin scrolling only if the direction is vertical (prevents conflicts with horizontal scroll views)
*/
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer else { return true }
let velocity = gestureRecognizer.velocity(in: gestureRecognizer.view)
return abs(velocity.y) > abs(velocity.x)
}
/**
UIGestureRecognizerDelegate function. Enables the scrolling of both the content and the navigation bar
*/
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
/**
UIGestureRecognizerDelegate function. Only scrolls the navigation bar with the content when `scrollingEnabled` is true
*/
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return scrollingEnabled
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mit |
spezzino/coursera-swift-week5 | Hamburguesas en el Mundo/Hamburguesas en el Mundo/AppDelegate.swift | 1 | 2160 | //
// AppDelegate.swift
// Hamburguesas en el Mundo
//
// Created by Stefano Pezzino on 12/6/15.
// Copyright © 2015 spezzino. All rights reserved.
//
import UIKit
@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:.
}
}
| lgpl-3.0 |
inket/stts | stts/Services/StatusPage/WeTransfer.swift | 1 | 197 | //
// WeTransfer.swift
// stts
//
import Foundation
class WeTransfer: StatusPageService {
let url = URL(string: "https://wetransfer.statuspage.io")!
let statusPageID = "sc26zwwp3c0r"
}
| mit |
proversity-org/edx-app-ios | Test/BranchConfigTests.swift | 1 | 693 | //
// BranchConfigTests.swift
// edX
//
// Created by Saeed Bashir on 9/29/17.
// Copyright © 2017 edX. All rights reserved.
//
import Foundation
import XCTest
@testable import edX
class BranchConfigTests: XCTestCase{
func testBranchConfig() {
let config = BranchConfig(dictionary: ["ENABLED": true, "BRANCH_KEY": "branch_key"])
XCTAssertNotNil(config)
XCTAssertTrue(config.enabled)
XCTAssertNotNil(config.branchKey)
}
func testEmptyBranchConfig() {
let config = BranchConfig(dictionary: [:])
XCTAssertNotNil(config)
XCTAssertFalse(config.enabled)
XCTAssertNil(config.branchKey)
}
}
| apache-2.0 |
taketin/SpeakLine | SpeakLineTests/SpeakLineTests.swift | 1 | 915 | //
// SpeakLineTests.swift
// SpeakLineTests
//
// Created by Takeshita Hidenori on 2015/05/25.
// Copyright (c) 2015年 taketin. All rights reserved.
//
import Cocoa
import XCTest
class SpeakLineTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
machelix/Lightbox | Source/LightboxView.swift | 1 | 4780 | import UIKit
public class LightboxView: UIView {
public var minimumZoomScale: CGFloat = 1
public var maximumZoomScale: CGFloat = 3
var lastZoomScale: CGFloat = -1
lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: CGRectZero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.userInteractionEnabled = true
return imageView
}()
lazy var scrollView: UIScrollView = { [unowned self] in
let scrollView = UIScrollView(frame: CGRectZero)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.multipleTouchEnabled = true
scrollView.minimumZoomScale = self.minimumZoomScale
scrollView.maximumZoomScale = self.maximumZoomScale
scrollView.delegate = self
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
var imageConstraintLeading: NSLayoutConstraint!
var imageConstraintTrailing: NSLayoutConstraint!
var imageConstraintTop: NSLayoutConstraint!
var imageConstraintBottom: NSLayoutConstraint!
var constraintsAdded = false
// MARK: - Initialization
public init(frame: CGRect, image: UIImage? = nil) {
super.init(frame: frame)
imageView.image = image
let config = LightboxConfig.sharedInstance.config
backgroundColor = config.backgroundColor
minimumZoomScale = config.zoom.minimumScale
maximumZoomScale = config.zoom.maximumScale
scrollView.addSubview(self.imageView)
addSubview(scrollView)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View lifecycle
public override func didMoveToSuperview() {
setUpConstraints()
}
// MARK: - Public methods
public func updateViewLayout() {
if constraintsAdded {
updateImageConstraints()
updateZoom()
}
}
// MARK: - Autolayout
public func setUpConstraints() {
if !constraintsAdded {
let layoutAttributes: [NSLayoutAttribute] = [.Leading, .Trailing, .Top, .Bottom]
for layoutAttribute in layoutAttributes {
addConstraint(NSLayoutConstraint(item: self.scrollView, attribute: layoutAttribute,
relatedBy: .Equal, toItem: self, attribute: layoutAttribute,
multiplier: 1, constant: 0))
}
imageConstraintLeading = NSLayoutConstraint(item: imageView, attribute: .Leading,
relatedBy: .Equal, toItem: scrollView, attribute: .Leading,
multiplier: 1, constant: 0)
imageConstraintTrailing = NSLayoutConstraint(item: imageView, attribute: .Trailing,
relatedBy: .Equal, toItem: scrollView, attribute: .Trailing,
multiplier: 1, constant: 0)
imageConstraintTop = NSLayoutConstraint(item: imageView, attribute: .Top,
relatedBy: .Equal, toItem: scrollView, attribute: .Top,
multiplier: 1, constant: 0)
imageConstraintBottom = NSLayoutConstraint(item: imageView, attribute: .Bottom,
relatedBy: .Equal, toItem: scrollView, attribute: .Bottom,
multiplier: 1, constant: 0)
addConstraints([imageConstraintLeading, imageConstraintTrailing,
imageConstraintTop, imageConstraintBottom])
layoutIfNeeded()
scrollView.contentSize = CGSize(width: frame.size.width, height: frame.size.height)
constraintsAdded = true
}
}
public func updateImageConstraints() {
if let image = imageView.image {
// Center image
var hPadding = (bounds.size.width - scrollView.zoomScale * image.size.width) / 2
if hPadding < 0 {
hPadding = 0
}
var vPadding = (bounds.size.height - scrollView.zoomScale * image.size.height) / 2
if vPadding < 0 {
vPadding = 0
}
for constraint in [imageConstraintLeading, imageConstraintTrailing] { constraint.constant = hPadding }
for constraint in [imageConstraintTop, imageConstraintBottom] { constraint.constant = vPadding }
layoutIfNeeded()
}
}
// MARK: - Zoom
public func updateZoom() {
if let image = imageView.image {
var minimumZoom = min(
bounds.size.width / image.size.width,
bounds.size.height / image.size.height)
if minimumZoom > 1 {
minimumZoom = 1
}
scrollView.minimumZoomScale = minimumZoom
if minimumZoom == lastZoomScale {
minimumZoom += 0.000001
}
scrollView.zoomScale = minimumZoom
lastZoomScale = minimumZoom
}
}
}
// MARK: - UIScrollViewDelegate
extension LightboxView: UIScrollViewDelegate {
public func scrollViewDidZoom(scrollView: UIScrollView) {
updateImageConstraints()
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blog Dashboard/Cards/Quick Start/QuickStartChecklistView.swift | 1 | 6008 | import UIKit
import WordPressShared
// A view representing the progress on a Quick Start checklist. Built according to old design specs.
//
// This view is used to display multiple Quick Start tour collections per Quick Start card.
//
// This view can be deleted once we've fully migrated to using NewQuicksTartChecklistView.
// See QuickStartChecklistConfigurable for more details.
//
final class QuickStartChecklistView: UIView, QuickStartChecklistConfigurable {
var tours: [QuickStartTour] = []
var blog: Blog?
var onTap: (() -> Void)?
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
labelStackView,
progressIndicatorView
])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.spacing = Metrics.mainStackViewSpacing
return stackView
}()
private lazy var labelStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
titleLabel,
subtitleLabel
])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = Metrics.labelStackViewSpacing
return stackView
}()
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = WPStyleGuide.serifFontForTextStyle(.body, fontWeight: .semibold)
label.adjustsFontForContentSizeCategory = true
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = Metrics.labelMinimumScaleFactor
label.textColor = .text
return label
}()
private lazy var subtitleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = WPStyleGuide.fontForTextStyle(.callout)
label.textColor = .textSubtle
return label
}()
private lazy var progressIndicatorView: ProgressIndicatorView = {
let appearance = ProgressIndicatorView.Appearance(
size: Metrics.progressIndicatorViewSize,
lineColor: .primary,
trackColor: .separator
)
let view = ProgressIndicatorView(appearance: appearance)
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.isAccessibilityElement = false
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
startObservingQuickStart()
}
required init?(coder: NSCoder) {
fatalError("Not implemented")
}
deinit {
stopObservingQuickStart()
}
func configure(collection: QuickStartToursCollection, blog: Blog) {
self.tours = collection.tours
self.blog = blog
titleLabel.text = collection.title
isAccessibilityElement = true
accessibilityTraits = .button
accessibilityHint = collection.hint
updateViews()
}
}
extension QuickStartChecklistView {
private func setupViews() {
addSubview(mainStackView)
pinSubviewToAllEdges(mainStackView, insets: Metrics.mainStackViewInsets)
let tap = UITapGestureRecognizer(target: self, action: #selector(didTap))
addGestureRecognizer(tap)
}
private func updateViews() {
guard let blog = blog,
let title = titleLabel.text else {
return
}
let completedToursCount = QuickStartTourGuide.shared.countChecklistCompleted(in: tours, for: blog)
if completedToursCount == tours.count {
titleLabel.attributedText = NSAttributedString(string: title, attributes: [NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue])
titleLabel.textColor = .textSubtle
} else {
titleLabel.attributedText = NSAttributedString(string: title, attributes: [:])
titleLabel.textColor = .text
}
let subtitle = String(format: Strings.subtitleFormat, completedToursCount, tours.count)
subtitleLabel.text = subtitle
// VoiceOver: Adding a period after the title to create a pause between the title and the subtitle
accessibilityLabel = "\(title). \(subtitle)"
let progress = Double(completedToursCount) / Double(tours.count)
progressIndicatorView.updateProgressLayer(with: progress)
}
private func startObservingQuickStart() {
NotificationCenter.default.addObserver(forName: .QuickStartTourElementChangedNotification, object: nil, queue: nil) { [weak self] notification in
guard let userInfo = notification.userInfo,
let element = userInfo[QuickStartTourGuide.notificationElementKey] as? QuickStartTourElement,
element == .tourCompleted else {
return
}
self?.updateViews()
}
}
private func stopObservingQuickStart() {
NotificationCenter.default.removeObserver(self)
}
@objc private func didTap() {
onTap?()
}
}
extension QuickStartChecklistView {
private enum Metrics {
static let mainStackViewInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16)
static let mainStackViewSpacing = 16.0
static let labelStackViewSpacing = 4.0
static let progressIndicatorViewSize = 24.0
static let labelMinimumScaleFactor = 0.5
}
private enum Strings {
static let subtitleFormat = NSLocalizedString("%1$d of %2$d completed",
comment: "Format string for displaying number of completed quickstart tutorials. %1$d is number completed, %2$d is total number of tutorials available.")
}
}
| gpl-2.0 |
weizhangCoder/DYZB_ZW | DYZB_ZW/DYZB_ZW/Classes/Main/Controller/CustomNavigationController.swift | 1 | 1795 | //
// CustomNavigationController.swift
// DYZB_ZW
//
// Created by 张三 on 1/11/17.
// Copyright © 2017年 jyall. All rights reserved.
//
import UIKit
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// 1.获取系统的Pop手势
guard let systemGes = interactivePopGestureRecognizer else{ return }
// 2.获取手势添加到的View中
guard let gesView = systemGes.view else {
return
}
// 3.获取target/action
// 3.1.利用运行时机制查看所有的属性名称
/*
var count : UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)!
for i in 0..<count {
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)
print(String(cString: name!))
}
*/
let targets = systemGes.value(forKey: "targets") as? [NSObject]
guard let targetObjc = targets?.first else {
return
}
// 3.2.取出target
guard let target = targetObjc.value(forKey: "target") else { return }
// 3.3.取出Action
let action = Selector(("handleNavigationTransition:"))
// 4.创建自己的Pan手势
let panGes = UIPanGestureRecognizer()
gesView.addGestureRecognizer(panGes)
panGes.addTarget(target, action: action)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
// 隐藏要push的控制器的tabbar
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
}
| mit |
PedroTrujilloV/TIY-Assignments | 11--Raiders-of-the-Lost-App/CustomCells/CustomCells/AnotherCell.swift | 1 | 535 | //
// AnotherCell.swift
// CustomCells
//
// Created by Ben Gohlke on 10/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class AnotherCell: UITableViewCell
{
@IBOutlet weak var aLabel: UILabel!
override func awakeFromNib()
{
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| cc0-1.0 |
narner/AudioKit | Examples/macOS/AudioUnitManager/AudioUnitManager/AudioUnitToolbar.swift | 1 | 1594 | //
// AudioUnitToolbar.swift
// AudioUnitManager
//
// Created by Ryan Francesconi on 10/8/17.
// Copyright © 2017 Ryan Francesconi. All rights reserved.
//
import AVFoundation
import Cocoa
class AudioUnitToolbar: NSView {
@IBInspectable var backgroundColor: NSColor?
var audioUnit: AVAudioUnit?
var bypassButton: NSButton?
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
initialize()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
initialize()
}
private func initialize() {
bypassButton = NSButton()
bypassButton!.frame = NSRect(x: 2, y: 2, width: 60, height: 16)
bypassButton!.controlSize = .mini
bypassButton!.bezelStyle = .rounded
bypassButton!.font = NSFont.systemFont(ofSize: 9)
bypassButton!.setButtonType(.pushOnPushOff)
bypassButton!.action = #selector(handleBypass)
bypassButton!.target = self
bypassButton!.title = "Bypass"
addSubview(bypassButton!)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if let bgColor = backgroundColor {
bgColor.setFill()
let rect = NSMakeRect(0, 0, bounds.width, bounds.height)
//let rectanglePath = NSBezierPath( roundedRect: rect, xRadius: 3, yRadius: 3)
rect.fill()
}
}
@objc func handleBypass() {
Swift.print("bypass: \(bypassButton!.state)")
audioUnit?.auAudioUnit.shouldBypassEffect = bypassButton!.state == .on
}
}
| mit |
emadhegab/GenericDataSource | GenericDataSourceTests/EditingActionsTester.swift | 1 | 2292 | //
// EditingActionsTester.swift
// GenericDataSource
//
// Created by Mohamed Ebrahim Mohamed Afifi on 3/14/17.
// Copyright © 2017 mohamede1945. All rights reserved.
//
import Foundation
import GenericDataSource
import XCTest
private class _ReportBasicDataSource<CellType>: ReportBasicDataSource<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
var result: [UITableViewRowAction]?
var indexPath: IndexPath?
override func ds_collectionView(_ collectionView: GeneralCollectionView, editActionsForItemAt indexPath: IndexPath) -> [UITableViewRowAction]? {
self.indexPath = indexPath
return result
}
}
class EditingActionsTester<CellType>: DataSourceTester where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
let dataSource: ReportBasicDataSource<CellType> = _ReportBasicDataSource<CellType>()
var result: [UITableViewRowAction]? {
return nil
}
required init(id: Int, numberOfReports: Int, collectionView: GeneralCollectionView) {
dataSource.items = Report.generate(numberOfReports: numberOfReports)
dataSource.registerReusableViewsInCollectionView(collectionView)
(dataSource as! _ReportBasicDataSource<CellType>).result = result
}
func test(indexPath: IndexPath, dataSource: AbstractDataSource, tableView: UITableView) -> [UITableViewRowAction]? {
return dataSource.tableView(tableView, editActionsForRowAt: indexPath)
}
func test(indexPath: IndexPath, dataSource: AbstractDataSource, collectionView: UICollectionView) -> [UITableViewRowAction]? {
return result
}
func assert(result: [UITableViewRowAction]?, indexPath: IndexPath, collectionView: GeneralCollectionView) {
if collectionView is UITableView {
XCTAssertIdentical(result, self.result)
XCTAssertEqual((dataSource as! _ReportBasicDataSource<CellType>).indexPath, indexPath)
}
}
}
let actions = [UITableViewRowAction(style: .destructive, title: "Edit", handler: { _ in })]
class EditingActionsTester2<CellType>: EditingActionsTester<CellType> where CellType: ReportCell, CellType: ReusableCell, CellType: NSObject {
override var result: [UITableViewRowAction]? {
return actions
}
}
| mit |
SwiftTools/Switt | Switt/Source/Converting/Swift/Module/File/Declarations/Type/Types/Protocol/ProtocolInitFromContextConverter.swift | 1 | 831 | import SwiftGrammar
protocol ProtocolInitFromContextConverter {
func convert(context: SwiftParser.Protocol_initializer_declarationContext?) -> ProtocolInit?
}
class ProtocolInitFromContextConverterImpl: ProtocolInitFromContextConverter {
private let assembly: ConvertingAssembly
init(assembly: ConvertingAssembly) {
self.assembly = assembly
}
func convert(context: SwiftParser.Protocol_initializer_declarationContext?) -> ProtocolInit? {
if let context = context {
return ProtocolInitData(
attributes: nil, // TODO
declarationModifiers: [], // TODO
parameters: [], // TODO
throwing: nil, // TODO
unwrapping: nil // TODO
)
} else {
return nil
}
}
} | mit |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommentTalentCell.swift | 1 | 2892 | //
// RecommentTalentCell.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/31.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommentTalentCell: UITableViewCell {
var cellArray:[RecipeRecommendWidgetData]?
var clickClosure:RecipClickClosure?{
didSet{
shorwData()
}
}
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var fansLabel: UILabel!
func shorwData()
{
//
if cellArray?.count > 0
{
let imgData = cellArray![0]
if imgData.type == "image"
{
imgView.kf_setImageWithURL(NSURL(string: imgData.content!), placeholderImage: UIImage(named: "sdefaultImage"))
}
}
//
if cellArray?.count > 1
{
let nameData = cellArray![1]
if nameData.type == "text"
{
nameLabel.text = nameData.content
}
}
//
if cellArray?.count > 2
{
let descData = cellArray![2]
if descData.type == "text"
{
descLabel.text = descData.content
}
}
//
if cellArray?.count > 3
{
let fansData = cellArray![3]
if fansData.type == "text"
{
fansLabel.text = fansData.content
}
}
//
let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick))
addGestureRecognizer(tap)
}
//创建cell
class func createTalentCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, cellArray:[RecipeRecommendWidgetData]?) ->RecommentTalentCell
{
let cellID = "recommentTalentCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommentTalentCell
if cell == nil
{
cell = NSBundle.mainBundle().loadNibNamed("RecommentTalentCell", owner: nil, options: nil).last as? RecommentTalentCell
}
cell?.cellArray = cellArray!
return cell!
}
func tapClick()
{
if cellArray?.count > 0
{
let imgData = cellArray![0]
if clickClosure != nil && imgData.link != nil
{
clickClosure!(imgData.link!)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
imgView.layer.cornerRadius = 35
imgView.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
miken01/SwiftData | SwiftDataTests/SwiftDataTests.swift | 1 | 986 | //
// SwiftDataTests.swift
// SwiftDataTests
//
// Created by Mike Neill on 10/26/15.
// Copyright © 2015 Mike's App Shop. All rights reserved.
//
import XCTest
@testable import SwiftData
class SwiftDataTests: 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 testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| gpl-3.0 |
priya273/stockAnalyzer | Stock Analyzer/Stock Analyzer/StockContract.swift | 1 | 675 | //
// StockContract.swift
// Stock Analyzer
//
// Created by Naga sarath Thodime on 3/16/16.
// Copyright © 2016 Priyadarshini Ragupathy. All rights reserved.
//
import Foundation
class StockContract
{
var change: NSNumber?
var changePercent: NSNumber?
var exchange: String?
var high: NSNumber?
var lastPrice: NSNumber?
var low: NSNumber?
var marketCap: NSNumber?
var name: String?
var open: NSNumber?
var symbol: String?
var timestamp: String?
var volumn: NSNumber?
init()
{
print("Created Stock contract");
}
deinit
{
print("Disposed Stock contract");
}
} | apache-2.0 |
milseman/swift | validation-test/compiler_crashers_fixed/28263-swift-typechecker-validatedecl.swift | 65 | 495 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol e{func^
protocol P{
extension{
class A{
protocol c:e
protocol P{
typealias e:c{
}func^
| apache-2.0 |
brentdax/SQLKit | Sources/PostgreSQLKit/PostgreSQLKitError.swift | 1 | 943 | //
// PostgreSQLKitError.swift
// LittlinkRouterPerfect
//
// Created by Brent Royal-Gordon on 12/3/16.
//
//
import Foundation
import CorePostgreSQL
/// Errors specific to `PostgreSQLKit`.
///
/// Note that most errors you might find underlying `SQLError`s will *not* be
/// `PostgreSQLKitError`s, but rather `PGError`s from the underlying
/// `CorePostgreSQL` library. If you want to perform rich, detailed matching of
/// errors, use that type to do so.
public enum PostgreSQLKitError: Error {
/// The timestamp does not correspond to a valid date in the Gregorian
/// calendar, so it cannot be converted to a `Date`.
case invalidDate(PGTimestamp)
}
extension PostgreSQLKitError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidDate(let timestamp):
return NSLocalizedString("Cannot convert \(timestamp) to an NSDate.", comment: "")
}
}
}
| mit |
Zglove/DouYu | DYTV/DYTV/Classes/Home/View/CollectionCycleCell.swift | 1 | 770 | //
// CollectionCycleCell.swift
// DYTV
//
// Created by people on 2016/11/7.
// Copyright © 2016年 people2000. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionCycleCell: UICollectionViewCell {
//MARK:- 控件属性
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
//MARK:- 定义模型属性
var cycleModel: CycleModel? {
didSet{
titleLabel.text = cycleModel?.title
let iconURL = NSURL(string: cycleModel?.pic_url ?? "")!
let resource = ImageResource.init(downloadURL: iconURL as URL)
iconImageView.kf.setImage(with: resource, placeholder: UIImage(named: "Img_default"))
}
}
}
| mit |
larryhou/swift | Regions/Regions/PlacemarkViewController.swift | 1 | 3123 | //
// LocationViewController.swift
// Regions
//
// Created by doudou on 9/5/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import Foundation
import CoreLocation
import UIKit
class PlacemarkViewController: UITableViewController {
let CELL_IDENTIFIER: String = "PlacemarkCell"
var placemark: CLPlacemark!
private var list: [NSObject]!
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "PlacemarkCell", bundle: nil), forCellReuseIdentifier: CELL_IDENTIFIER)
list = []
for (key, value) in placemark.addressDictionary {
list.append(key)
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:return "Attributes"
case 1:return "Address Dictionary"
default:return "Geographic"
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_IDENTIFIER) as UITableViewCell!
if indexPath.section == 0 {
switch indexPath.row {
case 0:
cell.textLabel?.text = "name"
cell.detailTextLabel?.text = placemark.name
case 1:
cell.textLabel?.text = "country"
cell.detailTextLabel?.text = placemark.country
case 2:
cell.textLabel?.text = "administrativeArea"
cell.detailTextLabel?.text = placemark.administrativeArea
case 3:
cell.textLabel?.text = "subAdministrativeArea"
cell.detailTextLabel?.text = placemark.subAdministrativeArea
case 4:
cell.textLabel?.text = "locality"
cell.detailTextLabel?.text = placemark.locality
case 5:
cell.textLabel?.text = "subLocality"
cell.detailTextLabel?.text = placemark.subLocality
case 6:
cell.textLabel?.text = "thoroughfare"
cell.detailTextLabel?.text = placemark.thoroughfare
case 7:
cell.textLabel?.text = "subThoroughfare"
cell.detailTextLabel?.text = placemark.subThoroughfare
case 8:
cell.textLabel?.text = "ISOcountryCode"
cell.detailTextLabel?.text = placemark.ISOcountryCode
default:
cell.textLabel?.text = "postalCode"
cell.detailTextLabel?.text = placemark.postalCode
}
} else
if indexPath.section == 1 {
var key = list[indexPath.row]
var value: AnyObject = placemark.addressDictionary[key]!
cell.textLabel?.text = key.description
if value is [String] {
cell.detailTextLabel?.text = (value as [String]).first
} else {
cell.detailTextLabel?.text = (value as String)
}
} else {
if indexPath.row == 0 {
cell.textLabel?.text = "inlandWater"
cell.detailTextLabel?.text = placemark.inlandWater
} else {
cell.textLabel?.text = "ocean"
cell.detailTextLabel?.text = placemark.ocean
}
}
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:return 10
case 1:return placemark.addressDictionary.count
default:return 2
}
}
}
| mit |
hashier/transfer.sh-mac | transfer.sh/DestinationView.swift | 1 | 2235 | //
// DestinationView.swift
// transfer.sh
//
// Created by Christopher Loessl on 2016-10-16.
// Copyright © 2016 chl. All rights reserved.
//
import Foundation
import Cocoa
protocol DestinationViewDelegate {
func processFileURLs(_ urls: [URL])
}
private let lineWidth: CGFloat = 6.0
class DestinationView: NSView {
private var isReceivingDrag = false {
didSet {
needsDisplay = true
}
}
var delegate: DestinationViewDelegate?
private var acceptedTypes = [kUTTypeFileURL as String]
// https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PasteboardGuide106/Articles/pbReading.html
private lazy var filteringOptions = [NSPasteboardURLReadingFileURLsOnlyKey : true]
override func awakeFromNib() {
setup()
}
private func setup() {
self.register(forDraggedTypes: acceptedTypes)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if isReceivingDrag {
NSColor.selectedControlColor.set()
let path = NSBezierPath(rect: bounds)
path.lineWidth = lineWidth
path.stroke()
}
}
private func shouldAllowDrag(_ draggingInfo: NSDraggingInfo) -> Bool {
var canAccept = false
let pasteBoard = draggingInfo.draggingPasteboard()
if pasteBoard.canReadObject(forClasses: [NSURL.self], options: filteringOptions) {
canAccept = true
}
return canAccept
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
let allow = shouldAllowDrag(sender)
isReceivingDrag = allow
return allow ? .copy : NSDragOperation()
}
override func draggingExited(_ sender: NSDraggingInfo?) {
isReceivingDrag = false
}
override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool {
isReceivingDrag = false
let pasteBoard = draggingInfo.draggingPasteboard()
if let urls = pasteBoard.readObjects(forClasses: [NSURL.self], options: filteringOptions) as? [URL], !urls.isEmpty {
delegate?.processFileURLs(urls)
return true
}
return false
}
}
| mit |
Romdeau4/16POOPS | Helps_Kitchen_iOS/Help's Kitchen/HomeViewController.swift | 1 | 2867 | //
// HomeViewController.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 2/13/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
import Firebase
class HomeViewController: UIViewController {
let ref = FIRDatabase.database().reference(fromURL: DataAccess.URL)
override func viewDidLoad() {
super.viewDidLoad()
checkStatus()
}
override func viewDidAppear(_ animated: Bool){
checkStatus()
}
func checkStatus() {
let uid = FIRAuth.auth()?.currentUser?.uid
if uid == nil {
handleLogout()
}else{
ref.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
for userType in snapshot.children {
let currentUserType = userType as! FIRDataSnapshot
for user in currentUserType.children {
let currentUser = user as! FIRDataSnapshot
if currentUser.key == uid {
switch currentUserType.key{
case "Host":
let hostController = HostSeatingController()
let navController = CustomNavigationController(rootViewController: hostController)
self.present(navController, animated: true, completion: nil)
case "Server":
let serverController = ServerTabBarController()
self.present(serverController, animated: true, completion: nil)
case "Kitchen":
let kitchenController = KitchenOrderListController()
let navController = CustomNavigationController(rootViewController: kitchenController)
self.present(navController, animated: true, completion: nil)
//TODO Add Kitchen ViewController
default:
self.handleLogout()
}
}
}
}
})
}
}
func handleLogout() {
do{
try FIRAuth.auth()?.signOut()
}catch let logoutError {
print(logoutError)
}
let loginViewController = LoginViewController()
present(loginViewController, animated: true, completion: nil)
}
}
| mit |
lkzhao/Hero | Sources/Extensions/CALayer+Hero.swift | 1 | 2091 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <me@lkzhao.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(UIKit)
import UIKit
internal extension CALayer {
// return all animations running by this layer.
// the returned value is mutable
var animations: [(String, CAAnimation)] {
if let keys = animationKeys() {
// swiftlint:disable:next force_cast
return keys.map { return ($0, self.animation(forKey: $0)!.copy() as! CAAnimation) }
}
return []
}
func flatTransformTo(layer: CALayer) -> CATransform3D {
var layer = layer
var trans = layer.transform
while let superlayer = layer.superlayer, superlayer != self, !(superlayer.delegate is UIWindow) {
trans = CATransform3DConcat(superlayer.transform, trans)
layer = superlayer
}
return trans
}
func removeAllHeroAnimations() {
guard let keys = animationKeys() else { return }
for animationKey in keys where animationKey.hasPrefix("hero.") {
removeAnimation(forKey: animationKey)
}
}
}
#endif
| mit |
thecb4/SwifterCSV | Sources/ParserHelpers.swift | 1 | 1209 |
//
// Parser.swift
// SwifterCSV
//
// Created by Will Richardson on 11/04/16.
// Copyright © 2016 JavaNut13. All rights reserved.
//
extension CSV {
/// List of dictionaries that contains the CSV data
public var rows: [[String: String]] {
if _rows == nil {
parse()
}
return _rows!
}
/// Parse the file and call a block for each row, passing it as a dictionary
public func enumerateAsDict(_ block: @escaping ([String: String]) -> ()) {
let enumeratedHeader = header.enumerated()
enumerateAsArray { fields in
var dict = [String: String]()
for (index, head) in enumeratedHeader {
dict[head] = index < fields.count ? fields[index] : ""
}
block(dict)
}
}
/// Parse the file and call a block on each row, passing it in as a list of fields
public func enumerateAsArray(_ block: @escaping ([String]) -> ()) {
self.enumerateAsArray(block, limitTo: nil, startAt: 1)
}
private func parse() {
var rows = [[String: String]]()
enumerateAsDict { dict in
rows.append(dict)
}
_rows = rows
}
}
| mit |
superman-coder/pakr | pakr/pakr/Model/Web/Bookmark.swift | 1 | 992 | //
// Created by Huynh Quang Thao on 4/9/16.
// Copyright (c) 2016 Pakr. All rights reserved.
//
import Foundation
import Parse
class Bookmark:Post, ParseModelProtocol {
let PKTopicId = "topicId"
var topicId: String!
var topic: Topic!
init(userId: String!, topicId: String!, topic: Topic!) {
self.topicId = topicId
self.topic = topic
super.init(userId: userId)
}
required init(pfObject: PFObject) {
topicId = pfObject[PKTopicId] as! String
let userId = pfObject[Bookmark.PKPostUser].objectId
super.init(userId: userId)
self.dateCreated = pfObject.createdAt
self.postId = pfObject.objectId
}
func toPFObject() -> PFObject {
let pfObject = PFObject(className: Constants.Table.Bookmark)
pfObject[Bookmark.PKPostUser] = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
pfObject[PKTopicId] = topicId
return pfObject
}
}
| apache-2.0 |
Rep2/IRSocket | IRSocket/IRSocketReader.swift | 1 | 653 | //
// IRSocketReader.swift
// RASUSLabos
//
// Created by Rep on 12/15/15.
// Copyright © 2015 Rep. All rights reserved.
//
import Foundation
class IRSocketReader{
let socket: IRSocket
init(socket:IRSocket){
self.socket = socket
}
func read(observerFunc: (Array<UInt8>, IRSockaddr) -> Void){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
repeat{
let (data, addr) = self.socket.reciveAndStoreAddres()
observerFunc(data, addr)
}while(true)
})
}
} | mit |
allsome/LSYPaper | LSYPaper/BigNewsDetailCell.swift | 1 | 33155 | //
// NewsDetailCell.swift
// LSYPaper
//
// Created by 梁树元 on 1/9/16.
// Copyright © 2016 allsome.love. All rights reserved.
//
import UIKit
import AVFoundation
public let bottomViewDefaultHeight:CGFloat = 55
private let transform3Dm34D:CGFloat = 1900.0
private let newsViewWidth:CGFloat = (SCREEN_WIDTH - 50) / 2
private let shiningImageHeight:CGFloat = (SCREEN_WIDTH - 50) * 296 / 325
private let newsViewY:CGFloat = SCREEN_HEIGHT - 20 - bottomViewDefaultHeight - newsViewWidth * 2
private let endAngle:CGFloat = CGFloat(M_PI) / 2.5
private let startAngle:CGFloat = CGFloat(M_PI) / 3.3
private let animateDuration:Double = 0.25
private let minScale:CGFloat = 0.97
private let maxFoldAngle:CGFloat = 1.0
private let minFoldAngle:CGFloat = 0.75
private let translationYForView:CGFloat = SCREEN_WIDTH - newsViewY
private let normalScale:CGFloat = SCREEN_WIDTH / (newsViewWidth * 2)
private let baseShadowRedius:CGFloat = 50.0
private let emitterWidth:CGFloat = 35.0
private let realShiningBGColor:UIColor = UIColor(white: 0.0, alpha: 0.4)
class BigNewsDetailCell: UICollectionViewCell {
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var upperScreenShot: UIImageView!
@IBOutlet weak var baseScreenShot: UIImageView!
@IBOutlet weak var baseLayerViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var webViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var realShiningView: UIView!
@IBOutlet weak var realBaseView: UIView!
@IBOutlet weak var totalView: UIView!
@IBOutlet weak var shiningViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var newsViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var coreViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak private var shadowView: UIView!
@IBOutlet weak private var shiningView: UIView!
@IBOutlet weak private var shiningImage: UIImageView!
@IBOutlet weak private var baseLayerView: UIView!
@IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var newsView: UIView!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var commentButton: UIButton!
@IBOutlet weak var summaryLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var labelView: UIView!
private var panNewsView:UIPanGestureRecognizer = UIPanGestureRecognizer()
private var panWebView:UIPanGestureRecognizer = UIPanGestureRecognizer()
private var tapSelf:UITapGestureRecognizer = UITapGestureRecognizer()
private var topLayer:CALayer = CALayer()
private var bottomLayer:CALayer = CALayer()
private var isHasRequest:Bool = false
private var isLike:Bool = false
private var isShare:Bool = false {
didSet {
if isShare == true {
LSYPaperPopView.showPopViewWith(CGRect(x: 0, y: SCREEN_HEIGHT - 47 - sharePopViewHeight, width: SCREEN_WIDTH, height: sharePopViewHeight), viewMode: LSYPaperPopViewMode.share,inView: totalView, frontView: bottomView, revokeOption: { () -> Void in
self.shareButton.addPopSpringAnimation()
self.revokePopView()
})
}else {
LSYPaperPopView.hidePopView(totalView)
}
}
}
private var isComment:Bool = false {
didSet {
if isComment == true {
LSYPaperPopView.showPopViewWith(CGRect(x: 0, y: SCREEN_HEIGHT - commentPopViewHeight - 47, width: SCREEN_WIDTH, height: commentPopViewHeight), viewMode: LSYPaperPopViewMode.comment,inView: totalView, frontView: bottomView,revokeOption: { () -> Void in
self.revokePopView()
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.labelView.alpha = 1.0
}, completion: { (stop:Bool) -> Void in
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.labelView.alpha = 0.0
})
})
})
}else {
LSYPaperPopView.hidePopView(totalView)
}
}
}
var isDarkMode:Bool = false {
didSet {
if isDarkMode == true {
tapSelf.isEnabled = true
sendCoreViewToBack()
LSYPaperPopView.showBackgroundView(totalView)
if isLike == false {
likeButton.setImage(UIImage(named: "LikePhoto"), for: UIControlState())
}
commentButton.setImage(UIImage(named: "CommentPhoto"), for: UIControlState())
shareButton.setImage(UIImage(named: "SharePhoto"), for: UIControlState())
summaryLabel.textColor = UIColor.white
commentLabel.textColor = UIColor.white
}else {
tapSelf.isEnabled = false
LSYPaperPopView.hideBackgroundView(totalView, completion: { () -> Void in
self.bringCoreViewToFront()
})
if isLike == false {
likeButton.setImage(UIImage(named: "Like"), for: UIControlState())
}
commentButton.setImage(UIImage(named: "Comment"), for: UIControlState())
shareButton.setImage(UIImage(named: "Share"), for: UIControlState())
summaryLabel.textColor = UIColor.lightGray
commentLabel.textColor = UIColor.lightGray
}
}
}
private var locationInSelf:CGPoint = CGPoint.zero
private var translationInSelf:CGPoint = CGPoint.zero
private var velocityInSelf:CGPoint = CGPoint.zero
private var transform3D:CATransform3D = CATransform3DIdentity
private var transformConcat:CATransform3D {
return CATransform3DConcat(CATransform3DRotate(transform3D, transform3DAngle, 1, 0, 0), CATransform3DMakeTranslation(translationInSelf.x, 0, 0))
}
private var foldScale:CGFloat {
let a = (normalScale - 1) / ((maxFoldAngle - minFoldAngle) * CGFloat(M_PI))
let b = 1 - (normalScale - 1) * minFoldAngle / (maxFoldAngle - minFoldAngle)
return a * transform3DAngleFold + b <= 1 ? 1 : a * transform3DAngleFold + b
}
private var transformConcatFold:CATransform3D {
return CATransform3DConcat(CATransform3DConcat(CATransform3DRotate(transform3D, transform3DAngleFold, 1, 0, 0), CATransform3DMakeTranslation(translationInSelf.x / foldScale, translationYForView / foldScale, 0)), CATransform3DMakeScale(foldScale, foldScale, 1))
}
private var transformEndedConcat:CATransform3D {
let scale = normalScale
return CATransform3DConcat(CATransform3DConcat(CATransform3DRotate(transform3D, CGFloat(M_PI), 1, 0, 0), CATransform3DMakeTranslation(0, translationYForView / scale, 0)), CATransform3DMakeScale(scale, scale, 1))
}
private var transform3DAngle:CGFloat {
let cosUpper = locationInSelf.y - newsViewY >= (newsViewWidth * 2) ? (newsViewWidth * 2) : locationInSelf.y - newsViewY
return acos(cosUpper / (newsViewWidth * 2))
+ asin((locationInSelf.y - newsViewY) / transform3Dm34D)
}
private var transform3DAngleFold:CGFloat {
let cosUpper = locationInSelf.y - SCREEN_WIDTH
return acos(cosUpper / SCREEN_WIDTH)
}
private var webViewRequest:URLRequest {
return URLRequest(url: URL(string: "https://github.com")!)
}
private var soundID:SystemSoundID {
var soundID:SystemSoundID = 0
let path = Bundle.main.path(forResource: "Pop", ofType: "wav")
let baseURL = URL(fileURLWithPath: path!)
AudioServicesCreateSystemSoundID(baseURL, &soundID)
return soundID
}
@IBOutlet weak var likeView: UIView!
@IBOutlet weak var alphaView: UIView!
@IBOutlet weak var coreView: UIView!
private var explosionLayer:CAEmitterLayer = CAEmitterLayer()
private var chargeLayer:CAEmitterLayer = CAEmitterLayer()
var unfoldWebViewOption:(() -> Void)?
var foldWebViewOption:(() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
layer.masksToBounds = true
layer.cornerRadius = CORNER_REDIUS
labelView.layer.masksToBounds = true
labelView.layer.cornerRadius = CORNER_REDIUS
totalView.layer.masksToBounds = true
totalView.layer.cornerRadius = cellGap * 2
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0, height: 2)
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.shadowRadius = 1.0
baseLayerView.layer.shadowColor = UIColor.black.cgColor
baseLayerView.layer.shadowOffset = CGSize(width: 0, height: baseShadowRedius)
baseLayerView.layer.shadowOpacity = 0.8
baseLayerView.layer.shadowRadius = baseShadowRedius
baseLayerView.alpha = 0.0
newsView.layer.shadowColor = UIColor.clear.cgColor
newsView.layer.shadowOffset = CGSize(width: 0, height: baseShadowRedius)
newsView.layer.shadowOpacity = 0.4
newsView.layer.shadowRadius = baseShadowRedius
upperScreenShot.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI), 1, 0, 0)
let pan = UIPanGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleNewsPanGesture(_:)))
pan.delegate = self
newsView.addGestureRecognizer(pan)
panNewsView = pan
let tap = UITapGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleNewsTapGesture(_:)))
newsView.addGestureRecognizer(tap)
transform3D.m34 = -1 / transform3Dm34D
webViewHeightConstraint.constant = SCREEN_WIDTH * 2
webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, SCREEN_WIDTH * 2 - SCREEN_HEIGHT, 0)
let webViewPan = UIPanGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleWebPanGesture(_:)))
webViewPan.delegate = self
webView.addGestureRecognizer(webViewPan)
panWebView = webViewPan
let tapContent = UITapGestureRecognizer(target: self, action: #selector(BigNewsDetailCell.handleContentTapGesture(_:)))
contentView.addGestureRecognizer(tapContent)
tapContent.isEnabled = false
tapSelf = tapContent
// heavily refer to MCFireworksView by Matthew Cheok
let explosionCell = CAEmitterCell()
explosionCell.name = "explosion"
explosionCell.alphaRange = 0.2
explosionCell.alphaSpeed = -1.0
explosionCell.lifetime = 0.5
explosionCell.lifetimeRange = 0.0
explosionCell.birthRate = 0
explosionCell.velocity = 44.00
explosionCell.velocityRange = 7.00
explosionCell.contents = UIImage(named: "Sparkle")?.cgImage
explosionCell.scale = 0.05
explosionCell.scaleRange = 0.02
let explosionLayer = CAEmitterLayer()
explosionLayer.name = "emitterLayer"
explosionLayer.emitterShape = kCAEmitterLayerCircle
explosionLayer.emitterMode = kCAEmitterLayerOutline
explosionLayer.emitterSize = CGSize(width: emitterWidth, height: 0)
let center = CGPoint(x: likeView.bounds.midX, y: likeView.bounds.midY)
explosionLayer.emitterPosition = center
explosionLayer.emitterCells = [explosionCell]
explosionLayer.masksToBounds = false
likeView.layer.addSublayer(explosionLayer)
self.explosionLayer = explosionLayer
let chargeCell = CAEmitterCell()
chargeCell.name = "charge"
chargeCell.alphaRange = 0.20
chargeCell.alphaSpeed = -1.0
chargeCell.lifetime = 0.3
chargeCell.lifetimeRange = 0.1
chargeCell.birthRate = 0
chargeCell.velocity = -60.0
chargeCell.velocityRange = 0.00
chargeCell.contents = UIImage(named: "Sparkle")?.cgImage
chargeCell.scale = 0.05
chargeCell.scaleRange = 0.02
let chargeLayer = CAEmitterLayer()
chargeLayer.name = "emitterLayer"
chargeLayer.emitterShape = kCAEmitterLayerCircle
chargeLayer.emitterMode = kCAEmitterLayerOutline
chargeLayer.emitterSize = CGSize(width: emitterWidth - 10, height: 0)
chargeLayer.emitterPosition = center
chargeLayer.emitterCells = [chargeCell]
chargeLayer.masksToBounds = false
likeView.layer.addSublayer(chargeLayer)
self.chargeLayer = chargeLayer
}
func handleContentTapGesture(_ recognizer:UITapGestureRecognizer) {
revokePopView()
}
func handleNewsTapGesture(_ recognizer:UITapGestureRecognizer) {
anchorPointSetting()
baseLayerView.alpha = 1.0
realBaseView.alpha = 0.5
locationInSelf = CGPoint(x: 0, y: SCREEN_HEIGHT - 9.5)
gestureStateChangedSetting(transform3DAngle)
tapNewsView()
}
func handleWebPanGesture(_ recognizer:UIPanGestureRecognizer) {
locationInSelf = recognizer.location(in: self)
translationInSelf = recognizer.translation(in: self)
if recognizer.state == UIGestureRecognizerState.began {
baseScreenShot.image = self.getSubImageFrom(self.getWebViewScreenShot(), frame: CGRect(x: 0, y: SCREEN_WIDTH, width: SCREEN_WIDTH, height: SCREEN_WIDTH))
upperScreenShot.image = self.getSubImageFrom(self.getWebViewScreenShot(), frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH))
webView.scrollView.panGestureRecognizer.isEnabled = false
webView.alpha = 0.0
let ratio = (M_PI - Double(transform3DAngleFold)) / M_PI
let alpha:CGFloat = transform3DAngleFold / CGFloat(M_PI) >= 0.5 ? 1.0 : 0.0
UIView.animate(withDuration: (animateDuration * 2 + 0.2) * ratio, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformConcatFold
self.shiningView.layer.transform = self.transformConcatFold
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(self.foldScale, self.foldScale, 1), CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView, 0))
self.newsView.layer.shadowColor = UIColor.black.cgColor
self.realBaseView.alpha = 0.5
self.realShiningView.alpha = 0.5
self.upperScreenShot.alpha = alpha
}, completion: { (stop:Bool) -> Void in
})
}else if recognizer.state == UIGestureRecognizerState.changed && webView.scrollView.panGestureRecognizer.isEnabled == false {
newsView.layer.transform = transformConcatFold
shiningView.layer.transform = transformConcatFold
baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(foldScale, foldScale, 1), CATransform3DMakeTranslation(translationInSelf.x, translationYForView, 0))
shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (transform3DAngleFold - startAngle) / (endAngle - startAngle))
gestureStateChangedSetting(transform3DAngleFold)
}else if (recognizer.state == UIGestureRecognizerState.cancelled || recognizer.state == UIGestureRecognizerState.ended) && webView.scrollView.panGestureRecognizer.isEnabled == false{
webView.scrollView.panGestureRecognizer.isEnabled = true
velocityInSelf = recognizer.velocity(in: self)
if self.velocityInSelf.y < 0 {
if transform3DAngleFold / CGFloat(M_PI) < 0.5 {
UIView.animate(withDuration: animateDuration * Double((CGFloat(M_PI) - transform3DAngleFold) / CGFloat(M_PI * 2)), delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView, 0))
self.shiningView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView, 0))
}, completion: { (stop:Bool) -> Void in
self.upperScreenShot.alpha = 1.0
self.shiningImage.alpha = 0.0
self.realShiningView.alpha = 1.0
self.shiningView.backgroundColor = UIColor.white
self.realShiningView.backgroundColor = realShiningBGColor
self.newsView.layer.shadowColor = UIColor.black.cgColor
self.shadowView.layer.shadowColor = UIColor.clear.cgColor
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(self.foldScale, self.foldScale, 1), CATransform3DMakeTranslation(self.translationInSelf.x, translationYForView / ((normalScale)), 0))
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeTranslation(0, translationYForView / ((normalScale)), 0),CATransform3DMakeScale(normalScale, normalScale, 1))
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
}, completion: { (stop:Bool) -> Void in
if self.velocityInSelf.y <= 0 {
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
}
})
})
}else {
baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(foldScale, foldScale, 1), CATransform3DMakeTranslation(translationInSelf.x, translationYForView / ((normalScale)), 0))
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeTranslation(0, translationYForView / ((normalScale)), 0),CATransform3DMakeScale(normalScale, normalScale, 1))
self.shiningImage.alpha = 0.0
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
},completion: { (stop:Bool) -> Void in
if self.velocityInSelf.y <= 0 {
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
}
})
}
}else {
self.normalLayoutNewsView()
}
}
}
func handleNewsPanGesture(_ recognizer:UIPanGestureRecognizer) {
locationInSelf = recognizer.location(in: self)
if recognizer.state == UIGestureRecognizerState.began {
anchorPointSetting()
translationInSelf = recognizer.translation(in: self)
UIView.animate(withDuration: animateDuration * 2 + 0.2, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.newsView.layer.transform = self.transformConcat
self.shiningView.layer.transform = self.transformConcat
self.shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (self.transform3DAngle - startAngle) / (endAngle - startAngle))
self.totalView.transform = CGAffineTransform(scaleX: minScale, y: minScale)
self.baseLayerView.alpha = 1.0
self.realBaseView.alpha = 0.5
}, completion: { (stop:Bool) -> Void in
})
}else if recognizer.state == UIGestureRecognizerState.changed {
translationInSelf = recognizer.translation(in: self)
newsView.layer.transform = transformConcat
shiningView.layer.transform = transformConcat
baseLayerView.layer.transform = CATransform3DMakeTranslation(translationInSelf.x, 0, 0)
shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (transform3DAngle - startAngle) / (endAngle - startAngle))
gestureStateChangedSetting(transform3DAngle)
}else if (recognizer.state == UIGestureRecognizerState.cancelled || recognizer.state == UIGestureRecognizerState.ended){
velocityInSelf = recognizer.velocity(in: self)
if self.velocityInSelf.y <= 0 {
if transform3DAngle / CGFloat(M_PI) < 0.5 {
tapNewsView()
}else {
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(normalScale, normalScale, 1), CATransform3DMakeTranslation(0, translationYForView, 0))
self.shiningImage.alpha = 0.0
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
},completion: { (stop:Bool) -> Void in
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
})
}
}else {
self.normalLayoutNewsView()
}
}
}
func revokePopView() {
isDarkMode = false
if isShare == true {
isShare = false
}else {
isComment = false
}
}
}
private extension BigNewsDetailCell {
@IBAction func showCommentOrNot(_ sender: UIButton) {
if isComment == false {
if isDarkMode == false {
isDarkMode = true
}else {
isShare = false
}
}else {
isDarkMode = false
}
if sender.tag != 1 {
commentButton.addSpringAnimation()
}
isComment = !isComment
}
@IBAction func showShareOrNot(_ sender: AnyObject) {
if isShare == false {
if isDarkMode == false {
isDarkMode = true
}else {
isComment = false
}
}else {
isDarkMode = false
}
shareButton.addSpringAnimation()
isShare = !isShare
}
@IBAction func likeOrNot(_ sender: AnyObject) {
if isLike == false {
likeButton.addSpringAnimation(1.3, durationArray: [0.05,0.1,0.23,0.195,0.155,0.12], delayArray: [0.0,0.0,0.1,0.0,0.0,0.0], scaleArray: [0.75,1.8,0.8,1.0,0.95,1.0])
chargeLayer.setValue(100, forKeyPath: "emitterCells.charge.birthRate")
delay((0.05 + 0.1 + 0.23) * 1.3, closure: { () -> Void in
self.chargeLayer.setValue(0, forKeyPath: "emitterCells.charge.birthRate")
self.explosionLayer.setValue(1000, forKeyPath: "emitterCells.explosion.birthRate")
self.delay(0.1, closure: { () -> Void in
self.explosionLayer.setValue(0, forKeyPath: "emitterCells.explosion.birthRate")
})
AudioServicesPlaySystemSound(self.soundID)
})
likeButton.setImage(UIImage(named: "Like-Blue"), for: UIControlState())
self.commentLabel.text = "Awesome!"
self.commentLabel.addFadeAnimation()
}else {
likeButton.addSpringAnimation()
let image = isDarkMode == false ? UIImage(named: "Like") : UIImage(named: "LikePhoto")
likeButton.setImage(image, for: UIControlState())
self.commentLabel.text = "Write a comment"
self.commentLabel.addFadeAnimation()
}
isLike = !isLike
}
private func bringCoreViewToFront() {
totalView.backgroundColor = UIColor.white
contentView.backgroundColor = UIColor.clear
contentView.bringSubview(toFront: coreView)
contentView.bringSubview(toFront: webView)
}
private func sendCoreViewToBack() {
totalView.backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.white
contentView.sendSubview(toBack: coreView)
}
private func loadWebViewRequest() {
if self.isHasRequest == false {
self.webView.loadRequest(self.webViewRequest)
self.isHasRequest = true
}
}
private func anchorPointSetting() {
newsView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
newsViewBottomConstraint.constant = newsViewWidth
shiningView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
shiningViewBottomConstraint.constant = newsViewWidth
baseLayerView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
baseLayerViewBottomConstraint.constant = newsViewWidth
}
private func getWebViewScreenShot() -> UIImage{
UIGraphicsBeginImageContextWithOptions(webView.frame.size, false, 1.0)
webView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
private func getSubImageFrom(_ originImage:UIImage,frame:CGRect) -> UIImage {
let imageRef = originImage.cgImage
let subImageRef = imageRef?.cropping(to: frame)
UIGraphicsBeginImageContext(frame.size)
let context = UIGraphicsGetCurrentContext()
context?.draw(in: frame, image: subImageRef!)
let subImage = UIImage(cgImage: subImageRef!)
UIGraphicsEndImageContext();
return subImage;
}
private func tapNewsView() {
UIView.animate(withDuration: animateDuration * Double((CGFloat(M_PI) - transform3DAngleFold) / CGFloat(M_PI * 2)), delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, 0, 0))
self.shiningView.layer.transform = CATransform3DConcat(CATransform3DRotate(self.transform3D, CGFloat(M_PI_2), 1, 0, 0),CATransform3DMakeTranslation(self.translationInSelf.x, 0, 0))
self.shiningImage.transform = CGAffineTransform(translationX: 0, y: shiningImageHeight + newsViewWidth * 2 * (self.transform3DAngle - startAngle) / (endAngle - startAngle))
}, completion: { (stop:Bool) -> Void in
self.shiningImage.alpha = 0.0
self.realShiningView.alpha = 0.5
self.upperScreenShot.alpha = 1.0
self.shiningView.backgroundColor = UIColor.white
self.realShiningView.backgroundColor = realShiningBGColor
self.newsView.layer.shadowColor = UIColor.black.cgColor
self.shadowView.layer.shadowColor = UIColor.clear.cgColor
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = self.transformEndedConcat
self.shiningView.layer.transform = self.transformEndedConcat
self.baseLayerView.layer.transform = CATransform3DConcat(CATransform3DMakeScale(normalScale, normalScale, 1), CATransform3DMakeTranslation(0, translationYForView, 0))
self.realBaseView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.newsView.layer.shadowColor = UIColor.clear.cgColor
}, completion: { (stop:Bool) -> Void in
if (self.unfoldWebViewOption != nil) {
self.unfoldWebViewOption!()
}
self.webView.alpha = 1.0
self.loadWebViewRequest()
})
})
}
private func normalLayoutNewsView() {
UIView.animate(withDuration: animateDuration, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.newsView.layer.transform = CATransform3DIdentity
self.shiningView.layer.transform = CATransform3DIdentity
self.shiningImage.transform = CGAffineTransform.identity
self.totalView.transform = CGAffineTransform.identity
self.baseLayerView.layer.transform = CATransform3DIdentity
self.shiningImage.alpha = 1.0
self.baseLayerView.alpha = 0.0
self.realShiningView.alpha = 0.0
self.shiningView.backgroundColor = UIColor.clear
self.newsView.layer.shadowColor = UIColor.clear.cgColor
self.shadowView.layer.shadowColor = UIColor.black.cgColor
},completion: { (stop:Bool) -> Void in
if (self.foldWebViewOption != nil) {
self.foldWebViewOption!()
}
})
}
private func gestureStateChangedSetting(_ targetAngle:CGFloat) {
if targetAngle / CGFloat(M_PI) >= 0.5 {
upperScreenShot.alpha = 1.0
shiningImage.alpha = 0
realShiningView.alpha = 0.5
shiningView.backgroundColor = UIColor.white
realShiningView.backgroundColor = realShiningBGColor
newsView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowColor = UIColor.clear.cgColor
}else {
upperScreenShot.alpha = 0.0
shiningImage.alpha = 1
realShiningView.alpha = 0.0
shiningView.backgroundColor = UIColor.clear
newsView.layer.shadowColor = UIColor.clear.cgColor
shadowView.layer.shadowColor = UIColor.black.cgColor
}
}
}
extension BigNewsDetailCell:UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panWebView && otherGestureRecognizer == webView.scrollView.panGestureRecognizer {
if (webView.scrollView.contentOffset.y <= 0 && webView.scrollView.panGestureRecognizer.velocity(in: self).y >= 0) || webView.scrollView.panGestureRecognizer.location(in: self).y <= 100 {
return true
}else {
return false
}
} else {
return false
}
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panNewsView {
if (panNewsView.velocity(in: self).y >= 0) || fabs(panNewsView.velocity(in: self).x) >= fabs(panNewsView.velocity(in: self).y) {
return false
}else {
return true
}
}else {
return true
}
}
}
| mit |
tomaszbak/uitestcollectionviewerror | CollectionViewUITests/AppDelegate.swift | 1 | 2159 | //
// AppDelegate.swift
// CollectionViewUITests
//
// Created by Tomasz Bąk on 12.11.2015.
// Copyright © 2015 Tomasz Bąk. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
ScoutHarris/WordPress-iOS | WordPressShared/WordPressShared/Languages.swift | 2 | 7253 | import Foundation
import NSObject_SafeExpectations
/// This helper class allows us to map WordPress.com LanguageID's into human readable language strings.
///
public class WordPressComLanguageDatabase: NSObject {
// MARK: - Public Properties
/// Languages considered 'popular'
///
public let popular: [Language]
/// Every supported language
///
public let all: [Language]
/// Returns both, Popular and All languages, grouped
///
public let grouped: [[Language]]
// MARK: - Public Methods
/// Designated Initializer: will load the languages contained within the `Languages.json` file.
///
public override init() {
// Parse the json file
let path = Bundle(for: WordPressComLanguageDatabase.self).path(forResource: filename, ofType: "json")
let raw = try! Data(contentsOf: URL(fileURLWithPath: path!))
let parsed = try! JSONSerialization.jsonObject(with: raw, options: [.mutableContainers, .mutableLeaves]) as? NSDictionary
// Parse All + Popular: All doesn't contain Popular. Otherwise the json would have dupe data. Right?
let parsedAll = Language.fromArray(parsed!.array(forKey: Keys.all) as! [NSDictionary])
let parsedPopular = Language.fromArray(parsed!.array(forKey: Keys.popular) as! [NSDictionary])
let merged = parsedAll + parsedPopular
// Done!
popular = parsedPopular
all = merged.sorted { $0.name < $1.name }
grouped = [popular] + [all]
}
/// Returns the Human Readable name for a given Language Identifier
///
/// - Parameter languageId: The Identifier of the language.
///
/// - Returns: A string containing the language name, or an empty string, in case it wasn't found.
///
public func nameForLanguageWithId(_ languageId: Int) -> String {
return find(id: languageId)?.name ?? ""
}
/// Returns the Language with a given Language Identifier
///
/// - Parameter id: The Identifier of the language.
///
/// - Returns: The language with the matching Identifier, or nil, in case it wasn't found.
///
public func find(id: Int) -> Language? {
return all.first(where: { $0.id == id })
}
/// Returns the current device language as the corresponding WordPress.com language ID.
/// If the language is not supported, it returns 1 (English).
///
/// This is a wrapper for Objective-C, Swift code should use deviceLanguage directly.
///
@objc(deviceLanguageId)
public func deviceLanguageIdNumber() -> NSNumber {
return NSNumber(value: deviceLanguage.id)
}
/// Returns the slug string for the current device language.
/// If the language is not supported, it returns "en" (English).
///
/// This is a wrapper for Objective-C, Swift code should use deviceLanguage directly.
///
@objc(deviceLanguageSlug)
public func deviceLanguageSlugString() -> String {
return deviceLanguage.slug
}
/// Returns the current device language as the corresponding WordPress.com language.
/// If the language is not supported, it returns English.
///
public var deviceLanguage: Language {
let variants = LanguageTagVariants(string: deviceLanguageCode)
for variant in variants {
if let match = self.languageWithSlug(variant) {
return match
}
}
return languageWithSlug("en")!
}
/// Searches for a WordPress.com language that matches a language tag.
///
fileprivate func languageWithSlug(_ slug: String) -> Language? {
let search = languageCodeReplacements[slug] ?? slug
// Use lazy evaluation so we stop filtering as soon as we got the first match
return all.lazy.filter({ $0.slug == search }).first
}
/// Overrides the device language. For testing purposes only.
///
func _overrideDeviceLanguageCode(_ code: String) {
deviceLanguageCode = code.lowercased()
}
// MARK: - Public Nested Classes
/// Represents a Language supported by WordPress.com
///
public class Language: Equatable {
/// Language Unique Identifier
///
public let id: Int
/// Human readable Language name
///
public let name: String
/// Language's Slug String
///
public let slug: String
/// Localized description for the current language
///
public var description: String {
return (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.identifier, value: slug) ?? name
}
/// Designated initializer. Will fail if any of the required properties is missing
///
init?(dict: NSDictionary) {
guard let unwrappedId = dict.number(forKey: Keys.identifier)?.intValue,
let unwrappedSlug = dict.string(forKey: Keys.slug),
let unwrappedName = dict.string(forKey: Keys.name) else {
id = Int.min
name = String()
slug = String()
return nil
}
id = unwrappedId
name = unwrappedName
slug = unwrappedSlug
}
/// Given an array of raw languages, will return a parsed array.
///
public static func fromArray(_ array: [NSDictionary]) -> [Language] {
return array.flatMap {
return Language(dict: $0)
}
}
public static func == (lhs: Language, rhs: Language) -> Bool {
return lhs.id == rhs.id
}
}
// MARK: - Private Variables
/// The device's current preferred language, or English if there's no preferred language.
///
fileprivate lazy var deviceLanguageCode: String = {
return NSLocale.preferredLanguages.first?.lowercased() ?? "en"
}()
// MARK: - Private Constants
fileprivate let filename = "Languages"
// (@koke 2016-04-29) I'm not sure how correct this mapping is, but it matches
// what we do for the app translations, so they will at least be consistent
fileprivate let languageCodeReplacements: [String: String] = [
"zh-hans": "zh-cn",
"zh-hant": "zh-tw"
]
// MARK: - Private Nested Structures
/// Keys used to parse the raw languages.
///
fileprivate struct Keys {
static let popular = "popular"
static let all = "all"
static let identifier = "i"
static let slug = "s"
static let name = "n"
}
}
/// Provides a sequence of language tags from the specified string, from more to less specific
/// For instance, "zh-Hans-HK" will yield `["zh-Hans-HK", "zh-Hans", "zh"]`
///
private struct LanguageTagVariants: Sequence {
let string: String
func makeIterator() -> AnyIterator<String> {
var components = string.components(separatedBy: "-")
return AnyIterator {
guard !components.isEmpty else {
return nil
}
let current = components.joined(separator: "-")
components.removeLast()
return current
}
}
}
| gpl-2.0 |
domenicosolazzo/practice-swift | Autolayout/Orientations/Orientations/AppDelegate.swift | 1 | 2178 | //
// AppDelegate.swift
// Orientations
//
// Created by Domenico on 18.04.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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:.
}
}
| mit |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/CoreStore/CoreStore/Migrating/DataStack+Migration.swift | 2 | 30502 | //
// DataStack+Migration.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - DataStack
public extension DataStack {
/**
Asynchronously adds an in-memory store to the stack.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result.
*/
public func addInMemoryStore(configuration configuration: String? = nil, completion: (PersistentStoreResult) -> Void) {
self.coordinator.performAsynchronously {
do {
let store = try self.coordinator.addPersistentStoreWithType(
NSInMemoryStoreType,
configuration: configuration,
URL: nil,
options: nil
)
self.updateMetadataForPersistentStore(store)
GCDQueue.Main.async {
completion(PersistentStoreResult(store))
}
}
catch {
let storeError = error as NSError
CoreStore.handleError(
storeError,
"Failed to add in-memory \(typeName(NSPersistentStore)) to the stack."
)
GCDQueue.Main.async {
completion(PersistentStoreResult(storeError))
}
}
}
}
/**
Asynchronously adds to the stack an SQLite store from the given SQLite file name. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.)
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS). A new SQLite file will be created if it does not exist. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileName` explicitly for each of them.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/
public func addSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
return try self.addSQLiteStore(
fileURL: defaultDirectory.URLByAppendingPathComponent(
fileName,
isDirectory: false
),
configuration: configuration,
mappingModelBundles: mappingModelBundles,
resetStoreOnModelMismatch: resetStoreOnModelMismatch,
completion: completion
)
}
/**
Asynchronously adds to the stack an SQLite store from the given SQLite file URL. Note that using `addSQLiteStore(...)` instead of `addSQLiteStoreAndWait(...)` implies that the migrations are allowed and expected (thus the asynchronous `completion`.)
- parameter fileURL: the local file URL for the SQLite persistent store. A new SQLite file will be created if it does not exist. If not specified, defaults to a file URL pointing to a "<Application name>.sqlite" file in the "Application Support" directory (or the "Caches" directory on tvOS). Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil`, the "Default" configuration. Note that if you have multiple configurations, you will need to specify a different `fileURL` explicitly for each of them.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
- parameter resetStoreOnModelMismatch: Set to true to delete the store on model mismatch; or set to false to report failure instead. Typically should only be set to true when debugging, or if the persistent store can be recreated easily. If not specified, defaults to false.
- parameter completion: the closure to be executed on the main queue when the process completes, either due to success or failure. The closure's `PersistentStoreResult` argument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a `.Failure` result if an error occurs asynchronously.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/
public func addSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = NSBundle.allBundles(), resetStoreOnModelMismatch: Bool = false, completion: (PersistentStoreResult) -> Void) throws -> NSProgress? {
CoreStore.assert(
fileURL.fileURL,
"The specified file URL for the SQLite store is invalid: \"\(fileURL)\""
)
let coordinator = self.coordinator;
if let store = coordinator.persistentStoreForURL(fileURL) {
guard store.type == NSSQLiteStoreType
&& store.configurationName == (configuration ?? Into.defaultConfigurationName) else {
let error = NSError(coreStoreErrorCode: .DifferentPersistentStoreExistsAtURL)
CoreStore.handleError(
error,
"Failed to add SQLite \(typeName(NSPersistentStore)) at \"\(fileURL)\" because a different \(typeName(NSPersistentStore)) at that URL already exists."
)
throw error
}
GCDQueue.Main.async {
completion(PersistentStoreResult(store))
}
return nil
}
let fileManager = NSFileManager.defaultManager()
_ = try? fileManager.createDirectoryAtURL(
fileURL.URLByDeletingLastPathComponent!,
withIntermediateDirectories: true,
attributes: nil
)
do {
let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(
NSSQLiteStoreType,
URL: fileURL,
options: self.optionsForSQLiteStore()
)
return self.upgradeSQLiteStoreIfNeeded(
fileURL: fileURL,
metadata: metadata,
configuration: configuration,
mappingModelBundles: mappingModelBundles,
completion: { (result) -> Void in
if case .Failure(let error) = result {
if resetStoreOnModelMismatch && error.isCoreDataMigrationError {
fileManager.removeSQLiteStoreAtURL(fileURL)
do {
let store = try self.addSQLiteStoreAndWait(
fileURL: fileURL,
configuration: configuration,
resetStoreOnModelMismatch: false
)
GCDQueue.Main.async {
completion(PersistentStoreResult(store))
}
}
catch {
completion(PersistentStoreResult(error as NSError))
}
return
}
completion(PersistentStoreResult(error))
return
}
do {
let store = try self.addSQLiteStoreAndWait(
fileURL: fileURL,
configuration: configuration,
resetStoreOnModelMismatch: false
)
completion(PersistentStoreResult(store))
}
catch {
completion(PersistentStoreResult(error as NSError))
}
}
)
}
catch let error as NSError
where error.code == NSFileReadNoSuchFileError && error.domain == NSCocoaErrorDomain {
let store = try self.addSQLiteStoreAndWait(
fileURL: fileURL,
configuration: configuration,
resetStoreOnModelMismatch: false
)
GCDQueue.Main.async {
completion(PersistentStoreResult(store))
}
return nil
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to load SQLite \(typeName(NSPersistentStore)) metadata."
)
throw error
}
}
/**
Migrates an SQLite store with the specified filename to the `DataStack`'s managed object model version WITHOUT adding the migrated store to the data stack.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/
public func upgradeSQLiteStoreIfNeeded(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
return try self.upgradeSQLiteStoreIfNeeded(
fileURL: defaultDirectory.URLByAppendingPathComponent(
fileName,
isDirectory: false
),
configuration: configuration,
mappingModelBundles: mappingModelBundles,
completion: completion
)
}
/**
Migrates an SQLite store at the specified file URL and configuration name to the `DataStack`'s managed object model version. This method does NOT add the migrated store to the data stack.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- parameter sourceBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.mainBundle()`.
- returns: an `NSProgress` instance if a migration has started, or `nil` is no migrations are required
*/
public func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil, completion: (MigrationResult) -> Void) throws -> NSProgress? {
let metadata: [String: AnyObject]
do {
metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(
NSSQLiteStoreType,
URL: fileURL,
options: self.optionsForSQLiteStore()
)
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to load SQLite \(typeName(NSPersistentStore)) metadata."
)
throw error
}
return self.upgradeSQLiteStoreIfNeeded(
fileURL: fileURL,
metadata: metadata,
configuration: configuration,
mappingModelBundles: mappingModelBundles,
completion: completion
)
}
/**
Checks for the required migrations needed for the store with the specified filename and configuration to be migrated to the `DataStack`'s managed object model version. This method throws an error if the store does not exist, if inspection of the store failed, or no mapping model was found/inferred.
- parameter fileName: the local filename for the SQLite persistent store in the "Application Support" directory (or the "Caches" directory on tvOS).
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
:return: an array of `MigrationType`s indicating the chain of migrations required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed.
*/
@warn_unused_result
public func requiredMigrationsForSQLiteStore(fileName fileName: String, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
return try requiredMigrationsForSQLiteStore(
fileURL: defaultDirectory.URLByAppendingPathComponent(
fileName,
isDirectory: false
),
configuration: configuration,
mappingModelBundles: mappingModelBundles
)
}
/**
Checks if the store at the specified file URL and configuration needs to be migrated to the `DataStack`'s managed object model version.
- parameter fileURL: the local file URL for the SQLite persistent store.
- parameter configuration: an optional configuration name from the model file. If not specified, defaults to `nil` which indicates the "Default" configuration.
- parameter mappingModelBundles: an optional array of bundles to search mapping model files from. If not set, defaults to the `NSBundle.allBundles()`.
:return: a `MigrationType` indicating the type of migration required for the store; or `nil` if either inspection of the store failed, or no mapping model was found/inferred. `MigrationType` acts as a `Bool` and evaluates to `false` if no migration is required, and `true` if either a lightweight or custom migration is needed.
*/
@warn_unused_result
public func requiredMigrationsForSQLiteStore(fileURL fileURL: NSURL = defaultSQLiteStoreURL, configuration: String? = nil, mappingModelBundles: [NSBundle] = NSBundle.allBundles() as [NSBundle]) throws -> [MigrationType] {
let metadata: [String : AnyObject]
do {
metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(
NSSQLiteStoreType,
URL: fileURL,
options: self.optionsForSQLiteStore()
)
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to load SQLite \(typeName(NSPersistentStore)) metadata."
)
throw error
}
guard let migrationSteps = self.computeMigrationFromStoreMetadata(metadata, configuration: configuration, mappingModelBundles: mappingModelBundles) else {
let error = NSError(coreStoreErrorCode: .MappingModelNotFound)
CoreStore.handleError(
error,
"Failed to find migration steps from the store at URL \"\(fileURL)\" to version model \"\(self.modelVersion)\"."
)
throw error
}
return migrationSteps.map { $0.migrationType }
}
// MARK: Private
private func upgradeSQLiteStoreIfNeeded(fileURL fileURL: NSURL, metadata: [String: AnyObject], configuration: String?, mappingModelBundles: [NSBundle]?, completion: (MigrationResult) -> Void) -> NSProgress? {
guard let migrationSteps = self.computeMigrationFromStoreMetadata(metadata, configuration: configuration, mappingModelBundles: mappingModelBundles) else {
CoreStore.handleError(
NSError(coreStoreErrorCode: .MappingModelNotFound),
"Failed to find migration steps from the store at URL \"\(fileURL)\" to version model \"\(model)\"."
)
GCDQueue.Main.async {
completion(MigrationResult(.MappingModelNotFound))
}
return nil
}
let numberOfMigrations: Int64 = Int64(migrationSteps.count)
if numberOfMigrations == 0 {
GCDQueue.Main.async {
completion(MigrationResult([]))
return
}
return nil
}
let migrationTypes = migrationSteps.map { $0.migrationType }
var migrationResult: MigrationResult?
var operations = [NSOperation]()
var cancelled = false
let progress = NSProgress(parent: nil, userInfo: nil)
progress.totalUnitCount = numberOfMigrations
// todo nsprogress crashing sometimes
for (sourceModel, destinationModel, mappingModel, _) in migrationSteps {
progress.becomeCurrentWithPendingUnitCount(1)
let childProgress = NSProgress(parent: progress, userInfo: nil)
childProgress.totalUnitCount = 100
operations.append(
NSBlockOperation { [weak self] in
guard let strongSelf = self where !cancelled else {
return
}
autoreleasepool {
do {
try strongSelf.startMigrationForSQLiteStore(
fileURL: fileURL,
sourceModel: sourceModel,
destinationModel: destinationModel,
mappingModel: mappingModel,
progress: childProgress
)
}
catch {
migrationResult = MigrationResult(error as NSError)
cancelled = true
}
}
GCDQueue.Main.async {
withExtendedLifetime(childProgress) { (_: NSProgress) -> Void in }
return
}
}
)
progress.resignCurrent()
}
let migrationOperation = NSBlockOperation()
#if USE_FRAMEWORKS
migrationOperation.qualityOfService = .Utility
#else
if #available(iOS 8.0, *) {
migrationOperation.qualityOfService = .Utility
}
#endif
operations.forEach { migrationOperation.addDependency($0) }
migrationOperation.addExecutionBlock { () -> Void in
GCDQueue.Main.async {
progress.setProgressHandler(nil)
completion(migrationResult ?? MigrationResult(migrationTypes))
return
}
}
operations.append(migrationOperation)
self.migrationQueue.addOperations(operations, waitUntilFinished: false)
return progress
}
private func computeMigrationFromStoreMetadata(metadata: [String: AnyObject], configuration: String? = nil, mappingModelBundles: [NSBundle]? = nil) -> [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]? {
let model = self.model
if model.isConfiguration(configuration, compatibleWithStoreMetadata: metadata) {
return []
}
guard let initialModel = model[metadata],
var currentVersion = initialModel.currentModelVersion else {
return nil
}
let migrationChain: MigrationChain = self.migrationChain.empty
? [currentVersion: model.currentModelVersion!]
: self.migrationChain
var migrationSteps = [(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, migrationType: MigrationType)]()
while let nextVersion = migrationChain.nextVersionFrom(currentVersion),
let sourceModel = model[currentVersion],
let destinationModel = model[nextVersion] where sourceModel != model {
if let mappingModel = NSMappingModel(
fromBundles: mappingModelBundles,
forSourceModel: sourceModel,
destinationModel: destinationModel) {
migrationSteps.append(
(
sourceModel: sourceModel,
destinationModel: destinationModel,
mappingModel: mappingModel,
migrationType: .Heavyweight(
sourceVersion: currentVersion,
destinationVersion: nextVersion
)
)
)
}
else {
do {
let mappingModel = try NSMappingModel.inferredMappingModelForSourceModel(
sourceModel,
destinationModel: destinationModel
)
migrationSteps.append(
(
sourceModel: sourceModel,
destinationModel: destinationModel,
mappingModel: mappingModel,
migrationType: .Lightweight(
sourceVersion: currentVersion,
destinationVersion: nextVersion
)
)
)
}
catch {
return nil
}
}
currentVersion = nextVersion
}
if migrationSteps.last?.destinationModel == model {
return migrationSteps
}
return nil
}
private func startMigrationForSQLiteStore(fileURL fileURL: NSURL, sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel, mappingModel: NSMappingModel, progress: NSProgress) throws {
autoreleasepool {
let journalUpdatingCoordinator = NSPersistentStoreCoordinator(managedObjectModel: sourceModel)
let store = try! journalUpdatingCoordinator.addPersistentStoreWithType(
NSSQLiteStoreType,
configuration: nil,
URL: fileURL,
options: [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
)
try! journalUpdatingCoordinator.removePersistentStore(store)
}
let migrationManager = MigrationManager(
sourceModel: sourceModel,
destinationModel: destinationModel,
progress: progress
)
let temporaryDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).URLByAppendingPathComponent(NSProcessInfo().globallyUniqueString)
let fileManager = NSFileManager.defaultManager()
try! fileManager.createDirectoryAtURL(
temporaryDirectoryURL,
withIntermediateDirectories: true,
attributes: nil
)
let temporaryFileURL = temporaryDirectoryURL.URLByAppendingPathComponent(fileURL.lastPathComponent!, isDirectory: false)
do {
try migrationManager.migrateStoreFromURL(
fileURL,
type: NSSQLiteStoreType,
options: nil,
withMappingModel: mappingModel,
toDestinationURL: temporaryFileURL,
destinationType: NSSQLiteStoreType,
destinationOptions: nil
)
}
catch {
do {
try fileManager.removeItemAtURL(temporaryDirectoryURL)
}
catch _ { }
let sourceVersion = migrationManager.sourceModel.currentModelVersion ?? "???"
let destinationVersion = migrationManager.destinationModel.currentModelVersion ?? "???"
CoreStore.handleError(
error as NSError,
"Failed to migrate from version model \"\(sourceVersion)\" to version model \"\(destinationVersion)\"."
)
throw error
}
do {
try fileManager.replaceItemAtURL(
fileURL,
withItemAtURL: temporaryFileURL,
backupItemName: nil,
options: [],
resultingItemURL: nil
)
progress.completedUnitCount = progress.totalUnitCount
do {
try fileManager.removeItemAtPath(fileURL.path! + "-shm")
}
catch _ { }
}
catch {
do {
try fileManager.removeItemAtURL(temporaryDirectoryURL)
}
catch _ { }
let sourceVersion = migrationManager.sourceModel.currentModelVersion ?? "???"
let destinationVersion = migrationManager.destinationModel.currentModelVersion ?? "???"
CoreStore.handleError(
error as NSError,
"Failed to save store after migrating from version model \"\(sourceVersion)\" to version model \"\(destinationVersion)\"."
)
throw error
}
}
}
| apache-2.0 |
xc1129/helloios | HelloIOS/HelloIOSTests/HelloIOSTests.swift | 1 | 898 | //
// HelloIOSTests.swift
// HelloIOSTests
//
// Created by 许陈 on 15/2/9.
// Copyright (c) 2015年 Spirit_xc. All rights reserved.
//
import UIKit
import XCTest
class HelloIOSTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
duliodenis/cs193p-Winter-2015 | assignment-1-calculator/Calculator/Calculator/ViewController.swift | 1 | 2852 | //
// ViewController.swift
// Calculator
//
// Created by Dulio Denis on 1/26/15.
// Copyright (c) 2015 ddApps. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
@IBOutlet weak var history: UILabel!
var operandStack = Array<Double>()
var operationStack = Array<Double>()
var userIsInTheMiddleOfTypingANumber = false
var decimalUsed = false
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
println("digit = \(digit)")
if userIsInTheMiddleOfTypingANumber {
if digit == "." && decimalUsed == true {
return
} else if digit == "." && decimalUsed == false {
decimalUsed = true
}
display.text = display.text! + digit
} else {
userIsInTheMiddleOfTypingANumber = true
if digit == "." {
decimalUsed = true
display.text = "0."
} else {
display.text = digit
}
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case "×": performOperation { $0 * $1 }
case "÷": performOperation { $1 / $0 }
case "+": performOperation { $0 + $1 }
case "−": performOperation { $1 - $0 }
case "√": performOperation { sqrt($0) }
case "sin": performOperation { sin($0) }
case "cos": performOperation { cos($0) }
case "∏": displayValue = M_PI
default: break
}
}
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
func performOperation(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
decimalUsed = false
operandStack.append(displayValue)
println("operandStack = \(operandStack)")
history.text = ""
for element in operandStack {
history.text = history.text! + "\(element), "
}
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
decimalUsed = false
}
}
}
| mit |
peigen/iLife | iLife/SecondVC.swift | 1 | 4385 | //
// SecondVC.swift
// CleanUp
//
// Created by peigen on 14-6-21.
// Copyright (c) 2014 Peigen.info. All rights reserved.
//
import Foundation
import UIKit
class SecondVC: BaseVC {
// UIView
@IBOutlet var usedToScrollView: UIScrollView
@IBOutlet var appScrollView: UIScrollView
@IBOutlet var callScrollView: UIScrollView
@IBOutlet var unkownScrollView: UIScrollView
// UIViewController
var appImges : Array<String> = ["com_sina_weibo_icon.png","com_tencent_mm_icon.png","com_eg_android_AlipayGphone_icon.png","com_android_chrome_icon.png","com_youku_phone_icon.png"]
var iphoneCalls : Array<String> = ["IMG_0883.JPG"]
override func viewDidLoad() {
super.viewDidLoad()
var background : UIImage = UIImage(named:"bookshelf.png")
UIGraphicsBeginImageContext(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-64));
background.drawInRect(CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64))
background = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// background.resizableImageWithCapInsets(background.capInsets, resizingMode: UIImageResizingMode.Stretch)
// = CGSize(SCREEN_WIDTH,SCREEN_HEIGHT)
self.view.backgroundColor = UIColor(patternImage: background)
initView()
initButton()
}
func setScrollView(scrollView : UIScrollView, yAxis : CGFloat) {
scrollView.frame = CGRectMake( ORIGINAL_POINT, yAxis, SCREEN_WIDTH, scrollViewHeight)
scrollView.contentSize = CGSize(width: SCREEN_WIDTH*2, height: scrollViewHeight)
// scrollView.backgroundColor = backgroundColor
scrollView.pagingEnabled = false
scrollView.bounces = true
}
func initView(){
self.view.frame = CGRectMake(ORIGINAL_POINT, ORIGINAL_POINT, SCREEN_WIDTH, SCREEN_HEIGHT)
// 0. used to
var usedToYAxis = space
setScrollView(usedToScrollView, yAxis: usedToYAxis)
// 1. app view
var appYAxis = usedToYAxis + scrollViewHeight
setScrollView(appScrollView, yAxis: appYAxis)
// 2. call view
var callYAxis = appYAxis + scrollViewHeight
setScrollView(callScrollView, yAxis: callYAxis)
// 3. unkown view
var unkownYAxis = callYAxis + scrollViewHeight
setScrollView(unkownScrollView, yAxis: unkownYAxis)
}
func initButton(){
var x = 30
for i in 0..4{
// title
initLabel(usedToScrollView, text: "App Manage", align: NSTextAlignment.Center)
// more
// button
var button = UIButton.buttonWithType(.Custom) as UIButton
button.frame = CGRect(x: x ,y: 40,width: 57,height: 57)
button.setImage(UIImage(named:appImges[i]),forState: .Normal)
button.addTarget(self, action: "onAction:", forControlEvents: .TouchUpInside)
// button.tag = i
addScrollView(button)
x += 57+10;
}
}
func initButton(i:Int,x:Int) {
//
// initLabel(usedToScrollView, text: <#String#>, align: <#NSTextAlignment#>)
}
func initLabel(view : UIView , text : String ,align : NSTextAlignment){
// title
var titleLabel : UILabel = UILabel(frame:CGRect(origin: CGPointMake(0.0, 0.0), size: CGSizeMake(150,20)))
titleLabel.textAlignment = align
titleLabel.text = text
titleLabel.textColor = UIColor.redColor()
view.addSubview(titleLabel)
}
func addScrollView(button : UIButton){
usedToScrollView.addSubview(button)
// appScrollView.addSubview(button)
// callScrollView.addSubview(button)
// unkownScrollView.addSubview(button)
}
func onAction(btn:UIButton)
{
if(btn.tag == 0)
{
openWeiboAction(btn)
}
if(btn.tag == 1)
{
openWeixinAction(btn)
}
if(btn.tag == 2)
{
openAlipayAction(btn)
}
if(btn.tag == 3)
{
openChromeAction(btn)
}
if(btn.tag == 4)
{
openYoukuAction(btn)
}
}
func openWeiboAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "weibo://"))
}
func openWeixinAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "weixin://"))
}
func openAlipayAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "alipays://"))
}
func openChromeAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "googlechrome://"))
}
func openYoukuAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "YouKu://"))
}
func callYayaAction(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "tel:18629091151"))
}
} | gpl-3.0 |
benbahrenburg/KeyStorage | KeyStorage/Classes/KeyChainInfo.swift | 1 | 5586 | //
// KeyStorage - Simplifying securely saving key information
// KeyChainInfo.swift
//
// Created by Ben Bahrenburg on 3/23/16.
// Copyright © 2019 bencoding.com. All rights reserved.
//
import Foundation
import Security
/**
Contains information related to the Keychain
*/
public struct KeyChainInfo {
/**
Struct returned from getAccessGroupInfo with information related to the Keychain Group.
*/
public struct AccessGroupInfo {
/// App ID Prefix
public var prefix: String
/// Keycahin Group
public var keyChainGroup: String
/// Raw kSecAttrAccessGroup value returned from Keychain
public var rawValue: String
}
/**
Enum to used determine error details
*/
public enum errorDetail: Error {
/// No password provided or available
case noPassword
/// Incorrect data provided as part of the password return
case unexpectedPasswordData
/// Incorrect data provided for a non password Keychain item
case unexpectedItemData
/// Unknown error returned by keychain
case unhandledError(status: OSStatus)
}
/**
Enum to used map the accessibility of keychain items.
For example, if whenUnlockedThisDeviceOnly the item data can
only be accessed once the device has been unlocked after a restart.
*/
public enum accessibleOption: RawRepresentable {
case whenUnlocked,
afterFirstUnlock,
whenUnlockedThisDeviceOnly,
afterFirstUnlockThisDeviceOnly,
whenPasscodeSetThisDeviceOnly
public init?(rawValue: String) {
switch rawValue {
/**
Item data can only be accessed
while the device is unlocked. This is recommended for items that only
need be accesible while the application is in the foreground. Items
with this attribute will migrate to a new device when using encrypted
backups.
*/
case String(kSecAttrAccessibleWhenUnlocked):
self = .whenUnlocked
/**
Item data can only be
accessed once the device has been unlocked after a restart. This is
recommended for items that need to be accesible by background
applications. Items with this attribute will migrate to a new device
when using encrypted backups.
*/
case String(kSecAttrAccessibleAfterFirstUnlock):
self = .afterFirstUnlock
/**
Item data can only
be accessed while the device is unlocked. This is recommended for items
that only need be accesible while the application is in the foreground.
Items with this attribute will never migrate to a new device, so after
a backup is restored to a new device, these items will be missing.
*/
case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly):
self = .whenUnlockedThisDeviceOnly
/**
Item data can
only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device these items will
be missing.
*/
case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly):
self = .afterFirstUnlockThisDeviceOnly
/**
Item data can
only be accessed while the device is unlocked. This class is only
available if a passcode is set on the device. This is recommended for
items that only need to be accessible while the application is in the
foreground. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device, these items
will be missing. No items can be stored in this class on devices
without a passcode. Disabling the device passcode will cause all
items in this class to be deleted.
*/
case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly):
self = .whenPasscodeSetThisDeviceOnly
default:
self = .afterFirstUnlockThisDeviceOnly
}
}
/// Convert Enum to String Const
public var rawValue: String {
switch self {
case .whenUnlocked:
return String(kSecAttrAccessibleWhenUnlocked)
case .afterFirstUnlock:
return String(kSecAttrAccessibleAfterFirstUnlock)
case .whenPasscodeSetThisDeviceOnly:
return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
case .whenUnlockedThisDeviceOnly:
return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .afterFirstUnlockThisDeviceOnly:
return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
}
}
}
}
| mit |
roambotics/swift | test/SourceKit/CodeComplete/complete_from_system.swift | 21 | 503 | struct MyCollection : Collection {
var startIndex: Int { 0 }
var endIndex: Int { 0 }
func index(after i: Int) -> Int { i + 1 }
subscript(position: Int) -> Int { 0 }
}
func test(col: MyCollection) {
col.
}
// RUN: %sourcekitd-test -req=complete -pos=9:7 %s -- %s -module-name TestMod | %FileCheck %s
// CHECK: key.name: "makeIterator()",
// CHECK-NOT: },
// CHECK: key.is_system: 1
// CHECK: },
// CHECK: key.name: "startIndex",
// CHECK-NOT: },
// CHECK-NOT: key.is_system: 1
// CHECK: },
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.