repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iossocket/VIPER-Douban
|
VIPER-Douban/EmbeddedSectionController.swift
|
1
|
1421
|
//
// EmbeddedSectionController.swift
// VIPER-Douban
//
// Created by XueliangZhu on 2/20/17.
// Copyright © 2017 ThoughtWorks. All rights reserved.
//
import UIKit
import IGListKit
import Kingfisher
class EmbeddedSectionController: IGListSectionController, IGListSectionType {
var data: DisplayMovie?
override init() {
super.init()
self.inset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
}
func numberOfItems() -> Int {
return 1
}
func sizeForItem(at index: Int) -> CGSize {
let height = collectionContext?.containerSize.height ?? 0
return CGSize(width: 110, height: height)
}
func cellForItem(at index: Int) -> UICollectionViewCell {
let cell = collectionContext!.dequeueReusableCell(of: MovieItemCell.self, for: self, at: index) as! MovieItemCell
guard let movie = data else {
return cell
}
cell.imageView.kf.setImage(with: URL(string: movie.imageUrl))
cell.imageView.heroID = movie.imageUrl
cell.titleLabel.text = movie.title
cell.configStars(star: movie.star)
return cell
}
func didUpdate(to object: Any) {
data = object as? DisplayMovie
}
func didSelectItem(at index: Int) {
SuggestionRouter().showDetailViewController(from: viewController, by: data?.imageUrl, id: data?.id)
}
}
|
mit
|
2b0dec3048d96e7458e4629d8833d8eb
| 27.4 | 121 | 0.641549 | 4.396285 | false | false | false | false |
SwiftBond/Bond
|
Sources/Bond/AppKit/NSGestureRecognizer.swift
|
2
|
4969
|
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Tony Arnold (@tonyarnold)
//
// 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 os(macOS)
import AppKit
import ReactiveKit
extension NSGestureRecognizer: BindingExecutionContextProvider {
public var bindingExecutionContext: ExecutionContext { return .immediateOnMain }
}
public extension ReactiveExtensions where Base: NSGestureRecognizer {
public var isEnabled: Bond<Bool> {
return bond { $0.isEnabled = $1 }
}
}
public extension ReactiveExtensions where Base: NSView {
public func addGestureRecognizer<T: NSGestureRecognizer>(_ gestureRecognizer: T) -> SafeSignal<T> {
let base = self.base
return Signal { [weak base] observer in
guard let base = base else {
observer.completed()
return NonDisposable.instance
}
let target = BNDGestureTarget(view: base, gestureRecognizer: gestureRecognizer) { recog in
// swiftlint:disable:next force_cast
observer.next(recog as! T)
}
return BlockDisposable {
target.unregister()
}
}
.take(until: base.deallocated)
}
public func clickGesture(numberOfClicks: Int = 1, numberOfTouches: Int = 1) -> SafeSignal<NSClickGestureRecognizer> {
let gesture = NSClickGestureRecognizer()
gesture.numberOfClicksRequired = numberOfClicks
if #available(macOS 10.12.2, *) {
gesture.numberOfTouchesRequired = numberOfTouches
}
return addGestureRecognizer(gesture)
}
public func magnificationGesture(magnification: CGFloat = 1.0, numberOfTouches: Int = 1) -> SafeSignal<NSMagnificationGestureRecognizer> {
let gesture = NSMagnificationGestureRecognizer()
gesture.magnification = magnification
return addGestureRecognizer(gesture)
}
public func panGesture(buttonMask: Int = 0x01, numberOfTouches: Int = 1) -> SafeSignal<NSPanGestureRecognizer> {
let gesture = NSPanGestureRecognizer()
gesture.buttonMask = buttonMask
if #available(macOS 10.12.2, *) {
gesture.numberOfTouchesRequired = numberOfTouches
}
return addGestureRecognizer(gesture)
}
public func pressGesture(buttonMask: Int = 0x01, minimumPressDuration: TimeInterval = NSEvent.doubleClickInterval, allowableMovement: CGFloat = 10.0, numberOfTouches: Int = 1) -> SafeSignal<NSPressGestureRecognizer> {
let gesture = NSPressGestureRecognizer()
gesture.buttonMask = buttonMask
gesture.minimumPressDuration = minimumPressDuration
gesture.allowableMovement = allowableMovement
if #available(macOS 10.12.2, *) {
gesture.numberOfTouchesRequired = numberOfTouches
}
return addGestureRecognizer(gesture)
}
public func rotationGesture() -> SafeSignal<NSRotationGestureRecognizer> {
return addGestureRecognizer(NSRotationGestureRecognizer())
}
}
@objc private class BNDGestureTarget: NSObject {
private weak var view: NSView?
private let observer: (NSGestureRecognizer) -> Void
private let gestureRecognizer: NSGestureRecognizer
fileprivate init(view: NSView, gestureRecognizer: NSGestureRecognizer, observer: @escaping (NSGestureRecognizer) -> Void) {
self.view = view
self.gestureRecognizer = gestureRecognizer
self.observer = observer
super.init()
gestureRecognizer.target = self
gestureRecognizer.action = #selector(actionHandler(recogniser:))
view.addGestureRecognizer(gestureRecognizer)
}
@objc private func actionHandler(recogniser: NSGestureRecognizer) {
observer(recogniser)
}
fileprivate func unregister() {
view?.removeGestureRecognizer(gestureRecognizer)
}
deinit {
unregister()
}
}
#endif
|
mit
|
8105b54dde832989815d5580d303a03d
| 35.807407 | 221 | 0.696921 | 4.973974 | false | false | false | false |
ReSwift/ReactiveReSwift
|
Sources/CoreTypes/Action.swift
|
1
|
4332
|
//
// Action.swift
// ReSwift
//
// Created by Benjamin Encz on 12/14/15.
// Copyright © 2015 Benjamin Encz. All rights reserved.
//
import Foundation
/**
This is ReSwift's built in action type, it is the only built in type that conforms to the
`Action` protocol. `StandardAction` can be serialized and can therefore be used with developer
tools that restore state between app launches.
The downside of `StandardAction` is that it carries its payload as an untyped dictionary which does
not play well with Swift's type system.
It is recommended that you define your own types that conform to `Action` - if you want to be able
to serialize your custom action types, you can implement `StandardActionConvertible` which will
make it possible to generate a `StandardAction` from your typed action - the best of both worlds!
*/
public struct StandardAction: Action {
/// A String that identifies the type of this `StandardAction`
public let type: String
/// An untyped, JSON-compatible payload
public let payload: [String: AnyObject]?
/// Indicates whether this action will be deserialized as a typed action or as a standard action
public let isTypedAction: Bool
/**
Initializes this `StandardAction` with a type, a payload and information about whether this is
a typed action or not.
- parameter type: String representation of the Action type
- parameter payload: Payload convertable to JSON
- parameter isTypedAction: Is Action a subclassed type
*/
public init(type: String, payload: [String: AnyObject]? = nil, isTypedAction: Bool = false) {
self.type = type
self.payload = payload
self.isTypedAction = isTypedAction
}
}
// MARK: Coding Extension
private let typeKey = "type"
private let payloadKey = "payload"
private let isTypedActionKey = "isTypedAction"
let reSwiftNull = "ReSwift_Null"
extension StandardAction: Coding {
public init?(dictionary: [String: AnyObject]) {
guard let type = dictionary[typeKey] as? String,
let isTypedAction = dictionary[isTypedActionKey] as? Bool else { return nil }
self.type = type
self.payload = dictionary[payloadKey] as? [String: AnyObject]
self.isTypedAction = isTypedAction
}
public var dictionaryRepresentation: [String: AnyObject] {
let payload: AnyObject = self.payload as AnyObject? ?? reSwiftNull as AnyObject
return [typeKey: type as NSString,
payloadKey: payload,
isTypedActionKey: isTypedAction as NSNumber]
}
}
/// Implement this protocol on your custom `Action` type if you want to make the action
/// serializable.
/// - Note: We are working on a tool to automatically generate the implementation of this protocol
/// for your custom action types.
public protocol StandardActionConvertible: Action {
/**
Within this initializer you need to use the payload from the `StandardAction` to configure the
state of your custom action type.
Example:
```
init(_ standardAction: StandardAction) {
self.twitterUser = decode(standardAction.payload!["twitterUser"]!)
}
```
- Note: If you, as most developers, only use action serialization/deserialization during
development, you can feel free to use the unsafe `!` operator.
*/
init (_ standardAction: StandardAction)
/**
Use the information from your custom action to generate a `StandardAction`. The `type` of the
StandardAction should typically match the type name of your custom action type. You also need
to set `isTypedAction` to `true`. Use the information from your action's properties to
configure the payload of the `StandardAction`.
Example:
```
func toStandardAction() -> StandardAction {
let payload = ["twitterUser": encode(self.twitterUser)]
return StandardAction(type: SearchTwitterScene.SetSelectedTwitterUser.type,
payload: payload, isTypedAction: true)
}
```
*/
func toStandardAction() -> StandardAction
}
/// All actions that want to be able to be dispatched to a store need to conform to this protocol
/// Currently it is just a marker protocol with no requirements.
public protocol Action { }
|
mit
|
0d24e8e85b61d7a6d20650b71f8c9e66
| 36.336207 | 100 | 0.698453 | 4.651987 | false | false | false | false |
cafielo/iOS_BigNerdRanch_5th
|
Chap14_Homepwner_bronze_silver_gold/Homepwner/Item.swift
|
2
|
1472
|
//
// Item.swift
// Homepwner
//
// Created by Joonwon Lee on 7/31/16.
// Copyright © 2016 Joonwon Lee. All rights reserved.
//
import UIKit
class Item: NSObject {
var name: String
var valueInDollars: Int
var serialNumber: String?
let dateCreated: NSDate
let itemKey: String
init(name: String, serialNumber: String?, valueInDollars:Int) {
self.name = name
self.valueInDollars = valueInDollars
self.serialNumber = serialNumber
self.dateCreated = NSDate()
self.itemKey = NSUUID().UUIDString
super.init()
}
convenience init(random: Bool = false) {
if random {
let adjectives = ["Fluffy", "Rusty", "Shiny"]
let nouns = ["Bear", "Spork", "Mac"]
var idx = arc4random_uniform(UInt32(adjectives.count))
let randomAdjective = nouns[Int(idx)]
idx = arc4random_uniform(UInt32(nouns.count))
let randomNoun = nouns[Int(idx)]
let randomName = "\(randomAdjective) \(randomNoun)"
let randomwValue = Int(arc4random_uniform(100))
let randomSerialNumber = NSUUID().UUIDString.componentsSeparatedByString("-").first!
self.init(name: randomName, serialNumber: randomSerialNumber, valueInDollars: randomwValue)
} else {
self.init(name: "", serialNumber: nil, valueInDollars: 0)
}
}
}
|
mit
|
615d26b7e9899c4d9cf8ecc653eda1ac
| 29.645833 | 103 | 0.590755 | 4.417417 | false | false | false | false |
gregomni/swift
|
SwiftCompilerSources/Sources/Optimizer/FunctionPasses/AssumeSingleThreaded.swift
|
3
|
1571
|
//===--- AssumeSingleThreaded.swift - Assume single-threaded execution ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Assume that user code is single-threaded.
//
// Convert all reference counting operations into non-atomic ones.
//
// To get rid of most atomic reference counting operations, the standard
// library should be compiled in this mode as well .
//
// This pass affects only reference counting operations resulting from SIL
// instructions. It wouldn't affect places in the runtime C++ code which
// hard-code calls to retain/release. We could take advantage of the Instruments
// instrumentation stubs to redirect calls from the runtime if it was
// significant, or else just build a single-threaded variant of the runtime.
//
//===----------------------------------------------------------------------===//
import SIL
let assumeSingleThreadedPass = FunctionPass(
name: "sil-assume-single-threaded", { function, context in
for block in function.blocks {
for inst in block.instructions {
guard let rcInst = inst as? RefCountingInst else { continue }
context.setAtomicity(of: rcInst, isAtomic: false)
}
}
}
)
|
apache-2.0
|
a9fb2c4a1e2bc07060b096bffccd0c16
| 38.275 | 80 | 0.65627 | 4.760606 | false | false | false | false |
heshamMassoud/tip-calculator
|
TipCalculatorModel.swift
|
1
|
1107
|
//
// TipCalculatorModel.swift
// TipCalculator
//
// Created by Hesham Massoud on 11/12/15.
// Copyright © 2015 Hesham Massoud. All rights reserved.
//
import Foundation
class TipCalculatorModel {
var total: Double
var taxPercantage: Double
var subTotal: Double {
get {
return total / (taxPercantage + 1)
}
}
init(total: Double, taxPercantage: Double) {
self.total = total
self.taxPercantage = taxPercantage
}
func calcTipWithTipPercantage(tipPercantage: Double) -> (Double, Double) {
let tip = subTotal * tipPercantage
let totalWithTip = tip + total
return (tip, totalWithTip)
}
func returnPossibleTips() -> [Int: (tip: Double, totalWithTip: Double)] {
let possibleTips = [0.15, 0.18, 0.20]
var returnValue = [Int: (tip: Double, totalWithTip: Double)]()
for possibleTip in possibleTips {
let intPercantage = Int(possibleTip * 100)
returnValue[intPercantage] = calcTipWithTipPercantage(possibleTip)
}
return returnValue
}
}
|
mit
|
4401e6fe653cfe6176ff2edd20cfa25a
| 26.65 | 78 | 0.627486 | 3.867133 | false | false | false | false |
jadevance/fuzz-therapy-iOS
|
Fuzz Therapy/UserClass.swift
|
1
|
844
|
//
// UserClass.swift
// Fuzz Therapy
//
// Created by Jade Vance on 8/14/16.
// Copyright © 2016 Jade Vance. All rights reserved.
//
import Foundation
class CurrentUser {
static var sharedInstance = CurrentUser()
var user:User?
}
class User {
var name:String
var uid:String
var location:String
var availability:String
var dogName:String
var dogBreed:String
var dogAge:Int
var email:String
init(name:String, uid:String, location:String, availability:String, dogName:String, dogBreed:String, dogAge:Int, email:String) {
self.name = name
self.uid = uid
self.location = location
self.availability = availability
self.dogName = dogName
self.dogBreed = dogBreed
self.dogAge = dogAge
self.email = email
}
}
|
apache-2.0
|
354f93260a868c0ebc6956cb07e0c700
| 21.210526 | 132 | 0.637011 | 3.939252 | false | false | false | false |
almazrafi/Metatron
|
Sources/Lyrics3/Lyrics3Tag.swift
|
1
|
10133
|
//
// Lyrics3Tag.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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
fileprivate func ~=<T: Equatable> (left: [T], right: [T]) -> Bool {
return (left == right)
}
public class Lyrics3Tag {
// MARK: Type Properties
static let dataMarker: [UInt8] = [76, 89, 82, 73, 67, 83, 66, 69, 71, 73, 78]
static let dataSignatureV1: [UInt8] = [76, 89, 82, 73, 67, 83, 69, 78, 68]
static let dataSignatureV2: [UInt8] = [76, 89, 82, 73, 67, 83, 50, 48, 48]
static let maxSignatureLength: Int = 15
static let maxDataLengthV1: Int = 5100
static let maxDataLengthV2: Int = 1000014
static let minDataLength: Int = 20
// MARK: Instance Properties
public var version: Lyrics3Version
// MARK:
private var fieldKeys: [Lyrics3FieldID: Int]
public private(set) var fieldList: [Lyrics3Field]
// MARK:
public var isEmpty: Bool {
return self.fieldList.isEmpty
}
// MARK: Initializers
private init?(bodyData: [UInt8], version: Lyrics3Version) {
assert(bodyData.starts(with: Lyrics3Tag.dataMarker), "Invalid data")
self.version = version
self.fieldKeys = [:]
self.fieldList = []
var offset = Lyrics3Tag.dataMarker.count
while offset < bodyData.count {
if let field = Lyrics3Field(fromBodyData: bodyData, offset: &offset, version: self.version) {
if let index = self.fieldKeys[field.identifier] {
self.fieldList[index] = field
} else {
self.fieldKeys.updateValue(self.fieldList.count, forKey: field.identifier)
self.fieldList.append(field)
}
} else {
break
}
}
}
// MARK:
public init(version: Lyrics3Version = Lyrics3Version.v2) {
self.version = version
self.fieldKeys = [:]
self.fieldList = []
}
public convenience init?(fromData data: [UInt8]) {
let stream = MemoryStream(data: data)
guard stream.openForReading() else {
return nil
}
var range = Range<UInt64>(0..<UInt64(data.count))
self.init(fromStream: stream, range: &range)
}
public convenience init?(fromStream stream: Stream, range: inout Range<UInt64>) {
assert(stream.isOpen && stream.isReadable && (stream.length >= range.upperBound), "Invalid stream")
guard range.lowerBound < range.upperBound else {
return nil
}
let minDataLength = UInt64(Lyrics3Tag.minDataLength)
let maxDataLength = UInt64(range.count)
guard minDataLength <= maxDataLength else {
return nil
}
guard stream.seek(offset: range.upperBound - UInt64(Lyrics3Tag.maxSignatureLength)) else {
return nil
}
let signature = stream.read(maxLength: Lyrics3Tag.maxSignatureLength)
guard signature.count == Lyrics3Tag.maxSignatureLength else {
return nil
}
switch [UInt8](signature.suffix(Lyrics3Tag.dataSignatureV1.count)) {
case Lyrics3Tag.dataSignatureV1:
let dataLength = min(maxDataLength, UInt64(Lyrics3Tag.maxDataLengthV1))
let dataStart = range.upperBound - dataLength
guard stream.seek(offset: dataStart) else {
return nil
}
let data = stream.read(maxLength: Int(dataLength))
guard data.count == Int(dataLength) else {
return nil
}
let bodyEnd = data.count - Lyrics3Tag.dataSignatureV1.count
guard let bodyStart = data.lastOccurrence(of: Lyrics3Tag.dataMarker) else {
return nil
}
self.init(bodyData: [UInt8](data[bodyStart..<bodyEnd]), version: Lyrics3Version.v1)
range = (dataStart + UInt64(bodyStart))..<range.upperBound
case Lyrics3Tag.dataSignatureV2:
guard let bodyLength = Int(ID3v1Latin1TextEncoding.regular.decode(signature.prefix(6)) ?? "") else {
return nil
}
let dataLength = UInt64(bodyLength + Lyrics3Tag.maxSignatureLength)
guard dataLength <= maxDataLength else {
return nil
}
guard stream.seek(offset: range.upperBound - dataLength) else {
return nil
}
let bodyData = stream.read(maxLength: bodyLength)
guard bodyData.count == bodyLength else {
return nil
}
guard bodyData.starts(with: Lyrics3Tag.dataMarker) else {
return nil
}
self.init(bodyData: bodyData, version: Lyrics3Version.v2)
range = (range.upperBound - dataLength)..<range.upperBound
default:
return nil
}
}
// MARK: Instance Methods
public func toData() -> [UInt8]? {
guard !self.isEmpty else {
return nil
}
var data = Lyrics3Tag.dataMarker
switch self.version {
case Lyrics3Version.v1:
let maxBodyLength = Lyrics3Tag.maxDataLengthV1 - Lyrics3Tag.dataSignatureV1.count
for field in self.fieldList {
if let fieldData = field.toData(version: self.version) {
if fieldData.count <= maxBodyLength - data.count {
data.append(contentsOf: fieldData)
}
}
}
guard data.count > Lyrics3Tag.dataMarker.count else {
return nil
}
data.append(contentsOf: Lyrics3Tag.dataSignatureV1)
case Lyrics3Version.v2:
let maxBodyLength = Lyrics3Tag.maxDataLengthV2 - Lyrics3Tag.maxSignatureLength
if let index = self.fieldKeys[Lyrics3FieldID.ind] {
if let fieldData = self.fieldList[index].toData(version: self.version) {
if fieldData.count <= maxBodyLength - data.count {
data.append(contentsOf: fieldData)
}
}
}
for field in self.fieldList {
if field.identifier != Lyrics3FieldID.ind {
if let fieldData = field.toData(version: self.version) {
if fieldData.count <= maxBodyLength - data.count {
data.append(contentsOf: fieldData)
}
}
}
}
guard data.count > Lyrics3Tag.dataMarker.count else {
return nil
}
data.append(contentsOf: ID3v1Latin1TextEncoding.regular.encode(String(format: "%06d", data.count)))
data.append(contentsOf: Lyrics3Tag.dataSignatureV2)
}
return data
}
@discardableResult
public func appendField(_ identifier: Lyrics3FieldID) -> Lyrics3Field {
if let index = self.fieldKeys[identifier] {
return self.fieldList[index]
} else {
let field = Lyrics3Field(identifier: identifier)
self.fieldKeys.updateValue(self.fieldList.count, forKey: identifier)
self.fieldList.append(field)
return field
}
}
@discardableResult
public func resetField(_ identifier: Lyrics3FieldID) -> Lyrics3Field {
if let index = self.fieldKeys[identifier] {
let field = self.fieldList[index]
field.reset()
return field
} else {
let field = Lyrics3Field(identifier: identifier)
self.fieldKeys.updateValue(self.fieldList.count, forKey: identifier)
self.fieldList.append(field)
return field
}
}
@discardableResult
public func removeField(_ identifier: Lyrics3FieldID) -> Bool {
guard let index = self.fieldKeys.removeValue(forKey: identifier) else {
return false
}
for i in (index + 1)..<self.fieldList.count {
self.fieldKeys.updateValue(i - 1, forKey: self.fieldList[i].identifier)
}
self.fieldList.remove(at: index)
return true
}
public func revise() {
for field in self.fieldList {
if field.isEmpty {
if let index = self.fieldKeys.removeValue(forKey: field.identifier) {
for i in index..<(self.fieldList.count - 1) {
self.fieldKeys.updateValue(i, forKey: self.fieldList[i + 1].identifier)
}
self.fieldList.remove(at: index)
}
}
}
}
public func clear() {
self.fieldKeys.removeAll()
self.fieldList.removeAll()
}
// MARK: Subscripts
public subscript(identifier: Lyrics3FieldID) -> Lyrics3Field? {
guard let index = self.fieldKeys[identifier] else {
return nil
}
return self.fieldList[index]
}
}
|
mit
|
708c8e093bd804e0bb89a39de29f9bc7
| 29.893293 | 112 | 0.59025 | 4.419102 | false | false | false | false |
nguyenantinhbk77/practice-swift
|
Games/UberJump/UberJump/EndScene.swift
|
3
|
2463
|
import SpriteKit
class EndScene: SKScene {
override init(size: CGSize) {
super.init(size: size)
var star: SKSpriteNode? = SKSpriteNode(imageNamed: "Star2")
star?.position = CGPointMake(25, size.height-30)
self.addChild(star!)
star = nil
var lblStars:SKLabelNode = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
lblStars.fontSize = 30;
lblStars.fontColor = SKColor.whiteColor()
lblStars.position = CGPointMake(50, size.height-40);
lblStars.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
lblStars.text = NSString(format:"%d", GameState.sharedInstance._stars)
self.addChild(lblStars)
// Score
var lblScore:SKLabelNode = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
lblScore.fontSize = 60;
lblScore.fontColor = SKColor.whiteColor()
lblScore.position = CGPointMake(160, 300);
lblScore.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center
lblScore.text = NSString(format:"%d", GameState.sharedInstance._score)
self.addChild(lblScore)
// High Score
var lblHighScore:SKLabelNode = SKLabelNode(fontNamed:"ChalkboardSE-Bold")
lblHighScore.fontSize = 30
lblHighScore.fontColor = SKColor.cyanColor()
lblHighScore.position = CGPointMake(160, 150);
lblHighScore.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center
lblHighScore.text = NSString(format: "High Score: %d", GameState.sharedInstance._highScore)
self.addChild(lblHighScore)
// Try again
var lblTryAgain:SKLabelNode = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
lblTryAgain.fontSize = 30;
lblTryAgain.fontColor = SKColor.whiteColor()
lblTryAgain.position = CGPointMake(160, 50)
lblTryAgain.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center
lblTryAgain.text = "Tap To Try Again"
self.addChild(lblTryAgain)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Restart the game
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var myScene:SKScene = GameScene(size:self.size)
var reveal:SKTransition = SKTransition.fadeWithDuration(0.5)
self.view?.presentScene(myScene, transition: reveal)
}
}
|
mit
|
eb5303db0e4b487a7f1b259ff3a2f799
| 40.05 | 99 | 0.671133 | 4.829412 | false | false | false | false |
LonelyHusky/SCWeibo
|
SCWeibo/Classes/ViewModel/SCUserAccountModel.swift
|
1
|
5343
|
//
// SCUserAccountModel.swift
// SCWeibo
//
// Created by 云卷云舒丶 on 16/7/23.
//
//
import UIKit
import SVProgressHUD
class SCUserAccountModel: NSObject {
static let sharedMOdel:SCUserAccountModel = SCUserAccountModel()
override init() {
super.init()
// 代表当前 viewModel 初始化的时候,就尝试去沙盒中读取数据
account = self.accountInSanbox()
}
// 当前登入用户的帐号信息 -
var account:SCUserAccount?
var accessToken :String?{
return self.account?.access_token
}
var isLogin:Bool{
// 1.是否有accessToken
if accessToken == nil {
// 如何没有accessToken就代表没有登录 就 returen false
return false
}
// 2.accessToken是否过期
guard let expiresDate = self.account?.expiresDate else{
return false
}
if NSDate().compare(expiresDate) == .OrderedAscending {
// 没有过期就true
return true
}
return false
}
func loadAccessToken(code:String,finished:(isSuccess:Bool)->()){
let urlString = "https://api.weibo.com/oauth2/access_token"
//
// 必选 类型及范围 说明
// client_id true string 申请应用时分配的AppKey。
// client_secret true string 申请应用时分配的AppSecret。
// grant_type true string 请求的类型,填写authorization_code
//
// grant_type为authorization_code时
// 必选 类型及范围 说明
// code true string 调用authorize获得的code值。
// redirect_uri true string 回调地址,需需与注册应用里的回调地址一致。
let parames = [
"client_id":appKEY,
"client_secret":appSecret,
"grant_type":"authorization_code",
"code":code,
"redirect_uri":appUrl
]
SCNetworkTools.sharedTools.request(.Post, urlString: urlString, parameters: parames) { (responseObject, error) in
if error != nil{
print(error)
finished(isSuccess: false)
return
}
// print("请求成功:\(responseObject)")
// 如果as是写在if let 或者 guard 里面 ,都是使用as?
guard let dict = responseObject as? [String: AnyObject] else {
print("后台返回数据格式不对")
finished(isSuccess: false)
return
}
let account = SCUserAccount(dict:dict)
// print(account)
// 获取个人信息
self.loadUserInfo(account,finished: finished)
}
}
private func loadUserInfo(accout:SCUserAccount,finished:(isSuccess:Bool)->()){
let urlString = "https://api.weibo.com/2/users/show.json"
// access_token true string 采用OAuth授权方式为必填参数,OAuth授权后获得。
// uid false int64 需要查询的用户ID。
// screen_name false string 需要查询的用户昵称。
let params = [
"access_token":accout.access_token ?? "",
"uid":accout.uid ?? ""
]
SCNetworkTools.sharedTools.request(urlString: urlString, parameters: params) { (responseObject, error) -> () in
if error != nil{
SVProgressHUD.showErrorWithStatus("网络错误")
return
}
guard let dict = responseObject as? [String: AnyObject] else {
print("后台返回数据格式不对")
return
}
// 如果等于前面可选值的话就用as? 如果是必选值。就用as!
accout.name = dict["name"] as? String
accout.avatar_large = dict["avatar_large"] as? String
// print(accout)
self.account = accout
self.saveAccount(accout)
// 保存登录信息
finished(isSuccess: true)
}
}
private func saveAccount(account:SCUserAccount){
let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("accout.archive")
// print(path)
NSKeyedArchiver.archiveRootObject(account, toFile: path)
}
// 去沙盒中读取信息
private func accountInSanbox() ->SCUserAccount?{
let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("accout.archive")
let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path)as? SCUserAccount
// print(result)
return result
}
}
|
mit
|
a6b39f49b5d6f6fe16d7b6e71f45ef98
| 28.783951 | 209 | 0.533264 | 4.679922 | false | false | false | false |
drahot/BSImagePicker
|
Pod/Classes/Model/CustomPhotoDataSource.swift
|
1
|
7413
|
//
// CustomPhotoDataSource.swift
// Pods
//
// Created by Tatsuya Hotta on 2017/04/12.
//
//
import Foundation
import UIKit
import BSGridCollectionViewLayout
open class CustomPhotoDataSource<T: NSObject>: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
public var selections = [T]()
public var items: [T]!
public var changeSelections: (([T]) -> Void)? = nil
public var imageSize: CGSize = CGSize.zero
var settings: Settings = Settings()
fileprivate let photoCellIdentifier = "photoCellIdentifier"
let bundle: Bundle = Bundle(path: Bundle(for: PhotosViewController.self).path(forResource: "BSImagePicker", ofType: "bundle")!)!
var collectionView: UICollectionView!
let rowHandler: ((T) -> UIImage)
public init(_ items: [T], collectionView: UICollectionView!, rowHandler: @escaping ((T) -> UIImage), selections: [T]? = nil) {
self.items = items
self.collectionView = collectionView
self.rowHandler = rowHandler
if let selections = selections {
self.selections = selections
}
super.init()
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.collectionViewLayout = GridCollectionViewLayout()
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
UIView.setAnimationsEnabled(false)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoCellIdentifier, for: indexPath) as! PhotoCell
cell.accessibilityIdentifier = "photo_cell_\(indexPath.item)"
cell.settings = settings
let item = self.items[indexPath.row]
cell.imageView.contentMode = .scaleAspectFill
cell.imageView.image = resize(rowHandler(item), size: self.imageSize)
// Set selection number
if let index = selections.index(of: item) {
if let character = settings.selectionCharacter {
cell.selectionString = String(character)
} else {
cell.selectionString = String(index+1)
}
cell.photoSelected = true
} else {
cell.photoSelected = false
}
UIView.setAnimationsEnabled(true)
return cell
}
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let cell = collectionView.cellForItem(at: indexPath) as? PhotoCell else { return false }
let item = self.items[indexPath.row]
if let index = self.selections.index(of: item) { // DeSelect
// Deselect asset
self.selections.remove(at: index)
// Get indexPaths of selected items
let selectedIndexPaths = self.selections.flatMap({ (item) -> IndexPath? in
let index = self.items.index(of: item)
guard index != NSNotFound else { return nil }
return IndexPath(item: index!, section: 1)
})
// Reload selected cells to update their selection number
UIView.setAnimationsEnabled(false)
collectionView.reloadItems(at: selectedIndexPaths)
UIView.setAnimationsEnabled(true)
cell.photoSelected = false
} else if self.selections.count < self.settings.maxNumberOfSelections { // Select
self.selections.append(item)
if let selectionCharacter = self.settings.selectionCharacter {
cell.selectionString = String(selectionCharacter)
} else {
cell.selectionString = String(self.selections.count)
}
cell.photoSelected = true
}
if let changeSelectionsHandler = self.changeSelections {
changeSelectionsHandler(self.selections)
}
return false
}
public func registerCellIdentifiersForCollectionView(_ collectionView: UICollectionView?) {
collectionView?.register(UINib(nibName: "PhotoCell", bundle: self.bundle), forCellWithReuseIdentifier: photoCellIdentifier)
}
private func resize(_ image: UIImage, size: CGSize) -> UIImage {
let widthRatio = size.width / image.size.width
let heightRatio = size.height / image.size.height
let ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio
let resizedSize = CGSize(width: (image.size.width * ratio), height: (image.size.height * ratio))
UIGraphicsBeginImageContext(resizedSize)
image.draw(in: CGRect(x: 0, y: 0, width: resizedSize.width, height: resizedSize.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage!
}
}
// MARK: CustomPhotoDataSource proxy
extension CustomPhotoDataSource: BSImagePickerSettings {
public var maxNumberOfSelections: Int {
get {
return settings.maxNumberOfSelections
}
set {
settings.maxNumberOfSelections = newValue
}
}
public var selectionCharacter: Character? {
get {
return settings.selectionCharacter
}
set {
settings.selectionCharacter = newValue
}
}
public var selectionFillColor: UIColor {
get {
return settings.selectionFillColor
}
set {
settings.selectionFillColor = newValue
}
}
public var selectionStrokeColor: UIColor {
get {
return settings.selectionStrokeColor
}
set {
settings.selectionStrokeColor = newValue
}
}
public var selectionShadowColor: UIColor {
get {
return settings.selectionShadowColor
}
set {
settings.selectionShadowColor = newValue
}
}
public var selectionTextAttributes: [NSAttributedString.Key: Any] {
get {
return settings.selectionTextAttributes
}
set {
settings.selectionTextAttributes = newValue
}
}
public var backgroundColor: UIColor {
get {
return settings.backgroundColor
}
set {
settings.backgroundColor = newValue
}
}
public var cellsPerRow: (_ verticalSize: UIUserInterfaceSizeClass, _ horizontalSize: UIUserInterfaceSizeClass) -> Int {
get {
return settings.cellsPerRow
}
set {
settings.cellsPerRow = newValue
}
}
public var takePhotos: Bool {
get {
return settings.takePhotos
}
set {
settings.takePhotos = newValue
}
}
public var takePhotoIcon: UIImage? {
get {
return settings.takePhotoIcon
}
set {
settings.takePhotoIcon = newValue
}
}
}
|
mit
|
583f66b663e4241296556e62b0cd669b
| 31.800885 | 132 | 0.611898 | 5.507429 | false | false | false | false |
qmathe/Confetti
|
Renderer/MetalRenderer.swift
|
1
|
2211
|
//
// MetalRenderer.swift
// Confetti
//
// Created by Quentin Mathé on 01/08/2016.
// Copyright © 2016 Quentin Mathé. All rights reserved.
//
import Foundation
import MetalKit
class MetalRenderer {
let device = MTLCreateSystemDefaultDevice()!
let commandQueue: MTLCommandQueue
let pipelineDescriptor = MTLRenderPipelineDescriptor()
let pipelineState: MTLRenderPipelineState
let library: MTLLibrary
let fragmentProgram: MTLFunction
let vertexProgram: MTLFunction
var vertexBuffer: MTLBuffer?
init() {
commandQueue = device.newCommandQueue()
let libFile = NSBundle(forClass: self.dynamicType).pathForResource("default", ofType: "metallib")!
library = try! device.newLibraryWithFile(libFile)
fragmentProgram = library.newFunctionWithName("basic_fragment")!
vertexProgram = library.newFunctionWithName("basic_vertex")!
pipelineDescriptor.vertexFunction = vertexProgram
pipelineDescriptor.fragmentFunction = fragmentProgram
pipelineDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm
pipelineState = try! device.newRenderPipelineStateWithDescriptor(pipelineDescriptor)
}
func renderItem(item: Item?, intoDrawable drawable: CAMetalDrawable) {
let commandBuffer = commandQueue.commandBuffer()
let vertexData:[Float] = [0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]
let dataSize = vertexData.count * sizeofValue(vertexData[0])
vertexBuffer = device.newBufferWithBytes(vertexData, length: dataSize, options: .OptionCPUCacheModeDefault)
let renderDescriptor = MTLRenderPassDescriptor()
renderDescriptor.colorAttachments[0].texture = drawable.texture
renderDescriptor.colorAttachments[0].loadAction = .Clear
renderDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.0, green: 104.0/255.0, blue: 5.0/255.0, alpha: 1.0)
let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderDescriptor)
renderEncoder.setRenderPipelineState(pipelineState)
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0)
renderEncoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: 3, instanceCount: 1)
renderEncoder.endEncoding()
commandBuffer.presentDrawable(drawable)
commandBuffer.commit()
}
}
|
mit
|
c5a3ff4b8ecae6863021317b161cacf7
| 34.047619 | 124 | 0.783062 | 4.246154 | false | false | false | false |
Fenrikur/ef-app_ios
|
EurofurenceTests/Presenter Tests/Dealer Detail/Test Doubles/FakeDealerDetailViewModel.swift
|
1
|
2521
|
@testable import Eurofurence
import EurofurenceModel
import Foundation
class FakeDealerDetailViewModel: DealerDetailViewModel {
init(numberOfComponents: Int) {
self.numberOfComponents = numberOfComponents
}
var numberOfComponents: Int
func describeComponent(at index: Int, to visitor: DealerDetailViewModelVisitor) { }
private(set) var toldToOpenWebsite = false
func openWebsite() {
toldToOpenWebsite = true
}
private(set) var toldToOpenTwitter = false
func openTwitter() {
toldToOpenTwitter = true
}
private(set) var toldToOpenTelegram = false
func openTelegram() {
toldToOpenTelegram = true
}
private(set) var shareCommandSender: Any?
func shareDealer(_ sender: Any) {
shareCommandSender = sender
}
}
class FakeDealerDetailSummaryViewModel: FakeDealerDetailViewModel {
private let summary: DealerDetailSummaryViewModel
init(summary: DealerDetailSummaryViewModel) {
self.summary = summary
super.init(numberOfComponents: 1)
}
override func describeComponent(at index: Int, to visitor: DealerDetailViewModelVisitor) {
visitor.visit(summary)
}
}
class FakeDealerDetailLocationAndAvailabilityViewModel: FakeDealerDetailViewModel {
private let location: DealerDetailLocationAndAvailabilityViewModel
init(location: DealerDetailLocationAndAvailabilityViewModel) {
self.location = location
super.init(numberOfComponents: 1)
}
override func describeComponent(at index: Int, to visitor: DealerDetailViewModelVisitor) {
visitor.visit(location)
}
}
class FakeDealerDetailAboutTheArtistViewModel: FakeDealerDetailViewModel {
private let aboutTheArtist: DealerDetailAboutTheArtistViewModel
init(aboutTheArtist: DealerDetailAboutTheArtistViewModel) {
self.aboutTheArtist = aboutTheArtist
super.init(numberOfComponents: 1)
}
override func describeComponent(at index: Int, to visitor: DealerDetailViewModelVisitor) {
visitor.visit(aboutTheArtist)
}
}
class FakeDealerDetailAboutTheArtViewModel: FakeDealerDetailViewModel {
private let aboutTheArt: DealerDetailAboutTheArtViewModel
init(aboutTheArt: DealerDetailAboutTheArtViewModel) {
self.aboutTheArt = aboutTheArt
super.init(numberOfComponents: 1)
}
override func describeComponent(at index: Int, to visitor: DealerDetailViewModelVisitor) {
visitor.visit(aboutTheArt)
}
}
|
mit
|
885e04e03c344a81b4b541f4051eebb3
| 25.536842 | 94 | 0.737009 | 5.285115 | false | false | false | false |
NorbertAgoston3pg/PinClustering
|
PinClustering/PinClustering/ViewControllers/MapViewController+MapHandlingExtension.swift
|
1
|
2039
|
//
// MapViewController+MapHandlingExtension.swift
// PinClustering
//
// Created by Norbert Agoston on 13/09/16.
// Copyright © 2016 Norbert Agoston. All rights reserved.
//
import Foundation
import MapKit
extension MapViewController: MKMapViewDelegate {
func setupMap(pointsOfInterest: [AnyObject]) {
guard let pointOfInterest = pointsOfInterest.first as? FuelLocation else {
return
}
centerMapOnLocation(pointOfInterest.coordinate)
displayOnMap(pointsOfInterest)
}
func displayOnMap(pointsOfInterest: [AnyObject]) {
if let pointsOfInterest = pointsOfInterest as? [FuelLocation] {
map.addAnnotations(pointsOfInterest)
}
}
func centerMapOnLocation(coordinate: CLLocationCoordinate2D) {
let regionRadius: CLLocationDistance = 50000
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
map.setRegion(coordinateRegion, animated: true)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? FuelLocation else {
return nil
}
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type:.DetailDisclosure) as UIView
}
return view
}
}
|
mit
|
43ab001d9339022ef4a10fb57f036b90
| 35.410714 | 119 | 0.653582 | 5.740845 | false | false | false | false |
juheon0615/GhostHandongSwift
|
HandongAppSwift/CVCalendar/CVCalendarWeekday.swift
|
13
|
362
|
//
// CVCalendarWeekday.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 15/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import Foundation
@objc enum CVCalendarWeekday: Int {
case Sunday = 1
case Monday = 2
case Tuesday = 3
case Wednesday = 4
case Thursday = 5
case Friday = 6
case Saturday = 7
}
|
mit
|
51fd683dfe11d0f177087b73fe604b90
| 18.105263 | 52 | 0.654696 | 3.770833 | false | false | false | false |
eric1202/LZJ_Coin
|
LZJ_Coin/LZJ_Coin/Section/News/NewsTableViewCell.swift
|
1
|
2111
|
//
// NewsTableViewCell.swift
// LZJ_Coin
//
// Created by Heyz on 2017/6/5.
// Copyright © 2017年 LZJ. All rights reserved.
//
import UIKit
import SnapKit
class NewsTableViewCell: UITableViewCell {
public var imageV : UIImageView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.imageV = UIImageView.init()
self.imageV?.contentMode = .scaleAspectFit
self.contentView.backgroundColor = UIColor.init(red:CGFloat((arc4random()%100))/100.0, green:CGFloat((arc4random()%100))/100.0, blue: CGFloat((arc4random()%100))/100.0, alpha: 0.3)
self.contentView.addSubview(self.imageV!)
weak var ws = self as NewsTableViewCell
if let cell = ws {
self.textLabel?.snp.remakeConstraints({ (make) in
make.left.equalTo(cell.contentView.snp.left).offset(15)
make.width.lessThanOrEqualTo(cell.contentView.snp.width)
make.bottom.equalTo(cell.contentView.snp.bottom).offset(-20)
make.top.equalTo(cell.contentView.snp.top).offset(20)
})
self.imageV!.snp.makeConstraints { (make) in
make.top.equalTo(cell.contentView.snp.top).offset(20)
make.right.equalTo(cell.contentView.snp.right).offset(-20)
make.size.equalTo(CGSize(width: 100, height: 100))
make.left.equalTo(cell.textLabel!.snp.right).offset(20)
make.bottom.lessThanOrEqualTo(cell.contentView.snp.bottom).offset(-20)
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
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
|
b4a1ee30efc5760782302dbb6b34fa31
| 33 | 188 | 0.633302 | 4.293279 | false | false | false | false |
YuAo/WAAccountStore
|
WAAccountStoreDemo/WAAccountStoreDemo/ViewController.swift
|
1
|
4023
|
//
// ViewController.swift
// WAAccountStoreDemo
//
// Created by YuAo on 5/23/15.
// Copyright (c) 2015 YuAo. All rights reserved.
//
import UIKit
import WAAccountStore
import Mantle
class User: MTLModel {
private(set) var name: String?
private(set) var email: String?
override init() {
super.init()
}
init (name: String, email: String) {
super.init()
self.name = name
self.email = email
}
required init(dictionary dictionaryValue: [NSObject : AnyObject]!) throws {
try super.init(dictionary: dictionaryValue)
}
required init!(coder: NSCoder!) {
super.init(coder: coder)
}
}
extension WAAccount {
var user: User {
get {
return self.userInfo as! User
}
}
convenience init(identifier: String, credential: WAAccountCredential, user: User) {
self.init(identifier: identifier, credential: credential, userInfo: user)
}
}
let UserAccessTokenStorageKey = "AccessToken"
extension WAAccountCredential {
var accessToken: String {
get {
return self.securityStorage[UserAccessTokenStorageKey] as! String
}
}
convenience init(identifier: String, accessToken: String) {
self.init(identifier: identifier, securityStorage: [UserAccessTokenStorageKey: accessToken])
}
}
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.reloadCurrentAccountInfo()
}
func reloadCurrentAccountInfo() {
if let currentAccount = WAAccountStore.defaultStore().currentAccount {
self.textView.text = "ID:\(currentAccount.identifier)\nName:\(currentAccount.user.name!)\nEmail:\(currentAccount.user.email!)\nAccessToken:\(currentAccount.credential.accessToken)"
} else {
self.textView.text = "No Accounts"
}
}
@IBAction func addAccountButtonTapped(sender: AnyObject) {
let alertController = UIAlertController(title: "Add Account", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
//AccountID
textField.text = NSProcessInfo.processInfo().globallyUniqueString
textField.textColor = UIColor.lightGrayColor()
textField.enabled = false
}
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "Name"
}
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "Email"
}
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "AccessToken"
}
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in
}))
alertController.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
//AccountID
let accountID = (alertController.textFields![0]).text
//Name
let name = (alertController.textFields![1]).text
//Email
let email = (alertController.textFields![2]).text
//AccessToken
let token = (alertController.textFields![3]).text
let account = WAAccount(
identifier: accountID!,
credential: WAAccountCredential(identifier: accountID!, accessToken: token!),
user: User(name: name!, email: email!))
WAAccountStore.defaultStore().addAccount(account)
self.reloadCurrentAccountInfo()
}))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
|
mit
|
94d2596b83005a3c50955978a77b74de
| 31.707317 | 192 | 0.63659 | 5.098859 | false | false | false | false |
ben-ng/swift
|
test/attr/attr_fixed_layout.swift
|
3
|
1803
|
// RUN: %target-swift-frontend -typecheck -dump-ast -enable-resilience %s 2>&1 | %FileCheck --check-prefix=RESILIENCE-ON %s
// RUN: %target-swift-frontend -typecheck -dump-ast %s 2>&1 | %FileCheck --check-prefix=RESILIENCE-OFF %s
//
// Public types with @_fixed_layout are always fixed layout
//
// RESILIENCE-ON: struct_decl "Point" interface type='Point.Type' access=public @_fixed_layout
// RESILIENCE-OFF: struct_decl "Point" interface type='Point.Type' access=public @_fixed_layout
@_fixed_layout public struct Point {
let x, y: Int
}
// RESILIENCE-ON: enum_decl "ChooseYourOwnAdventure" interface type='ChooseYourOwnAdventure.Type' access=public @_fixed_layout
// RESILIENCE-OFF: enum_decl "ChooseYourOwnAdventure" interface type='ChooseYourOwnAdventure.Type' access=public @_fixed_layout
@_fixed_layout public enum ChooseYourOwnAdventure {
case JumpIntoRabbitHole
case EatMushroom
}
//
// Public types are resilient when -enable-resilience is on
//
// RESILIENCE-ON: struct_decl "Size" interface type='Size.Type' access=public @_resilient_layout
// RESILIENCE-OFF: struct_decl "Size" interface type='Size.Type' access=public @_fixed_layout
public struct Size {
let w, h: Int
}
// RESILIENCE-ON: enum_decl "TaxCredit" interface type='TaxCredit.Type' access=public @_resilient_layout
// RESILIENCE-OFF: enum_decl "TaxCredit" interface type='TaxCredit.Type' access=public @_fixed_layout
public enum TaxCredit {
case EarnedIncome
case MortgageDeduction
}
//
// Internal types are always fixed layout
//
// RESILIENCE-ON: struct_decl "Rectangle" interface type='Rectangle.Type' access=internal @_fixed_layout
// RESILIENCE-OFF: struct_decl "Rectangle" interface type='Rectangle.Type' access=internal @_fixed_layout
struct Rectangle {
let topLeft: Point
let bottomRight: Size
}
|
apache-2.0
|
8375f4f7d504c6ecba2b44c3c6c25f54
| 37.361702 | 127 | 0.754298 | 3.401887 | false | false | false | false |
pkluz/PKHUD
|
PKHUD/Window.swift
|
1
|
5782
|
//
// HUDWindow.swift
// PKHUD
//
// Created by Philip Kluz on 6/16/14.
// Copyright (c) 2016 NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import UIKit
/// The window used to display the PKHUD within. Placed atop the applications main window.
internal class ContainerView: UIView {
private var keyboardIsVisible = false
private var keyboardHeight: CGFloat = 0.0
internal let frameView: FrameView
internal init(frameView: FrameView = FrameView()) {
self.frameView = frameView
super.init(frame: CGRect.zero)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
frameView = FrameView()
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
backgroundColor = UIColor.clear
isHidden = true
addSubview(backgroundView)
addSubview(frameView)
}
internal override func layoutSubviews() {
super.layoutSubviews()
frameView.center = calculateHudCenter()
backgroundView.frame = bounds
}
internal func showFrameView() {
layer.removeAllAnimations()
frameView.center = calculateHudCenter()
frameView.alpha = 1.0
isHidden = false
}
fileprivate var willHide = false
internal func hideFrameView(animated anim: Bool, completion: ((Bool) -> Void)? = nil) {
let finalize: (_ finished: Bool) -> Void = { finished in
self.isHidden = true
self.removeFromSuperview()
self.willHide = false
completion?(finished)
}
if isHidden {
return
}
willHide = true
if anim {
UIView.animate(withDuration: 0.8, animations: {
self.frameView.alpha = 0.0
self.hideBackground(animated: false)
}, completion: { _ in finalize(true) })
} else {
self.frameView.alpha = 0.0
finalize(true)
}
}
fileprivate let backgroundView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.0, alpha: 0.25)
view.alpha = 0.0
return view
}()
internal func showBackground(animated anim: Bool) {
if anim {
UIView.animate(withDuration: 0.175, animations: {
self.backgroundView.alpha = 1.0
})
} else {
backgroundView.alpha = 1.0
}
}
internal func hideBackground(animated anim: Bool) {
if anim {
UIView.animate(withDuration: 0.65, animations: {
self.backgroundView.alpha = 0.0
})
} else {
backgroundView.alpha = 0.0
}
}
// MARK: Notifications
internal func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
internal func deregisterFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
// MARK: Triggered Functions
@objc private func keyboardWillShow(notification: NSNotification) {
keyboardIsVisible = true
guard let userInfo = notification.userInfo else {
return
}
if let keyboardHeight = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height {
self.keyboardHeight = keyboardHeight
}
if !self.isHidden {
if let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber {
animateHUDWith(duration: duration.doubleValue,
curve: UIView.AnimationCurve(rawValue: curve.intValue) ?? UIView.AnimationCurve.easeInOut,
toLocation: calculateHudCenter())
}
}
}
@objc private func keyboardWillBeHidden(notification: NSNotification) {
keyboardIsVisible = false
if !self.isHidden {
guard let userInfo = notification.userInfo else {
return
}
if let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
let curve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber {
animateHUDWith(duration: duration.doubleValue,
curve: UIView.AnimationCurve(rawValue: curve.intValue) ?? UIView.AnimationCurve.easeInOut,
toLocation: calculateHudCenter())
}
}
}
// MARK: - Helpers
private func animateHUDWith(duration: Double, curve: UIView.AnimationCurve, toLocation location: CGPoint) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(TimeInterval(duration))
UIView.setAnimationCurve(curve)
frameView.center = location
UIView.commitAnimations()
}
private func calculateHudCenter() -> CGPoint {
if !keyboardIsVisible {
return center
} else {
let yLocation = (frame.height - keyboardHeight) / 2
return CGPoint(x: center.x, y: yLocation)
}
}
}
|
mit
|
69aba8ded00e37030b1ba4e744ea087e
| 32.616279 | 171 | 0.617606 | 5.363636 | false | false | false | false |
brentvatne/react-native-video
|
ios/Video/Features/RCTPlayerObserver.swift
|
1
|
9057
|
import AVFoundation
import AVKit
import Foundation
@objc
protocol RCTPlayerObserverHandlerObjc {
func handleDidFailToFinishPlaying(notification:NSNotification!)
func handlePlaybackStalled(notification:NSNotification!)
func handlePlayerItemDidReachEnd(notification:NSNotification!)
// unused
// func handleAVPlayerAccess(notification:NSNotification!)
}
protocol RCTPlayerObserverHandler: RCTPlayerObserverHandlerObjc {
func handleTimeUpdate(time:CMTime)
func handleReadyForDisplay(changeObject: Any, change:NSKeyValueObservedChange<Bool>)
func handleTimeMetadataChange(playerItem:AVPlayerItem, change:NSKeyValueObservedChange<[AVMetadataItem]?>)
func handlePlayerItemStatusChange(playerItem:AVPlayerItem, change:NSKeyValueObservedChange<AVPlayerItem.Status>)
func handlePlaybackBufferKeyEmpty(playerItem:AVPlayerItem, change:NSKeyValueObservedChange<Bool>)
func handlePlaybackLikelyToKeepUp(playerItem:AVPlayerItem, change:NSKeyValueObservedChange<Bool>)
func handlePlaybackRateChange(player: AVPlayer, change: NSKeyValueObservedChange<Float>)
func handleExternalPlaybackActiveChange(player: AVPlayer, change: NSKeyValueObservedChange<Bool>)
func handleViewControllerOverlayViewFrameChange(overlayView:UIView, change:NSKeyValueObservedChange<CGRect>)
}
class RCTPlayerObserver: NSObject {
var _handlers: RCTPlayerObserverHandler!
var player:AVPlayer? {
willSet {
removePlayerObservers()
removePlayerTimeObserver()
}
didSet {
if player != nil {
addPlayerObservers()
addPlayerTimeObserver()
}
}
}
var playerItem:AVPlayerItem? {
willSet {
removePlayerItemObservers()
}
didSet {
if playerItem != nil {
addPlayerItemObservers()
}
}
}
var playerViewController:AVPlayerViewController? {
willSet {
removePlayerViewControllerObservers()
}
didSet {
if playerViewController != nil {
addPlayerViewControllerObservers()
}
}
}
var playerLayer:AVPlayerLayer? {
willSet {
removePlayerLayerObserver()
}
didSet {
if playerLayer != nil {
addPlayerLayerObserver()
}
}
}
private var _progressUpdateInterval:TimeInterval = 250
private var _timeObserver:Any?
private var _playerRateChangeObserver:NSKeyValueObservation?
private var _playerExpernalPlaybackActiveObserver:NSKeyValueObservation?
private var _playerItemStatusObserver:NSKeyValueObservation?
private var _playerPlaybackBufferEmptyObserver:NSKeyValueObservation?
private var _playerPlaybackLikelyToKeepUpObserver:NSKeyValueObservation?
private var _playerTimedMetadataObserver:NSKeyValueObservation?
private var _playerViewControllerReadyForDisplayObserver:NSKeyValueObservation?
private var _playerLayerReadyForDisplayObserver:NSKeyValueObservation?
private var _playerViewControllerOverlayFrameObserver:NSKeyValueObservation?
deinit {
NotificationCenter.default.removeObserver(_handlers)
}
func addPlayerObservers() {
guard let player = player else {
return
}
_playerRateChangeObserver = player.observe(\.rate, changeHandler: _handlers.handlePlaybackRateChange)
_playerExpernalPlaybackActiveObserver = player.observe(\.isExternalPlaybackActive, changeHandler: _handlers.handleExternalPlaybackActiveChange)
}
func removePlayerObservers() {
_playerRateChangeObserver?.invalidate()
_playerExpernalPlaybackActiveObserver?.invalidate()
}
func addPlayerItemObservers() {
guard let playerItem = playerItem else { return }
_playerItemStatusObserver = playerItem.observe(\.status, options: [.new, .old], changeHandler: _handlers.handlePlayerItemStatusChange)
_playerPlaybackBufferEmptyObserver = playerItem.observe(\.isPlaybackBufferEmpty, options: [.new, .old], changeHandler: _handlers.handlePlaybackBufferKeyEmpty)
_playerPlaybackLikelyToKeepUpObserver = playerItem.observe(\.isPlaybackLikelyToKeepUp, options: [.new, .old], changeHandler: _handlers.handlePlaybackLikelyToKeepUp)
_playerTimedMetadataObserver = playerItem.observe(\.timedMetadata, options: [.new], changeHandler: _handlers.handleTimeMetadataChange)
}
func removePlayerItemObservers() {
_playerItemStatusObserver?.invalidate()
_playerPlaybackBufferEmptyObserver?.invalidate()
_playerPlaybackLikelyToKeepUpObserver?.invalidate()
_playerTimedMetadataObserver?.invalidate()
}
func addPlayerViewControllerObservers() {
guard let playerViewController = playerViewController else { return }
_playerViewControllerReadyForDisplayObserver = playerViewController.observe(\.isReadyForDisplay, options: [.new], changeHandler: _handlers.handleReadyForDisplay)
_playerViewControllerOverlayFrameObserver = playerViewController.contentOverlayView?.observe(\.frame, options: [.new, .old], changeHandler: _handlers.handleViewControllerOverlayViewFrameChange)
}
func removePlayerViewControllerObservers() {
_playerViewControllerReadyForDisplayObserver?.invalidate()
_playerViewControllerOverlayFrameObserver?.invalidate()
}
func addPlayerLayerObserver() {
_playerLayerReadyForDisplayObserver = playerLayer?.observe(\.isReadyForDisplay, options: [.new], changeHandler: _handlers.handleReadyForDisplay)
}
func removePlayerLayerObserver() {
_playerLayerReadyForDisplayObserver?.invalidate()
}
func addPlayerTimeObserver() {
removePlayerTimeObserver()
let progressUpdateIntervalMS:Float64 = _progressUpdateInterval / 1000
// @see endScrubbing in AVPlayerDemoPlaybackViewController.m
// of https://developer.apple.com/library/ios/samplecode/AVPlayerDemo/Introduction/Intro.html
_timeObserver = player?.addPeriodicTimeObserver(
forInterval: CMTimeMakeWithSeconds(progressUpdateIntervalMS, preferredTimescale: Int32(NSEC_PER_SEC)),
queue:nil,
using:_handlers.handleTimeUpdate
)
}
/* Cancels the previously registered time observer. */
func removePlayerTimeObserver() {
if _timeObserver != nil {
player?.removeTimeObserver(_timeObserver)
_timeObserver = nil
}
}
func addTimeObserverIfNotSet() {
if (_timeObserver == nil) {
addPlayerTimeObserver()
}
}
func replaceTimeObserverIfSet(_ newUpdateInterval:Float64? = nil) {
if let newUpdateInterval = newUpdateInterval {
_progressUpdateInterval = newUpdateInterval
}
if (_timeObserver != nil) {
addPlayerTimeObserver()
}
}
func attachPlayerEventListeners() {
NotificationCenter.default.removeObserver(_handlers,
name:NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object:player?.currentItem)
NotificationCenter.default.addObserver(_handlers,
selector:#selector(RCTPlayerObserverHandler.handlePlayerItemDidReachEnd(notification:)),
name:NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object:player?.currentItem)
NotificationCenter.default.removeObserver(_handlers,
name:NSNotification.Name.AVPlayerItemPlaybackStalled,
object:nil)
NotificationCenter.default.addObserver(_handlers,
selector:#selector(RCTPlayerObserverHandler.handlePlaybackStalled(notification:)),
name:NSNotification.Name.AVPlayerItemPlaybackStalled,
object:nil)
NotificationCenter.default.removeObserver(_handlers,
name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime,
object:nil)
NotificationCenter.default.addObserver(_handlers,
selector:#selector(RCTPlayerObserverHandler.handleDidFailToFinishPlaying(notification:)),
name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime,
object:nil)
}
func clearPlayer() {
player = nil
playerItem = nil
NotificationCenter.default.removeObserver(_handlers)
}
}
|
mit
|
d92b3fd01533992f98cc86960ddfed22
| 42.753623 | 202 | 0.664127 | 6.09899 | false | false | false | false |
ZhengShouDong/CloudPacker
|
Sources/CloudPacker/Utilities/CloudPackerUtils.swift
|
1
|
10579
|
//
// CloudPackerUtils.swift
// CloudPacker
//
// Created by ZHENGSHOUDONG on 2017/10/18.
//
import Foundation
import PerfectLib
import XcodeManager
public enum ProvisioningStyle: String {
public typealias RawValue = String
case automatic = "Automatic"
case manual = "Manual"
}
public class CloudPackerUtils {
/// 执行单个shell命令
///
/// - Parameters:
/// - shellStr: shell命令(字符串)
/// - success: 成功闭包回调
/// - failed: 失败闭包回调
public class func executeShell(shellStr: String, success: (String) -> (), failed: (NSDictionary) -> ()) {
guard !shellStr.isEmpty else { return }
var eventDescriptor = NSAppleEventDescriptor()
var script = NSAppleScript()
var error: NSDictionary? = NSDictionary()
let scriptSource = String(format: "do shell script \"%@\"", shellStr)
guard !scriptSource.isEmpty else {
failed(["error": "scriptSource is empty!"])
return
}
script = NSAppleScript(source: scriptSource)!
eventDescriptor = script.executeAndReturnError(&error)
if (error!.count > 0) {
// printLog(message: "error:\(error!)", type:.error)
failed(error!)
}else {
let info = eventDescriptor.stringValue ?? emptyString
// printLog(message: "info:\(info)", type:.info)
success(info)
}
}
/// 判断指定路径是否为文件夹,亦可用来判断文件夹是否存在
///
/// - Parameter fullPath: 路径
/// - Returns: 文件夹是否存在
public class func isDirectoryExists(fullPath: String) -> Bool {
guard !fullPath.isEmpty else { return false }
return access(fullPath, F_OK) != -1
/*
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: fullPath, isDirectory:&isDir) {
if isDir.boolValue {
// file exists and is a directory
return true
} else {
// file exists and is not a directory
return false
}
} else {
// dir does not exist
return false
} */
}
/// 在指定路径创建文件夹,如果不存在则创建
///
/// - Parameter path: 路径
public class func createFolderIfNeeded(path: String) {
guard !path.isEmpty else { return }
if !Dir(path).exists {
do {
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}catch {
printLog(message: error, type: .error)
}
}else {
// printLog(message: "[" + path + "] Folder is exists,pass.", type: .debug)
}
}
/// 指定路径创建文件夹,不存在自动创建
///
/// - Parameter pathArray: 传入数组,数组中放多个路径字符串
public class func createFolderIfNeeded(pathArray: [String]) {
for path:String in pathArray {
createFolderIfNeeded(path: path)
}
}
/// 字符串处理
///
/// - Parameter gitLocation: Input:"https://github.com/ZhengShouDong/CloudPacker.git"
/// - Returns: Output:"CloudPacker"
public class func getProjectName(gitLocation: String) -> String {
guard !gitLocation.isEmpty else { return emptyString }
let gitL = gitLocation.replacingOccurrences(of: " ", with: "")
let arr = gitL.split(separator: "/")
var name = arr[arr.count - 1].description
name = name.replacingOccurrences(of: ".git", with: "")
return name
}
/// json to dictionary
///
/// - Parameter jsonString: Json字符串
/// - Returns: 转换为Dictionary对象
public class func getDictionaryFromJSONString(jsonString:String) -> Dictionary<String, Any> {
guard !jsonString.isEmpty else { return [:] }
let jsonData:Data = jsonString.data(using: .utf8)!
let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
if dict != nil {
return dict as! Dictionary
}
return [:]
}
public class func disposeProjProvisioningStyle(style: ProvisioningStyle, xcodeprojPath: String) {
var path = xcodeprojPath
guard !path.isEmpty else {
printLog(message: "处理自动签名失败,原因:传入路径空!", type: .error)
return
}
if path.hasSuffix(".pbxproj") {
path = path.replacingOccurrences(of: "/project.pbxproj", with: "", options: .backwards, range: nil)
}
var project = try? XcodeManager.init(projectFile: path, printLog: true)
switch style {
case .automatic:
project?.updateCodeSignStyle(type: .automatic)
break
case .manual:
project?.updateCodeSignStyle(type: .manual)
break
}
let isSaveSuccess = project?.save() ?? false
if (isSaveSuccess) {
printLog(message: "更改自动签名设置: 成功")
}else {
printLog(message: "更改自动签名设置: 失败")
}
}
/// 筛选出无用的文件和文件夹
///
/// - Parameter path:传入路径
/// - Returns: 返回字符串数组
public class func nameFiltrate(path: String) -> [String] {
guard !path.isEmpty else { return [] }
do {
let nameArr = try FileManager.default.contentsOfDirectory(atPath: path)
if nameArr.count > 0 {
var dirArr: [String] = Array()
for key: String in nameArr {
if key.hasSuffix(".bundle") { continue }
if key.hasSuffix(".zip") { continue }
if key.hasPrefix(".") { continue }
if !key.hasPrefix("BS") { continue }
if key.hasPrefix(" ") { continue }
dirArr.append(key)
}
return dirArr
}else {
printLog(message: "路径下没有文件或者文件夹!返回空数组!", type: .error)
return []
}
} catch {
printLog(message: "筛选出无用的文件和文件夹错误:\(error)", type: .error)
return []
}
}
public class func runProc(cmd: String, args: [String], read: Bool = false) throws -> String? {
let envs = [("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin")]
let proc = try SysProcess(cmd, args: args, env: envs)
var ret: String?
if read {
var ary = [UInt8]()
while true {
do {
guard let s = try proc.stdout?.readSomeBytes(count: 1024), s.count > 0 else {
break
}
ary.append(contentsOf: s)
} catch PerfectLib.PerfectError.fileError(let code, _) {
if code != EINTR {
break
}
}
}
ret = UTF8Encoding.encode(bytes: ary)
}
let res = try proc.wait(hang: true)
if res != 0 {
let s = try proc.stderr?.readString()
throw PerfectError.systemError(Int32(res), s!)
}
return ret
}
/// 正则验证字符串
///
/// - Parameters:
/// - str: 将要验证的字符串
/// - pattern: 正则字符串
public class func matches(str: String, pattern: String) -> [NSTextCheckingResult] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let result = regex.matches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, str.count))
return result
} catch {
printLog(message: "\(error)", type: .error)
}
return []
}
/// 正则验证字符串(匹配第一次校验到的,并返回一个NSRange)
///
/// - Parameters:
/// - str: 将要验证的字符串
/// - pattern: 正则字符串规则
/// -
public class func checkRangeOfFirstMatch(str: String, pattern: String) -> NSRange {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
return regex.rangeOfFirstMatch(in: str, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, str.lengthOfBytes(using: .utf8)))
} catch {
printLog(message: "\(error)", type: .error)
}
return NSRange(location: 0, length: 0)
}
/// 获取本机IP
public class func GetIPAddresses() -> String? {
var addresses = [String]()
var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while (ptr != nil) {
let flags = Int32(ptr!.pointee.ifa_flags)
var addr = ptr!.pointee.ifa_addr.pointee
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
if let address = String(validatingUTF8:hostname) {
addresses.append(address)
}
}
}
}
ptr = ptr!.pointee.ifa_next
}
freeifaddrs(ifaddr)
}
return addresses.first
}
}
|
apache-2.0
|
690c4664e69db6c0e01d300a54334ed7
| 34.982079 | 174 | 0.509911 | 4.717575 | false | false | false | false |
AnyPresence/justapis-swift-sdk
|
Source/Response.swift
|
1
|
3386
|
//
// Response.swift
// JustApisSwiftSDK
//
// Created by Andrew Palumbo on 12/29/15.
// Copyright © 2015 AnyPresence. All rights reserved.
//
import Foundation
///
/// Properties that define a Response.
///
public protocol ResponseProperties
{
/// The Gateway from which this response was generated
var gateway:Gateway { get }
/// The Request that was ultimately submitted to the gateway
var request:Request { get }
/// The final URL that was sent to the gateway (prior to redirection)
var requestedURL:NSURL { get }
/// The final URL of the request (after any redirection)
var resolvedURL:NSURL? { get }
/// The HTTP status code returned by the server
var statusCode:Int { get }
/// HTTP headers returned by the server
var headers:Headers { get }
/// Any body data returned by the server
var body:NSData? { get }
/// Any parsed body data
var parsedBody:AnyObject? { get }
/// Indicates that this response was retrieved from a local cache
var retreivedFromCache:Bool { get }
}
public protocol ResponseBuilderMethods
{
/// Returns a new Response with gateway set to the provided value
func gateway(value:Gateway) -> Self
/// Returns a new Response with request set to the provided value
func request(value:Request) -> Self
/// Returns a new Response with requestedURL set to the provided value
func requestedURL(value:NSURL) -> Self
/// Returns a new Response with resolvedURL set to the provided value
func resolvedURL(value:NSURL) -> Self
/// Returns a new Response with statusCode set to the provided value
func statusCode(value:Int) -> Self
/// Returns a new Response with all headers set to the provided value
func headers(value:Headers) -> Self
/// Returns a new Response with a header with the provided key set to the provided value
func header(key:String, value:String?) -> Self
/// Returns a new Response with body set to the provided value
func body(value:NSData?) -> Self
/// Returns a new Response with parsedBody set to the provided value
func parsedBody(value:AnyObject?) -> Self
// Returns a new Response with retreivedFromCache set to the provided value
func retreivedFromCache(value:Bool) -> Self
}
public protocol Response : ResponseProperties, ResponseBuilderMethods
{
}
///
/// Basic mutable representation of public Response properties
///
public struct MutableResponseProperties : ResponseProperties
{
public var gateway:Gateway
public var request:Request
public var requestedURL:NSURL
public var resolvedURL:NSURL?
public var statusCode:Int
public var headers:Headers
public var body:NSData?
public var parsedBody:AnyObject?
public var retreivedFromCache:Bool
public init(gateway:Gateway, request:Request, requestedURL:NSURL, resolvedURL:NSURL, statusCode:Int, headers:Headers, body:NSData?, parsedBody:AnyObject?, retreivedFromCache:Bool) {
self.gateway = gateway
self.request = request
self.requestedURL = requestedURL
self.resolvedURL = resolvedURL
self.statusCode = statusCode
self.headers = headers
self.body = body
self.parsedBody = parsedBody
self.retreivedFromCache = retreivedFromCache
}
}
|
mit
|
f5134e075179c3d4793794abdc2a0022
| 30.351852 | 185 | 0.693058 | 4.701389 | false | false | false | false |
manGoweb/SpecTools
|
SpecTools/Classes/SpecTools.swift
|
1
|
2264
|
//
// SpecTools.swift
// Pods
//
// Created by Ondrej Rafaj on 25/08/2017.
//
//
import Foundation
import UIKit
/// Checking properties of an object or a view
public struct Check<T> {
let element: T
init(_ obj: T) {
element = obj
}
}
/// Searching for views by their text or type
public struct Find<T> {
let element: T
init(_ obj: T) {
element = obj
}
}
/// Prepare objects or views for certain state
public struct Prepare<T> {
let element: T
init(_ obj: T) {
element = obj
}
}
/// Simulate actions on views or objects
public struct Action<T> {
let element: T
init(_ obj: T) {
element = obj
}
}
/// Main holding property. Any supported view or object will have .spec property available
public struct Property<T> {
let element: T
/// Contains checks on supported elements
/// (like isVisible or hasSiblings, etc)
public let check: Check<T>
/// If you are looking for something, find is your guy
/// (You can find text, recurse through UIView structures, etc)
public let find: Find<T>
/// Prepares supported elements
/// (like prepare view controllers for testing, etc)
public let prepare: Prepare<T>
/// Actions on supported elements
/// (like tap on a button or execute a gesture recognizers targets)
public let action: Action<T>
init(_ obj: T) {
element = obj
check = Check(obj)
find = Find(obj)
prepare = Prepare(obj)
action = Action(obj)
}
}
/// Main property protocol which delivers basic element accessors
public protocol PropertyProtocol {
associatedtype PropertyParentType
var spec: Property<PropertyParentType> { get }
}
extension PropertyProtocol {
/// Main property used to access checks, finds, prepares and and actions for any supported elements
public var spec: Property<Self> {
get {
return Property(self)
}
}
}
extension UIGestureRecognizer: PropertyProtocol { }
extension UIView: PropertyProtocol { }
extension UIViewController: PropertyProtocol { }
extension UIBarButtonItem: PropertyProtocol { }
|
mit
|
6ba4e17b0e0338cade92e21988832b3e
| 19.962963 | 103 | 0.623233 | 4.37911 | false | false | false | false |
bugix/VerticalLabel
|
VerticalLabel/VerticalLabel.swift
|
1
|
2372
|
//
// VerticalLabel.swift
// VerticalLabel
//
// Created by Martin Imobersteg on 10.10.17.
// Copyright © 2017 Martin Imobersteg. All rights reserved.
//
import UIKit
@IBDesignable
public class VerticalLabel: UIView {
private let label = UILabel()
@IBInspectable
public var text: String = "" {
didSet {
self.label.text = self.text
invalidateIntrinsicContentSize()
}
}
@IBInspectable
public var fontSize: Int = 14 {
didSet {
self.label.font = .systemFont(ofSize: CGFloat(fontSize))
invalidateIntrinsicContentSize()
}
}
@IBInspectable
public var fontColor: UIColor = .black {
didSet {
self.label.textColor = fontColor
}
}
@IBInspectable
public var boldFont: Bool = false {
didSet {
if boldFont {
self.label.font = .boldSystemFont(ofSize: CGFloat(fontSize))
}
else {
self.label.font = .systemFont(ofSize: CGFloat(fontSize))
}
invalidateIntrinsicContentSize()
}
}
override public var intrinsicContentSize: CGSize {
return CGSize(width: label.intrinsicContentSize.height, height: label.intrinsicContentSize.width)
}
override public init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLabel()
}
private func setupLabel() {
addSubview(label)
label.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
}
}
|
mit
|
13d403749ec6e59665b7330697a025f9
| 29.397436 | 158 | 0.631801 | 4.69505 | false | false | false | false |
garygriswold/Bible.js
|
SafeBible2/SafeBible_ios/SafeBible/ViewControllers/ReaderPagesController.swift
|
1
|
8283
|
//
// ReaderPageController.swift
// Settings
//
// Created by Gary Griswold on 10/29/18.
// Copyright © 2018 ShortSands. All rights reserved.
//
import UIKit
import AudioPlayer
class ReaderPagesController : UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
// This event occurs when the TOC or history are used to set this controller to a new page.
static let NEW_REFERENCE = NSNotification.Name("new-reference")
// This event occurs when a web page is loaded.
static let WEB_LOAD_DONE = NSNotification.Name("web-load-done")
// This event occurs when a new bible and language are selected for compare view
static let NEW_COMPARE = NSNotification.Name("new-compare")
//var pageViewController: PageViewController!
var pageViewController: UIPageViewController!
private var readerViewQueue = ReaderViewQueue.shared
private var toolBar: ReaderToolbar!
override var prefersStatusBarHidden: Bool { get { return true } }
override func loadView() {
super.loadView()
self.toolBar = ReaderToolbar(controller: self)
let read = NSLocalizedString("Bible", comment: "Button to return to read Bible")
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: read, style: .plain, target: nil,
action: nil)
NotificationCenter.default.addObserver(self, selector: #selector(loadBiblePage(note:)),
name: ReaderPagesController.NEW_REFERENCE, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(audioChapterChanged(note:)),
name: AudioBibleController.AUDIO_CHAP_CHANGED, object: nil)
// Load the starting page
NotificationCenter.default.post(name: ReaderPagesController.NEW_REFERENCE,
object: HistoryModel.shared.current())
}
@objc func loadBiblePage(note: NSNotification) {
let reference = note.object as! Reference
self.toolBar.loadBiblePage(reference: reference)
if self.pageViewController != nil {
self.pageViewController.view.removeFromSuperview()
self.pageViewController.removeFromParent()
}
//self.pageViewController = PageViewController()
self.pageViewController = UIPageViewController(transitionStyle: .scroll,
navigationOrientation: .horizontal, options: nil)
self.addChild(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.dataSource = self
self.pageViewController.delegate = self
let page1 = self.readerViewQueue.first(reference: reference)
self.pageViewController.setViewControllers([page1], direction: .forward, animated: true, completion: nil)
print("Doing setViewController \(reference.toString())")
self.pageViewController.view.translatesAutoresizingMaskIntoConstraints = false
let margins = self.view.safeAreaLayoutGuide
self.pageViewController.view.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
self.pageViewController.view.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
self.pageViewController.view.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true
self.pageViewController.view.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
// listen for completion of webView set with content in ReaderViewController
NotificationCenter.default.addObserver(self, selector: #selector(setViewControllerComplete),
name: ReaderPagesController.WEB_LOAD_DONE, object: nil)
NotificationCenter.default.post(name: AudioBibleController.TEXT_PAGE_CHANGED, object: nil)
}
@objc func setViewControllerComplete(note: NSNotification) {
self.readerViewQueue.preload()
}
/**
* This method does not work, the second chapter auto scrolled presents blank.
* So, the ability to auto scroll text as audio advances is NOT implemented.
* Fixing this might require some rework in ReaderViewQueue or a custom UIPageViewController
*/
@objc func audioChapterChanged(note: NSNotification) {
if let refString = note.object as? String {
if let reference = Reference.factory(reference: refString) {
HistoryModel.shared.changeReference(reference: reference)
}
}
// This setting of view controller does not work,
// the second chapter auto scrolled presents blank.
// So, the ability to auto scroll text as audio advances is NOT implemented.
// Fixing this might require some rework in ReaderViewQueue or a custom UIPageViewController
//let ref = HistoryModel.shared.current().nextChapter()
//let pageNext = self.readerViewQueue.first(reference: ref)
//self.pageViewController.setViewControllers([pageNext], direction: .forward, animated: true,
// completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.backgroundColor = AppFont.backgroundColor
self.toolBar.refresh()
//let hideNavBar = (AppFont.nightMode) ? false : true
let hideNavBar = true
self.navigationController?.setNavigationBarHidden(hideNavBar, animated: false)
self.navigationController?.isToolbarHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
//
// DataSource
//
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController? {
return self.readerViewQueue.prior(controller: viewController)
}
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController? {
return self.readerViewQueue.next(controller: viewController)
}
// These two methods are part of what is needed for the PageControl
//func presentationCount(for pageViewController: UIPageViewController) -> Int {
// return 7
//}
//func presentationIndex(for pageViewController: UIPageViewController) -> Int {
// return 1
//}
//
// Delegate
//
func pageViewController(_ pageViewController: UIPageViewController,
willTransitionTo pendingViewControllers: [UIViewController]) {
//let page = pendingViewControllers[0] as! ReaderViewController
//print("will Transition To \(page.reference.toString())")
}
func pageViewController(_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
let page = self.pageViewController.viewControllers![0] as! ReaderViewController
print("Display \(page.reference.toString())")
self.toolBar.loadBiblePage(reference: page.reference)
HistoryModel.shared.changeReference(reference: page.reference)
NotificationCenter.default.post(name: AudioBibleController.TEXT_PAGE_CHANGED, object: nil)
}
func pageViewControllerSupportedInterfaceOrientations(_ pageViewController: UIPageViewController) -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
func pageViewControllerPreferredInterfaceOrientationForPresentation(_ pageViewController: UIPageViewController) -> UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
}
|
mit
|
4c25b0b4a5e5db43d8b3b6c295eb5a33
| 46.325714 | 143 | 0.671939 | 5.755386 | false | false | false | false |
glock45/swiftX
|
Source/http/websocket.swift
|
1
|
5413
|
//
// websockets.swift
// swiftx
//
// Copyright © 2016 kolakowski. All rights reserved.
//
import Foundation
public enum WebSocketError: Error {
case unknownOpCode(String)
case unMaskedFrame
case notImplemented(String)
}
public enum WebsocketEvent {
case disconnected(Int, String)
case text(String)
case binary([UInt8])
}
public class WebsocketResponse: Response {
public init(_ request: Request, _ closure: @escaping ((WebsocketEvent) -> Void)) {
super.init()
guard request.hasToken("websocket", forHeader: "upgrade") else {
self.status = Status.badRequest.rawValue
self.body = [UInt8](("Invalid value of 'Upgrade' header.").utf8)
return
}
guard request.hasToken("upgrade", forHeader: "connection") else {
self.status = Status.badRequest.rawValue
self.body = [UInt8](("Invalid value of 'Connection' header.").utf8)
return
}
guard let (_, secWebSocketKey) = request.headers.filter({ $0.0 == "sec-websocket-key" }).first else {
self.status = Status.badRequest.rawValue
self.body = [UInt8](("Invalid value of 'Sec-Websocket-Key' header.").utf8)
return
}
let secWebSocketAccept = String.toBase64((secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").sha1())
self.status = Status.switchingProtocols.rawValue
self.headers = [ ("Upgrade", "WebSocket"), ("Connection", "Upgrade"), ("Sec-WebSocket-Accept", secWebSocketAccept)]
self.processingSuccesor = WebsocketDataPorcessor(WebsocketFramesProcessor(closure))
}
}
public class WebSocketFrame {
public enum OpCode: UInt8 {
case `continue` = 0x00
case close = 0x08
case ping = 0x09
case pong = 0x0A
case text = 0x01
case binary = 0x02
}
public init(_ opcode: OpCode, _ payload: [UInt8]) {
self.opcode = opcode
self.payload = payload
}
public let opcode: OpCode
public let payload: [UInt8]
}
public class WebsocketFramesProcessor {
private let closure: ((WebsocketEvent) -> Void)
public init(_ closure: @escaping ((WebsocketEvent) -> Void)) {
self.closure = closure
}
public func process(_ frame: WebSocketFrame) throws {
switch frame.opcode {
case .text:
if let text = String(bytes: frame.payload, encoding: .utf8) {
self.closure(.text(text))
} else {
print("Invalid payload (not utf8): \(frame.payload)")
}
case .binary:
self.closure(.binary(frame.payload))
default:
throw WebSocketError.notImplemented("Not able to handle: \(frame.opcode.rawValue)")
}
}
}
public class WebsocketDataPorcessor: IncomingDataProcessor {
private let framesProcessor: WebsocketFramesProcessor
public init(_ framesProcessor: WebsocketFramesProcessor) {
self.framesProcessor = framesProcessor
}
private var stack = [UInt8]()
public func process(_ chunk: ArraySlice<UInt8>) throws {
stack.append(contentsOf: chunk)
guard stack.count > 1 else { return }
_ = stack[0] & 0x80 != 0
let opc = stack[0] & 0x0F
guard let opcode = WebSocketFrame.OpCode(rawValue: opc) else {
// "If an unknown opcode is received, the receiving endpoint MUST _Fail the WebSocket Connection_."
// http://tools.ietf.org/html/rfc6455#section-5.2 ( Page 29 )
throw WebSocketError.unknownOpCode("\(opc)")
}
let msk = stack[1] & 0x80 != 0
guard msk else {
// "...a client MUST mask all frames that it sends to the serve.."
// http://tools.ietf.org/html/rfc6455#section-5.1
throw WebSocketError.unMaskedFrame
}
var len = UInt64(stack[1] & 0x7F)
var offset = 2
if len == 0x7E {
guard stack.count > 3 else { return }
let b0 = UInt64(stack[2])
let b1 = UInt64(stack[3])
len = UInt64(littleEndian: b0 << 8 | b1)
offset = 4
} else if len == 0x7F {
guard stack.count > 9 else { return }
let b0 = UInt64(stack[2])
let b1 = UInt64(stack[3])
let b2 = UInt64(stack[4])
let b3 = UInt64(stack[5])
let b4 = UInt64(stack[6])
let b5 = UInt64(stack[7])
let b6 = UInt64(stack[8])
let b7 = UInt64(stack[9])
len = UInt64(littleEndian: b0 << 54 | b1 << 48 | b2 << 40 | b3 << 32 | b4 << 24 | b5 << 16 | b6 << 8 | b7)
offset = 10
}
guard (len + UInt64(offset) + 4) >= UInt64(stack.count) else {
return
}
let mask = [stack[offset], stack[offset+1], stack[offset+2], stack[offset+3]]
offset = offset + mask.count
let payload = stack[offset..<(offset + Int(len /* //TODO fix this */))].enumerated().map { $0.element ^ mask[Int($0.offset % 4)] }
stack.removeFirst(offset+Int(len))
try framesProcessor.process(WebSocketFrame(opcode, payload))
}
}
|
bsd-3-clause
|
5c575ad18f850a42e2f8d8fd81f0d2f8
| 31.023669 | 138 | 0.56116 | 4.118721 | false | false | false | false |
uacaps/PageMenu
|
Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/RecentsTableViewController.swift
|
4
|
3257
|
//
// RecentsTableViewController.swift
// PageMenuDemoTabbar
//
// Created by Niklas Fahl on 1/9/15.
// Copyright (c) 2015 Niklas Fahl. All rights reserved.
//
import UIKit
class RecentsTableViewController: UITableViewController {
var namesArray : [String] = ["Kim White", "Kim White", "David Fletcher", "Anna Hunt", "Timothy Jones", "Timothy Jones", "Timothy Jones", "Lauren Richard", "Lauren Richard", "Juan Rodriguez"]
var photoNameArray : [String] = ["woman1.jpg", "woman1.jpg", "man8.jpg", "woman3.jpg", "man3.jpg", "man3.jpg", "man3.jpg", "woman5.jpg", "woman5.jpg", "man5.jpg"]
var activityTypeArray : NSArray = [0, 1, 1, 0, 2, 1, 2, 0, 0, 2]
var dateArray : NSArray = ["4:22 PM", "Wednesday", "Tuesday", "Sunday", "01/02/15", "12/31/14", "12/28/14", "12/24/14", "12/17/14", "12/14/14"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: "RecentsTableViewCell", bundle: nil), forCellReuseIdentifier: "RecentsTableViewCell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("recents page: viewWillAppear")
}
override func viewDidAppear(_ animated: Bool) {
self.tableView.showsVerticalScrollIndicator = false
super.viewDidAppear(animated)
self.tableView.showsVerticalScrollIndicator = true
// println("recents page: viewDidAppear")
}
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 {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : RecentsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RecentsTableViewCell") as! RecentsTableViewCell
// Configure the cell...
cell.nameLabel.text = namesArray[indexPath.row]
cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row])
cell.dateLabel.text = dateArray[indexPath.row] as! NSString as String
cell.nameLabel.textColor = UIColor(red: 85.0/255.0, green: 85.0/255.0, blue: 85.0/255.0, alpha: 1.0)
if activityTypeArray[indexPath.row] as! Int == 0 {
cell.activityImageView.image = UIImage(named: "phone_send")
} else if activityTypeArray[indexPath.row] as! Int == 1 {
cell.activityImageView.image = UIImage(named: "phone_receive")
} else {
cell.activityImageView.image = UIImage(named: "phone_down")
cell.nameLabel.textColor = UIColor.red
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 94.0
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
}
|
bsd-3-clause
|
d4987f2f37f9c35bca7604a7aae8f1c0
| 39.7125 | 194 | 0.647528 | 4.308201 | false | false | false | false |
thebookofleaves/ZhiHuDaily
|
ZhiHuDaily/ZhiHuDaily/HomeViewController.swift
|
3
|
3288
|
//
// HomeViewController.swift
// ZhiHuDaily
//
// Created by Cocoa Lee on 15/7/5.
// Copyright (c) 2015年 Cocoa Lee. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getLunchImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getLunchImage(){
let lunchImageView = UIImageView(frame: view.bounds);
lunchImageView.backgroundColor = UIColor ( red: 0.7488, green: 0.9865, blue: 0.6194, alpha: 1.0 )
view.addSubview(lunchImageView)
let urlString = "http://pic3.zhimg.com/d7f7dd90c013b1f115997047b8a6d5fe.jpg"
if let url = NSURL(string: urlString){
// 利用URL创建session
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let dataTask = session.dataTaskWithURL(url, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if data == nil{
println("获取数据失败")
lunchImageView.image = nil
}else
{
println("获取数据成功")
lunchImageView.image = UIImage(data: data!)
// self.saveLunchImage(data!)
}
})
dataTask.resume()
}
}
func saveLunchImage(imageData : NSData)->(){
let home = NSHomeDirectory() as String
let docPath = home.stringByAppendingPathComponent("Documents") as String
let filepath = docPath.stringByAppendingPathComponent("lunchImageData.data")
NSKeyedArchiver.archivedDataWithRootObject(imageData)
self.readLunchImageData()
}
func readLunchImageData(){
let home = NSHomeDirectory() as String
let docPath = home.stringByAppendingPathComponent("Documents") as String
let filepath = docPath.stringByAppendingPathComponent("lunchImageData.data")
// let data: AnyObject? = NSData.dataWithContentsOfMappedFile(filepath)
let dd = NSData(contentsOfFile: filepath)
println("data :\(dd)")
let imgv = UIImageView(image: UIImage(data: dd!))
imgv.frame = CGRect(x: 10, y: 10, width: 100, height: 100);
view.addSubview(imgv)
}
override func viewWillAppear(animated: Bool) {
navigationController?.navigationBarHidden = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
eed22a20f8cf8f627424c3c22a2ae91e
| 29.411215 | 143 | 0.584511 | 5.291057 | false | false | false | false |
mottx/XCGLogger
|
Sources/XCGLogger/LogFormatters/PrePostFixLogFormatter.swift
|
8
|
3212
|
//
// PrePostFixLogFormatter.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2016-09-20.
// Copyright © 2016 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
#if os(macOS)
import AppKit
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
// MARK: - PrePostFixLogFormatter
/// A log formatter that will optionally add a prefix, and/or postfix string to a message
open class PrePostFixLogFormatter: LogFormatterProtocol, CustomDebugStringConvertible {
/// Internal cache of the prefix strings for each log level
internal var prefixStrings: [XCGLogger.Level: String] = [:]
/// Internal cache of the postfix strings codes for each log level
internal var postfixStrings: [XCGLogger.Level: String] = [:]
public init() {
}
/// Set the prefix/postfix strings for a specific log level.
///
/// - Parameters:
/// - prefix: A string to prepend to log messages.
/// - postfix: A string to postpend to log messages.
/// - level: The log level.
///
/// - Returns: Nothing
///
open func apply(prefix: String? = nil, postfix: String? = nil, to level: XCGLogger.Level? = nil) {
guard let level = level else {
guard prefix != nil || postfix != nil else { clearFormatting(); return }
// No level specified, so, apply to all levels
for level in XCGLogger.Level.all {
self.apply(prefix: prefix, postfix: postfix, to: level)
}
return
}
if let prefix = prefix {
prefixStrings[level] = prefix
}
else {
prefixStrings.removeValue(forKey: level)
}
if let postfix = postfix {
postfixStrings[level] = postfix
}
else {
postfixStrings.removeValue(forKey: level)
}
}
/// Clear all previously set colours. (Sets each log level back to default)
///
/// - Parameters: None
///
/// - Returns: Nothing
///
open func clearFormatting() {
prefixStrings = [:]
postfixStrings = [:]
}
// MARK: - LogFormatterProtocol
/// Apply some additional formatting to the message if appropriate.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Formatted/processed message ready for output.
///
/// - Returns: message with the additional formatting
///
@discardableResult open func format(logDetails: inout LogDetails, message: inout String) -> String {
message = "\(prefixStrings[logDetails.level] ?? "")\(message)\(postfixStrings[logDetails.level] ?? "")"
return message
}
// MARK: - CustomDebugStringConvertible
open var debugDescription: String {
get {
var description: String = "\(extractTypeName(self)): "
for level in XCGLogger.Level.all {
description += "\n\t- \(level) > \(prefixStrings[level] ?? "None") | \(postfixStrings[level] ?? "None")"
}
return description
}
}
}
|
mit
|
a6dc2f4cf5ce055245d7eee9495b4dfa
| 31.11 | 120 | 0.59701 | 4.567568 | false | false | false | false |
bignerdranch/Deferred
|
Sources/Deferred/DeferredQueue.swift
|
1
|
3002
|
//
// DeferredQueue.swift
// Deferred
//
// Created by Zachary Waldowski on 2/22/18.
// Copyright © 2018 Big Nerd Ranch. Licensed under MIT.
//
extension Deferred {
/// Heap storage acting as a linked list node of continuations.
///
/// The use of `ManagedBuffer` ensures aligned and heap-allocated addresses
/// for the storage. The storage is tail-allocated with a reference to the
/// next node.
final class Node: ManagedBuffer<Node?, Continuation> {
static func create(with continuation: Continuation) -> Node {
let storage = super.create(minimumCapacity: 1, makingHeaderWith: { _ in nil })
storage.withUnsafeMutablePointers { (_, pointerToContinuation) in
pointerToContinuation.initialize(to: continuation)
}
return unsafeDowncast(storage, to: Node.self)
}
deinit {
_ = withUnsafeMutablePointers { (_, pointerToContinuation) in
pointerToContinuation.deinitialize(count: 1)
}
}
}
/// A singly-linked list of continuations to be submitted after fill.
///
/// A multi-producer, single-consumer atomic queue a la `DispatchGroup`:
/// <https://github.com/apple/swift-corelibs-libdispatch/blob/master/src/semaphore.c>.
struct Queue {
fileprivate(set) var head: Node?
fileprivate(set) var tail: Node?
}
}
private extension Deferred.Node {
/// The next node in the linked list.
///
/// - warning: To alleviate data races, the next node is loaded
/// unconditionally. `self` must have been checked not to be the tail.
var next: Deferred.Node {
get {
return withUnsafeMutablePointers { (target, _) in
bnr_atomic_load_and_wait(target)
}
}
set {
_ = withUnsafeMutablePointers { (target, _) in
bnr_atomic_store(target, newValue, .relaxed)
}
}
}
func execute(with value: Value) {
withUnsafeMutablePointers { (_, pointerToContinuation) in
pointerToContinuation.pointee.execute(with: value)
}
}
}
extension Deferred {
static func drain(from target: UnsafeMutablePointer<Queue>, continuingWith value: Value) {
var head = bnr_atomic_store(&target.pointee.head, nil, .relaxed)
let tail = head != nil ? bnr_atomic_store(&target.pointee.tail, nil, .release) : nil
while let current = head {
head = current !== tail ? current.next : nil
current.execute(with: value)
}
}
static func push(_ continuation: Continuation, to target: UnsafeMutablePointer<Queue>) -> Bool {
let node = Node.create(with: continuation)
if let tail = bnr_atomic_store(&target.pointee.tail, node, .release) {
tail.next = node
return false
}
_ = bnr_atomic_store(&target.pointee.head, node, .seq_cst)
return true
}
}
|
mit
|
6533d7ed07b9fce8ed4f4ca65d7f239d
| 32.344444 | 100 | 0.610796 | 4.506006 | false | false | false | false |
pauldardeau/tataille-swift
|
tataille-swift/AppDelegate.swift
|
1
|
17031
|
//
// AppDelegate.swift
// tataille-swift
//
// Created by Paul Dardeau on 8/1/14.
// Copyright (c) 2014 SwampBits. All rights reserved.
// BSD license
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow?
let TOP: CGFloat = 25
let COMBO_HEIGHT: CGFloat = 26.0
let WINDOW_WIDTH: CGFloat = 600.0
let WINDOW_HEIGHT: CGFloat = 500.0
let BUTTON_WIDTH: CGFloat = 120.0
let BUTTON_HEIGHT: CGFloat = 44.0
let LABEL_HEIGHT: CGFloat = 30.0
let LEFT_EDGE: CGFloat = 25.0
let LBL_CUSTOMER_WIDTH: CGFloat = 65.0
let EF_CUSTOMER_WIDTH: CGFloat = 200.0
let EF_CUSTOMER_HEIGHT: CGFloat = 24.0
let CK_DELIVERY_WIDTH: CGFloat = 100.0
let CK_DELIVERY_HEIGHT: CGFloat = 30.0
let CK_RUSH_WIDTH: CGFloat = 100.0
let CK_RUSH_HEIGHT: CGFloat = 30.0
let LIST_WIDTH: CGFloat = 130.0
let LIST_HEIGHT: CGFloat = 270.0
let LISTVIEW_WIDTH: CGFloat = 325.0
let LBL_ORDERTOTAL_WIDTH: CGFloat = 65.0
let VALUES_DELIMITER = ","
let PAYMENT_METHOD_VALUES = "Cash,Amex,Discover,MasterCard,Visa"
var displayEngine: CocoaDisplayEngine?
var cidCustomerLabel: ControlId?
var cidEntryField: ControlId?
var cidCheckDelivery: ControlId?
var cidCheckRush: ControlId?
var cidComboPayment: ControlId?
var cidListBox: ControlId?
var cidListView: ControlId?
var cidAddButton: ControlId?
var cidRemoveButton: ControlId?
var cidOrderButton: ControlId?
var cidOrderTotal: ControlId?
var listMenuItems = [String]()
var menuItems = ""
var listPaymentMethods: [String]!
var paymentMethod: String!
var isDelivery: Bool = false
var isRushOrder: Bool = false
var selectedMenuItemIndex = -1
var selectedOrderItemIndex = -1
var menu = Dictionary<String, Double>()
var listOrderItems = Array<OrderItem>()
var orderTotal = 0.00
//**************************************************************************
func addMenuItem(item: String, price: Double) {
self.menu[item] = price
self.listMenuItems.append(item)
if countElements(self.menuItems) > 0 {
self.menuItems += ","
}
self.menuItems += item
}
//**************************************************************************
func applicationDidFinishLaunching(aNotification: NSNotification?) {
self.displayEngine = CocoaDisplayEngine(mainWindow:self.window!)
// set up our menu
self.addMenuItem("Cheeseburger", price:4.25)
self.addMenuItem("Chips", price:2.00)
self.addMenuItem("Drink", price:1.75)
self.addMenuItem("French Fries", price:2.25)
self.addMenuItem("Grilled Cheese", price:3.75)
self.addMenuItem("Hamburger", price:4.00)
self.addMenuItem("Hot Dog", price:3.00)
self.addMenuItem("Peanuts", price:2.00)
self.listPaymentMethods = PAYMENT_METHOD_VALUES.componentsSeparatedByString(",")
self.startApp(self.displayEngine!);
}
//**************************************************************************
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
//**************************************************************************
//**************************************************************************
class PaymentMethodHandler : ComboBoxHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func combBoxItemSelected(itemIndex: Int) {
if let listMethods = self.appDelegate.listPaymentMethods {
self.appDelegate.paymentMethod = listMethods[itemIndex]
}
}
}
//**************************************************************************
//**************************************************************************
class RushCheckBoxHandler : CheckBoxHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func checkBoxToggled(isChecked: Bool) {
self.appDelegate.isRushOrder = isChecked
}
}
//**************************************************************************
//**************************************************************************
class DeliveryCheckBoxHandler : CheckBoxHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func checkBoxToggled(isChecked: Bool) {
self.appDelegate.isDelivery = isChecked
}
}
//**************************************************************************
//**************************************************************************
class AddPushButtonHandler : PushButtonHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func pushButtonClicked() {
self.appDelegate.onAddClicked()
}
}
//**************************************************************************
//**************************************************************************
class RemovePushButtonHandler : PushButtonHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func pushButtonClicked() {
self.appDelegate.onRemoveClicked()
}
}
//**************************************************************************
//**************************************************************************
class OrderPushButtonHandler : PushButtonHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func pushButtonClicked() {
self.appDelegate.onOrderClicked()
}
}
//**************************************************************************
//**************************************************************************
class ListMenuSelectionHandler : ListBoxHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func listBoxItemSelected(itemIndex: Int) {
self.appDelegate.onListMenuSelection(itemIndex)
}
}
//**************************************************************************
//**************************************************************************
class OrderListViewHandler : ListViewHandler {
var appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
func listViewRowSelected(rowIndex: Int) {
self.appDelegate.onListViewOrderRowSelection(rowIndex)
}
}
//**************************************************************************
//**************************************************************************
func onListMenuSelection(itemIndex: Int) {
self.selectedMenuItemIndex = itemIndex
var buttonEnabled = true
if itemIndex == -1 {
buttonEnabled = false
}
self.displayEngine!.setEnabled(buttonEnabled, cid:self.cidAddButton!)
}
//**************************************************************************
func onListViewOrderRowSelection(itemIndex: Int) {
println("order item selected: \(itemIndex)")
self.selectedOrderItemIndex = itemIndex
var buttonEnabled = true
if itemIndex == -1 {
buttonEnabled = false
}
self.displayEngine!.setEnabled(buttonEnabled, cid:self.cidRemoveButton!)
}
//**************************************************************************
func onAddClicked() {
if let cidMenu = self.cidListBox {
if let cidOrderItems = self.cidListView {
let selectedMenuItem = self.listMenuItems[self.selectedMenuItemIndex]
let orderItem = OrderItem()
orderItem.quantity = 1
orderItem.itemName = selectedMenuItem
orderItem.itemPrice = self.menu[selectedMenuItem]!
self.listOrderItems.append(orderItem)
let itemPriceAsString = NSString(format:"%.2f", orderItem.itemPrice)
self.displayEngine!.addRow("\(orderItem.quantity),\(selectedMenuItem),\(itemPriceAsString)", cid:self.cidListView!)
self.orderTotal += orderItem.itemPrice
let orderTotalString = NSString(format:"%.2f", self.orderTotal)
self.displayEngine!.setStaticText(orderTotalString, cid: self.cidOrderTotal!)
if self.listOrderItems.count == 1 {
self.displayEngine!.enableControl(self.cidOrderButton!)
}
}
}
}
//**************************************************************************
func onRemoveClicked() {
if self.selectedOrderItemIndex > -1 {
let item = self.listOrderItems[self.selectedOrderItemIndex]
self.orderTotal -= item.itemPrice
let orderTotalString = NSString(format:"%.2f", self.orderTotal)
self.displayEngine!.setStaticText(orderTotalString, cid: self.cidOrderTotal!)
self.listOrderItems.removeAtIndex(self.selectedOrderItemIndex)
self.displayEngine!.removeRow(self.selectedOrderItemIndex, cid: self.cidListView!)
self.selectedOrderItemIndex = -1
self.displayEngine!.disableControl(self.cidRemoveButton!)
if self.listOrderItems.isEmpty {
self.displayEngine!.disableControl(self.cidOrderButton!)
}
}
}
//**************************************************************************
func onOrderClicked() {
let numberItems = self.listOrderItems.count
let orderTotalString = NSString(format:"%.2f", self.orderTotal)
let orderAlert = NSAlert()
orderAlert.messageText = "Order Confirmation"
orderAlert.informativeText = "\(numberItems) items for total: $ \(orderTotalString)"
orderAlert.runModal()
// clear out app for next order
self.orderTotal = 0.00
self.listOrderItems.removeAll(keepCapacity: true)
self.displayEngine!.removeAllRows(self.cidListView!)
self.displayEngine!.setStaticText("0.00", cid: self.cidOrderTotal!)
self.displayEngine!.disableControl(self.cidOrderButton!)
}
//**************************************************************************
func startApp(de: CocoaDisplayEngine) {
let LBL_CUSTOMER_HEIGHT = LABEL_HEIGHT
let LISTVIEW_HEIGHT = LIST_HEIGHT
let BTN_ADD_WIDTH = BUTTON_WIDTH
let BTN_ADD_HEIGHT = BUTTON_HEIGHT
let BTN_REMOVE_WIDTH = BUTTON_WIDTH
let BTN_REMOVE_HEIGHT = BUTTON_HEIGHT
let BTN_ORDER_WIDTH = BUTTON_WIDTH
let BTN_ORDER_HEIGHT = BUTTON_HEIGHT
let LBL_ORDERTOTAL_HEIGHT = LABEL_HEIGHT
let windowId: Int = 0 //DisplayEngine.ID_MAIN_WINDOW
var ci: ControlInfo
var controlId = 1
var x = LEFT_EDGE
var y = TOP
var topRowText = y + 4
self.cidCustomerLabel = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidCustomerLabel!)
ci.rect = NSMakeRect(x, topRowText, LBL_CUSTOMER_WIDTH, LBL_CUSTOMER_HEIGHT)
ci.text = "Customer:"
de.createStaticText(ci)
x += LBL_CUSTOMER_WIDTH
x += 10
self.cidEntryField = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidEntryField!)
ci.rect = NSMakeRect(x, y, EF_CUSTOMER_WIDTH, EF_CUSTOMER_HEIGHT)
de.createEntryField(ci)
x += EF_CUSTOMER_WIDTH
x += 20
self.cidCheckDelivery = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidCheckDelivery!)
ci.rect = NSMakeRect(x, y - 3, CK_DELIVERY_WIDTH, CK_DELIVERY_HEIGHT)
ci.text = "Delivery"
ci.helpCaption = "check if this order is for delivery"
de.createCheckBox(ci)
de.setCheckBoxHandler(DeliveryCheckBoxHandler(appDelegate: self), cid: self.cidCheckDelivery!)
x += CK_DELIVERY_WIDTH
x += 20
self.cidCheckRush = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidCheckRush!)
ci.rect = NSMakeRect(x, y - 3, CK_RUSH_WIDTH, CK_RUSH_HEIGHT)
ci.text = "Rush"
ci.helpCaption = "check if this is a rush order"
de.createCheckBox(ci)
de.setCheckBoxHandler(RushCheckBoxHandler(appDelegate: self), cid: self.cidCheckRush!)
x += CK_RUSH_WIDTH
x += 15
let cidTotalLabel = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:cidTotalLabel)
let w: CGFloat = 50.0
ci.rect = NSMakeRect(x, topRowText, w, LBL_ORDERTOTAL_HEIGHT)
ci.text = "Total: $ "
de.createStaticText(ci)
x += w
self.cidOrderTotal = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidOrderTotal!)
ci.rect = NSMakeRect(x, topRowText, LBL_ORDERTOTAL_WIDTH, LBL_ORDERTOTAL_HEIGHT)
ci.text = "0.00"
ci.helpCaption = "total cost of order"
de.createStaticText(ci)
x = LEFT_EDGE
y += EF_CUSTOMER_HEIGHT
y += 15
self.cidComboPayment = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidComboPayment!)
ci.rect = NSMakeRect(x, y, 120, COMBO_HEIGHT)
ci.values = PAYMENT_METHOD_VALUES
ci.helpCaption = "method of payment"
de.createComboBox(ci)
de.setComboBoxHandler(PaymentMethodHandler(appDelegate: self), cid: self.cidComboPayment!)
y += COMBO_HEIGHT
y += 12
self.cidListBox = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidListBox!)
ci.rect = NSMakeRect(x, y, LIST_WIDTH, LIST_HEIGHT)
ci.values = self.menuItems
ci.valuesDelimiter = VALUES_DELIMITER
ci.helpCaption = "list of items available for order"
de.createListBox(ci)
de.setListBoxHandler(ListMenuSelectionHandler(appDelegate: self), cid: self.cidListBox!)
x += LIST_WIDTH
x += 30
self.cidListView = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidListView!)
ci.rect = NSMakeRect(x, y, LISTVIEW_WIDTH, LISTVIEW_HEIGHT)
ci.text = "Group"
ci.values = "Qty,Item,Price"
ci.valuesDelimiter = VALUES_DELIMITER
ci.helpCaption = "list of items on order"
de.createListView(ci)
de.setListViewHandler(OrderListViewHandler(appDelegate: self), cid: self.cidListView!)
y += LISTVIEW_HEIGHT
y += 30
x = LEFT_EDGE
self.cidAddButton = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidAddButton!)
ci.rect = NSMakeRect(x, y, BTN_ADD_WIDTH, BTN_ADD_HEIGHT)
ci.text = "Add Item"
ci.isEnabled = false;
de.createPushButton(ci)
de.setPushButtonHandler(AddPushButtonHandler(appDelegate: self), cid: self.cidAddButton!)
x += LIST_WIDTH
x += 30
self.cidRemoveButton = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidRemoveButton!)
ci.rect = NSMakeRect(x, y, BTN_REMOVE_WIDTH, BTN_REMOVE_HEIGHT)
ci.text = "Remove Item"
ci.isEnabled = false
de.createPushButton(ci)
de.setPushButtonHandler(RemovePushButtonHandler(appDelegate: self), cid: self.cidRemoveButton!)
x += 150
self.cidOrderButton = ControlId(windowId:windowId, controlId:controlId++)
ci = ControlInfo(cid:self.cidOrderButton!)
ci.rect = NSMakeRect(x, y, BTN_ORDER_WIDTH, BTN_ORDER_HEIGHT)
ci.text = "Place Order"
ci.isEnabled = false
de.createPushButton(ci)
de.setPushButtonHandler(OrderPushButtonHandler(appDelegate: self), cid: self.cidOrderButton!)
}
//**************************************************************************
}
|
bsd-3-clause
|
6464d268caa9b0e1a431bfaf22e59f6e
| 35.468951 | 131 | 0.540368 | 4.842479 | false | false | false | false |
SusanDoggie/Doggie
|
Sources/DoggieGraphics/ImageCodec/Decoder/APNGDecoder.swift
|
1
|
14499
|
//
// APNGDecoder.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension PNGDecoder {
class Frame {
let lck = NSLock()
let prev_frame: Frame?
let chunks: [PNGChunk]
let ihdr: IHDR
let fctl: FrameControlChunk
let data: Data
var decoded: AnyImage?
init(prev_frame: Frame?, chunks: [PNGChunk], ihdr: IHDR, fctl: FrameControlChunk, data: Data) {
self.prev_frame = prev_frame
self.chunks = chunks
self.ihdr = ihdr
self.fctl = fctl
self.data = data
}
}
}
extension PNGDecoder {
struct AnimationControlChunk {
var num_frames: BEUInt32
var num_plays: BEUInt32
init(data: Data) {
self.num_frames = data.load(as: BEUInt32.self)
self.num_plays = data.load(fromByteOffset: 4, as: BEUInt32.self)
}
}
struct FrameControlChunk {
var sequence_number: BEUInt32
var width: BEUInt32
var height: BEUInt32
var x_offset: BEUInt32
var y_offset: BEUInt32
var delay_num: BEUInt16
var delay_den: BEUInt16
var dispose_op: UInt8
var blend_op: UInt8
init(data: Data) {
self.sequence_number = data.load(as: BEUInt32.self)
self.width = data.load(fromByteOffset: 4, as: BEUInt32.self)
self.height = data.load(fromByteOffset: 8, as: BEUInt32.self)
self.x_offset = data.load(fromByteOffset: 12, as: BEUInt32.self)
self.y_offset = data.load(fromByteOffset: 16, as: BEUInt32.self)
self.delay_num = data.load(fromByteOffset: 20, as: BEUInt16.self)
self.delay_den = data.load(fromByteOffset: 22, as: BEUInt16.self)
self.dispose_op = data.load(fromByteOffset: 24, as: UInt8.self)
self.blend_op = data.load(fromByteOffset: 25, as: UInt8.self)
}
var region: PNGRegion {
return PNGRegion(x: Int(x_offset), y: Int(y_offset), width: Int(width), height: Int(height))
}
}
struct FrameDataChunk {
var sequence_number: BEUInt32
var data: Data
init(data: Data) {
self.sequence_number = data.load(as: BEUInt32.self)
self.data = data.dropFirst(4)
}
}
mutating func resolve_frames() {
var actl: AnimationControlChunk?
var frames: [Frame] = []
var fctl: FrameControlChunk?
var data = Data()
var last_sequence_number: Int = -1
for chunk in chunks {
switch chunk.signature {
case "acTL":
guard actl == nil, chunk.data.count >= 8 else { return }
actl = AnimationControlChunk(data: chunk.data)
case "fcTL":
guard actl != nil else { return }
guard chunk.data.count >= 26 else { return }
if let _fctl = fctl {
frames.append(Frame(prev_frame: frames.last, chunks: chunks, ihdr: ihdr, fctl: _fctl, data: data))
data = Data()
}
let _fctl = FrameControlChunk(data: chunk.data)
fctl = _fctl
guard last_sequence_number < _fctl.sequence_number else { return }
last_sequence_number = Int(_fctl.sequence_number)
case "IDAT":
guard actl != nil else { return }
guard let fctl = fctl else { break }
guard fctl.x_offset == 0 && fctl.y_offset == 0 && fctl.width == ihdr.width && fctl.height == ihdr.height else { return }
guard frames.last == nil else { return }
data = self.idat
case "fdAT":
guard actl != nil, fctl != nil else { return }
guard chunk.data.count >= 4 else { return }
let data_chunk = FrameDataChunk(data: chunk.data)
data.append(data_chunk.data)
guard last_sequence_number < data_chunk.sequence_number else { return }
last_sequence_number = Int(data_chunk.sequence_number)
default: break
}
}
guard let _fctl = fctl else { return }
frames.append(Frame(prev_frame: frames.last, chunks: chunks, ihdr: ihdr, fctl: _fctl, data: data))
guard let num_frames = actl?.num_frames, num_frames == frames.count else { return }
self.actl = actl
self.frames = frames
}
}
extension PNGDecoder {
var isAnimated: Bool {
return actl != nil
}
var repeats: Int {
return actl.map { Int($0.num_plays) } ?? 0
}
var numberOfPages: Int {
return actl == nil ? 1 : frames.count
}
func page(_ index: Int) -> ImageRepBase {
precondition(actl != nil || index == 0, "Index out of range.")
return actl == nil ? self : frames[index]
}
}
extension PNGDecoder.Frame: ImageRepBase {
var width: Int {
return Int(ihdr.width)
}
var height: Int {
return Int(ihdr.height)
}
var resolution: Resolution {
return _png_resolution(chunks: chunks)
}
var colorSpace: AnyColorSpace {
return _png_colorspace(ihdr: ihdr, chunks: chunks)
}
var duration: Double {
return Double(fctl.delay_num) / Double(fctl.delay_den == 0 ? 100 : fctl.delay_den)
}
var _empty_image: AnyImage {
return _png_image(ihdr: ihdr, chunks: chunks, width: width, height: height, data: nil, fileBacked: false)
}
var is_full_frame: Bool {
return fctl.x_offset == 0 && fctl.y_offset == 0 && fctl.width == ihdr.width && fctl.height == ihdr.height
}
var is_key_frame: Bool {
guard let prev_frame = prev_frame else { return true }
if fctl.blend_op == 0 && is_full_frame {
return true
}
if prev_frame.fctl.dispose_op == 1 {
return prev_frame.is_full_frame
}
return false
}
var _disposed: AnyImage {
switch fctl.dispose_op {
case 0: return _image
case 1: return _png_clear(fctl.region, _image)
case 2: return prev_frame?._disposed ?? _empty_image
default: return _empty_image
}
}
var _image: AnyImage {
self.lck.lock()
defer { self.lck.unlock() }
if let decoded = self.decoded { return decoded }
let width = Int(fctl.width)
let height = Int(fctl.height)
let current_frame = _png_image(ihdr: ihdr, chunks: chunks, width: width, height: height, data: data, fileBacked: false)
let prev_image: AnyImage
if is_key_frame {
if is_full_frame {
return current_frame
}
prev_image = _empty_image
} else {
prev_image = prev_frame?._disposed ?? _empty_image
}
var decoded: AnyImage
switch fctl.blend_op {
case 0: decoded = _png_copy(fctl.region, prev_image, current_frame)
case 1: decoded = _png_blend(fctl.region, prev_image, current_frame)
default: decoded = _empty_image
}
decoded.fileBacked = true
self.decoded = decoded
return decoded
}
func image(fileBacked: Bool) -> AnyImage {
var image = _image
image.fileBacked = fileBacked
return image
}
}
func _png_clear(_ region: PNGRegion, _ image: AnyImage) -> AnyImage {
switch image.base {
case let image as Image<Gray16ColorPixel>: return AnyImage(_png_clear(region, image))
case let image as Image<Gray32ColorPixel>: return AnyImage(_png_clear(region, image))
case let image as Image<RGBA32ColorPixel>: return AnyImage(_png_clear(region, image))
case let image as Image<RGBA64ColorPixel>: return AnyImage(_png_clear(region, image))
default: fatalError()
}
}
func _png_copy(_ region: PNGRegion, _ prev_image: AnyImage, _ image: AnyImage) -> AnyImage {
switch (prev_image.base, image.base) {
case let (prev_image, image) as (Image<Gray16ColorPixel>, Image<Gray16ColorPixel>): return AnyImage(_png_copy(region, prev_image, image))
case let (prev_image, image) as (Image<Gray32ColorPixel>, Image<Gray32ColorPixel>): return AnyImage(_png_copy(region, prev_image, image))
case let (prev_image, image) as (Image<RGBA32ColorPixel>, Image<RGBA32ColorPixel>): return AnyImage(_png_copy(region, prev_image, image))
case let (prev_image, image) as (Image<RGBA64ColorPixel>, Image<RGBA64ColorPixel>): return AnyImage(_png_copy(region, prev_image, image))
default: fatalError()
}
}
func _png_blend(_ region: PNGRegion, _ prev_image: AnyImage, _ image: AnyImage) -> AnyImage {
switch (prev_image.base, image.base) {
case let (prev_image, image) as (Image<Gray16ColorPixel>, Image<Gray16ColorPixel>): return AnyImage(_png_blend(region, prev_image, image))
case let (prev_image, image) as (Image<Gray32ColorPixel>, Image<Gray32ColorPixel>): return AnyImage(_png_blend(region, prev_image, image))
case let (prev_image, image) as (Image<RGBA32ColorPixel>, Image<RGBA32ColorPixel>): return AnyImage(_png_blend(region, prev_image, image))
case let (prev_image, image) as (Image<RGBA64ColorPixel>, Image<RGBA64ColorPixel>): return AnyImage(_png_blend(region, prev_image, image))
default: fatalError()
}
}
func _png_clear<P>(_ region: PNGRegion, _ image: Image<P>) -> Image<P> {
var image = image
let image_width = image.width
let x = max(0, region.x)
let y = max(0, region.y)
let width = max(0, min(region.width + region.x, image.width) - x)
let height = max(0, min(region.height + region.y, image.height) - y)
guard width != 0 && height != 0 else { return image }
image.withUnsafeMutableBufferPointer {
guard var pixels = $0.baseAddress else { return }
pixels += x + y * image_width
for _ in 0..<height {
var p = pixels
for _ in 0..<width {
p.pointee = P()
p += 1
}
pixels += image_width
}
}
return image
}
func _png_copy<P>(_ region: PNGRegion, _ prev_image: Image<P>, _ image: Image<P>) -> Image<P> {
var prev_image = prev_image
let prev_image_width = prev_image.width
let x = max(0, region.x)
let y = max(0, region.y)
let width = max(0, min(region.width + region.x, prev_image.width) - x)
let height = max(0, min(region.height + region.y, prev_image.height) - y)
guard width != 0 && height != 0 else { return prev_image }
image.withUnsafeBufferPointer {
guard var source = $0.baseAddress else { return }
prev_image.withUnsafeMutableBufferPointer {
guard var destination = $0.baseAddress else { return }
destination += x + y * prev_image_width
for _ in 0..<height {
var p = destination
for _ in 0..<width {
p.pointee = source.pointee
source += 1
p += 1
}
destination += prev_image_width
}
}
}
return prev_image
}
func _png_blend<P>(_ region: PNGRegion, _ prev_image: Image<P>, _ image: Image<P>) -> Image<P> {
var prev_image = prev_image
let prev_image_width = prev_image.width
let x = max(0, region.x)
let y = max(0, region.y)
let width = max(0, min(region.width + region.x, prev_image.width) - x)
let height = max(0, min(region.height + region.y, prev_image.height) - y)
guard width != 0 && height != 0 else { return prev_image }
image.withUnsafeBufferPointer {
guard var source = $0.baseAddress else { return }
prev_image.withUnsafeMutableBufferPointer {
guard var destination = $0.baseAddress else { return }
destination += x + y * prev_image_width
for _ in 0..<height {
var p = destination
for _ in 0..<width {
p.pointee = p.pointee.blended(source: source.pointee)
source += 1
p += 1
}
destination += prev_image_width
}
}
}
return prev_image
}
|
mit
|
9969f8d5a921a109e422e2f6e40a5346
| 31.436242 | 142 | 0.546038 | 4.142571 | false | false | false | false |
mcrollin/S2Geometry
|
Sources/S2/S2Projection+SiTi.swift
|
1
|
3252
|
//
// S2ProjectionSiTi.swift
// S2Geometry
//
// Created by Marc Rollin on 5/1/17.
// Copyright © 2017 Marc Rollin. All rights reserved.
//
import Foundation
typealias S2FaceSiTiLevel = (face: Int, si: UInt64, ti: UInt64, level: Int)
extension S2Projection {
/// The maximum value of an si- or ti-coordinate.
/// It is one shift more than maxSize.
static let maxSiTi = UInt64(S2CellIdentifier.maxSize << 1)
/// Converts an si- or ti-value to the corresponding s- or t-value.
/// Value is capped at 1.0.
func st(siTi: UInt64) -> Double {
let maxSiTi = S2Projection.maxSiTi
if siTi > maxSiTi {
return 1.0
}
return Double(siTi) / Double(maxSiTi)
}
/// Converts the s- or t-value to the nearest si- or ti-coordinate.
/// The result may be outside the range of valid (si,ti)-values.
/// Value of 0.49999999999999994 (math.NextAfter(0.5, -1)), will be incorrectly rounded up.
func siTi(st: Double) -> UInt64 {
let maxSiTi = S2Projection.maxSiTi
if st < 0 {
return 0 &- UInt64(-st * Double(maxSiTi) + 0.5)
}
return UInt64(st * Double(maxSiTi) + 0.5)
}
/// Transforms the (si, ti) coordinates to a (not necessarily unit length) Point on the given face.
func xyz(face: Int, si: UInt64, ti: UInt64) -> S2Point {
assert(0 ..< S2CellIdentifier.facesCount ~= face)
return xyz(face: face,
u: uv(st: st(siTi: si)),
v: uv(st: st(siTi: ti)))
}
/// Transforms the (not necessarily unit length) Point to (face, si, ti) coordinates and the level the point is at.
func faceSiTi(xyz xyzCoordinate: XYZPositionable) -> S2FaceSiTiLevel {
let maxLevel = S2CellIdentifier.maxLevel
let maxSiTi = S2Projection.maxSiTi
let (face, u, v) = faceUV(xyz: xyzCoordinate)
let si = siTi(st: st(uv: u))
let ti = siTi(st: st(uv: v))
// If the levels corresponding to si, ti are not equal, then p is not a cell center.
// The si,ti values of 0 and maxSiTi need to be handled specially because they
// do not correspond to cell centers at any valid level; they are mapped to level -1
// by the code at the end.
let level = maxLevel - S2CellIdentifier.leastSignificantBitSetNonZero(si | maxSiTi)
if level < 0 || level != maxLevel - S2CellIdentifier.leastSignificantBitSetNonZero(ti | maxSiTi) {
return S2FaceSiTiLevel(face: face, si: si, ti: ti, level: -1)
}
// In infinite precision, this test could be changed to ST == SiTi. However,
// due to rounding errors, uvToST(xyzToFaceUV(faceUVToXYZ(stToUV(...)))) is
// not idempotent. On the other hand, the center is computed exactly the same
// way p was originally computed (if it is indeed the center of a Cell);
// the comparison can be exact.
let point = S2Point(x: xyzCoordinate.x, y: xyzCoordinate.y, z: xyzCoordinate.z)
if point == xyz(face: face, si: si, ti: ti).normalized {
return S2FaceSiTiLevel(face: face, si: si, ti: ti, level: level)
}
return S2FaceSiTiLevel(face: face, si: si, ti: ti, level: -1)
}
}
|
mit
|
b0d39760a2aec9b9b33cf06512c40e01
| 37.702381 | 119 | 0.622885 | 3.52221 | false | false | false | false |
djflsdl08/BasicIOS
|
Calculator/Cal/ViewController.swift
|
1
|
1786
|
//
// ViewController.swift
// Cal
//
// Created by 김예진 on 2017. 9. 24..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet private weak var display: UILabel!
private var userIsInTheMiddleOfTyping = false
private var arithmaticOperation = false
private var rememberOperation : String?
@IBAction private func TouchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
//print("touched \(digit) ")
arithmaticOperation = false
if rememberOperation != nil {
brain.performOperation(symbol : rememberOperation!)
rememberOperation = nil
}
if userIsInTheMiddleOfTyping {
display.text! += digit
} else {
display.text = digit
userIsInTheMiddleOfTyping = true
}
}
private var displayValue : Double {
get {
return Double(display.text!)!
}
set {
display.text = String(newValue)
}
}
private var brain = CalculatorBrain()
@IBAction private func Operation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping {
brain.setOperand(operand:displayValue)
}
userIsInTheMiddleOfTyping = false
if let currentOperation = sender.currentTitle {
switch currentOperation {
case "+","−","×","÷" :
arithmaticOperation = true
rememberOperation = currentOperation
default : brain.performOperation(symbol : currentOperation)
}
}
if (arithmaticOperation == false) {
displayValue = brain.result
}
}
}
|
mit
|
45b00036ca7e4586d7afa282975671dc
| 26.276923 | 71 | 0.577552 | 5.308383 | false | false | false | false |
mohamede1945/quran-ios
|
Quran/QariTableViewCell.swift
|
2
|
1998
|
//
// QariTableViewCell.swift
// Quran
//
// Created by Mohamed Afifi on 5/12/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
class QariTableViewCell: UITableViewCell {
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
photoImageView.layer.borderColor = UIColor.lightGray.cgColor
photoImageView.layer.borderWidth = 0.5
let selectionBackground = UIView()
selectionBackground.backgroundColor = #colorLiteral(red: 0.9137254902, green: 0.9137254902, blue: 0.9137254902, alpha: 1)
selectedBackgroundView = selectionBackground
}
override func layoutSubviews() {
super.layoutSubviews()
photoImageView.layer.cornerRadius = photoImageView.bounds.width / 2
photoImageView.layer.masksToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
accessoryType = selected ? .checkmark : .none
updateSelectedBackgroundView()
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
updateSelectedBackgroundView()
}
fileprivate func updateSelectedBackgroundView() {
// selectedBackgroundView?.hidden = selected || !highlighted
}
}
|
gpl-3.0
|
f370ab88bba5ca82b153eb86bae9c7b0
| 33.448276 | 129 | 0.71021 | 4.734597 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges
|
WhiteBoardCodingChallenges/Challenges/HackerRank/Encryption/Encryption.swift
|
1
|
1714
|
//
// Encryption.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 12/05/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
//https://www.hackerrank.com/challenges/encryption
class Encryption: NSObject {
class func encrypt(originalString: String) -> String {
var rowsCount = Int(floor(sqrt(Double(originalString.count))))
let columnsCount = Int(ceil(sqrt(Double(originalString.count))))
if originalString.count > rowsCount * columnsCount {
rowsCount += 1
}
var grid = [[String]]()
for rowIndex in 0..<rowsCount {
var row = [String]()
let start = rowIndex * columnsCount
let end = start + columnsCount
let startRange = originalString.index(originalString.startIndex, offsetBy: start)
var endRange = originalString.endIndex
if originalString.count > end {
endRange = originalString.index(originalString.startIndex, offsetBy: end)
}
let substring = originalString[startRange..<endRange]
for character in substring {
row.append(String(character))
}
grid.append(row)
}
var encryptString = ""
for columnIndex in 0..<columnsCount {
for rowIndex in 0..<rowsCount {
let row = grid[rowIndex]
if row.count > columnIndex{
encryptString += grid[rowIndex][columnIndex]
}
}
if columnIndex != (columnsCount - 1) {
encryptString += " "
}
}
return encryptString
}
}
|
mit
|
85e51c259907f5cf570d9f07f5258534
| 25.353846 | 93 | 0.56509 | 5.008772 | false | false | false | false |
arvedviehweger/swift
|
test/stmt/switch_stmt2.swift
|
1
|
2718
|
// RUN: %target-typecheck-verify-swift
enum E {
case e1
case e2
}
func foo1(e : E) {
switch e { // expected-error{{switch must be exhaustive, consider adding missing cases:}}
// expected-note@-1 {{missing case: '.e2'}}
case .e1: return
}
}
func foo2(i : Int) {
switch i { // expected-error{{switch must be exhaustive, consider adding a default clause}}{{3-3=default: <#code#>\n}}
case 1: return
}
}
// Treat nil as .none and do not emit false
// non-exhaustive warning.
func testSwitchEnumOptionalNil(_ x: Int?) -> Int {
switch x { // no warning
case .some(_):
return 1
case nil:
return -1
}
}
// Do not emit false non-exhaustive warnings if both
// true and false are covered by the switch.
func testSwitchEnumBool(_ b: Bool, xi: Int) -> Int {
var x = xi
let Cond = b
switch Cond { // no warning
default:
x += 1
}
switch Cond { // expected-error{{switch must be exhaustive}}
// expected-note@-1 {{missing case: 'false'}}
case true:
x += 1
}
switch Cond { // expected-error{{switch must be exhaustive}}
// expected-note@-1 {{missing case: 'true'}}
case false:
x += 1
}
switch Cond { // no warning
case true:
x += 1
case false:
x -= 1
}
return x
}
func testSwitchOptionalBool(_ b: Bool?, xi: Int) -> Int {
var x = xi
switch b { // No warning
case .some(true):
x += 1
case .some(false):
x += 1
case .none:
x -= 1
}
switch b { // expected-error{{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.some(false)'}}
case .some(true):
x += 1
case .none:
x -= 1
}
return xi
}
// Do not emit false non-exhaustive warnings if both
// true and false are covered for a boolean element of a tuple.
func testSwitchEnumBoolTuple(_ b1: Bool, b2: Bool, xi: Int) -> Int {
var x = xi
let Cond = (b1, b2)
switch Cond { // no warning
default:
x += 1
}
switch Cond { // expected-error{{switch must be exhaustive}}
// expected-note@-1 {{missing case: '(false, _)'}}
// expected-note@-2 {{missing case: '(_, false)'}}
case (true, true):
x += 1
}
switch Cond { // expected-error{{switch must be exhaustive}}
// expected-note@-1 {{missing case: '(true, _)'}}
// expected-note@-2 {{missing case: '(_, false)'}}
case (false, true):
x += 1
}
switch Cond { // no warning
case (true, true):
x += 1
case (true, false):
x += 1
case (false, true):
x -= 1
case (false, false):
x -= 1
}
return x
}
func non_fully_covered_switch(x: Int) -> Int {
var x = x
switch x { // expected-error{{switch must be exhaustive, consider adding a default clause:}}
case 0:
x += 1
case 3:
x -= 1
}
return x
}
|
apache-2.0
|
99b2bc182d1a6b8aeeff2affbd64a6b0
| 18.985294 | 120 | 0.589772 | 3.351418 | false | false | false | false |
pavankataria/SwiftDataTables
|
SwiftDataTables/Classes/Models/DataStructureModel.swift
|
1
|
3636
|
//
// DataStructureModel.swift
// SwiftDataTables
//
// Created by Pavan Kataria on 22/02/2017.
// Copyright © 2017 Pavan Kataria. All rights reserved.
//
import Foundation
//struct DataTableColumnModel {
//
//}
public struct DataStructureModel {
//MARK: - Private Properties
private var shouldFitTitles: Bool = true
var columnCount: Int {
return headerTitles.count// ?? 0
}
//MARK: - Public Properties
var data = DataTableContent()
var headerTitles = [String]()
var footerTitles = [String]()
var shouldFootersShowSortingElement: Bool = false
private var columnAverageContentLength = [Float]()
//MARK: - Lifecycle
init() {
self.init(data: DataTableContent(), headerTitles: [String]())
}
init(
data: DataTableContent, headerTitles: [String],
shouldMakeTitlesFitInColumn: Bool = true,
shouldDisplayFooterHeaders: Bool = true
//sortableColumns: [Int] // This will map onto which column can be sortable
) {
self.headerTitles = headerTitles
let unfilteredData = data
let sanitisedData = unfilteredData.filter({ currentRowData in
//Trim column count for current row to the number of headers present
let rowWithPreferredColumnCount = Array(currentRowData.prefix(upTo: self.columnCount))
return rowWithPreferredColumnCount.count == self.columnCount
})
self.data = sanitisedData//sanitisedData
self.shouldFitTitles = shouldMakeTitlesFitInColumn
self.columnAverageContentLength = self.processColumnDataAverages(data: self.data)
if shouldDisplayFooterHeaders {
self.footerTitles = headerTitles
}
}
public func averageColumnDataLengthTotal() -> Float {
return Array(0..<self.headerTitles.count).reduce(0){ $0 + self.averageDataLengthForColumn(index: $1) }
}
public func averageDataLengthForColumn(
index: Int) -> Float {
if self.shouldFitTitles {
return max(self.columnAverageContentLength[index], Float(self.headerTitles[index].count))
}
return self.columnAverageContentLength[index]
}
//extension DataStructureModel {
//Finds the average content length in each column
private func processColumnDataAverages(data: DataTableContent) -> [Float] {
var columnContentAverages = [Float]()
for column in Array(0..<self.headerTitles.count) {
let averageForCurrentColumn = Array(0..<data.count).reduce(0){
let dataType: DataTableValueType = data[$1][column]
return $0 + Int(dataType.stringRepresentation.widthOfString(usingFont: UIFont.systemFont(ofSize: UIFont.labelFontSize)).rounded(.up))
}
columnContentAverages.append((data.count == 0) ? 1 : Float(averageForCurrentColumn) / Float(data.count))
}
return columnContentAverages
}
public func columnHeaderSortType(for index: Int) -> DataTableSortType {
guard self.headerTitles[safe: index] != nil else {
return .hidden
}
//Check the configuration object to see what it wants us to display otherwise return default
return .unspecified
}
public func columnFooterSortType(for index: Int) -> DataTableSortType {
guard self.footerTitles[safe: index] != nil else {
return .hidden
}
//Check the configuration object to see what it wants us to display otherwise return default
return .hidden
}
}
|
mit
|
abc83cf8b9cbbff46a8c19aebac82402
| 34.291262 | 147 | 0.651719 | 4.684278 | false | false | false | false |
xedin/swift
|
test/IRGen/dllexport.swift
|
10
|
2574
|
// RUN: %swift -target thumbv7--windows-itanium -emit-ir -parse-as-library -disable-legacy-type-info -parse-stdlib -module-name dllexport %s -o - | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-OPT
// RUN: %swift -target thumbv7--windows-itanium -O -emit-ir -parse-as-library -disable-legacy-type-info -parse-stdlib -module-name dllexport %s -o - | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-OPT
// REQUIRES: CODEGENERATOR=ARM
enum Never {}
@_silgen_name("_swift_fatalError")
func fatalError() -> Never
public protocol p {
func f()
}
open class c {
public init() { }
}
public var ci : c = c()
open class d {
private func m() -> Never {
fatalError()
}
}
// CHECK-DAG: @"$s9dllexport2ciAA1cCvp" = dllexport global %T9dllexport1cC* null, align 4
// CHECK-DAG: @"$s9dllexport1pMp" = dllexport constant
// CHECK-DAG: @"$s9dllexport1cCMn" = dllexport constant
// CHECK-DAG: @"$s9dllexport1cCN" = dllexport alias %swift.type
// CHECK-DAG: @"$s9dllexport1dCN" = dllexport alias %swift.type, bitcast ({{.*}})
// CHECK-DAG-OPT: @"$s9dllexport1dC1m33_C57BA610BA35E21738CC992438E660E9LLyyF" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG-OPT: @"$s9dllexport1dCACycfc" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG-OPT: @"$s9dllexport1cCACycfc" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG-OPT: @"$s9dllexport1cCACycfC" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG: define dllexport swiftcc %swift.refcounted* @"$s9dllexport1cCfd"(%T9dllexport1cC*{{.*}})
// CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1cC* @"$s9dllexport1cCACycfc"(%T9dllexport1cC*)
// CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1cC* @"$s9dllexport1cCACycfC"(%swift.type*)
// CHECK-DAG: define dllexport swiftcc i8* @"$s9dllexport2ciAA1cCvau"()
// CHECK-DAG-NO-OPT: define dllexport swiftcc void @"$s9dllexport1dC1m33_C57BA610BA35E21738CC992438E660E9LLyyF"(%T9dllexport1dC*)
// CHECK-DAG-NO-OPT: define dllexport swiftcc void @"$s9dllexport1dCfD"(%T9dllexport1dC*)
// CHECK-DAG: define dllexport swiftcc %swift.refcounted* @"$s9dllexport1dCfd"(%T9dllexport1dC*{{.*}})
// CHECK-DAG: define dllexport swiftcc %swift.metadata_response @"$s9dllexport1cCMa"(i32)
// CHECK-DAG: define dllexport swiftcc %swift.metadata_response @"$s9dllexport1dCMa"(i32)
// CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1dC* @"$s9dllexport1dCACycfc"(%T9dllexport1dC*)
// CHECK-DAG-OPT: define dllexport swiftcc void @"$s9dllexport1dCfD"(%T9dllexport1dC*)
|
apache-2.0
|
568ff64298d25f9a218583f44a3bc561
| 53.765957 | 208 | 0.729992 | 3.177778 | false | false | false | false |
xedin/swift
|
test/SourceKit/CodeComplete/complete_structure.swift
|
9
|
4208
|
// XFAIL: broken_std_regex
// RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_DOT | %FileCheck %s -check-prefix=S1_DOT
// RUN: %complete-test %s -group=none -add-inner-results -fuzz -structure -tok=S1_POSTFIX | %FileCheck %s -check-prefix=S1_POSTFIX
// RUN: %complete-test %s -group=none -add-inner-results -fuzz -structure -tok=S1_POSTFIX_INIT | %FileCheck %s -check-prefix=S1_INIT
// RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_PAREN_INIT | %FileCheck %s -check-prefix=S1_INIT
// RUN: %complete-test %s -group=none -hide-none -fuzz -structure -tok=STMT_0 | %FileCheck %s -check-prefix=STMT_0
// RUN: %complete-test %s -group=none -fuzz -structure -tok=ENUM_0 | %FileCheck %s -check-prefix=ENUM_0
// RUN: %complete-test %s -group=none -fuzz -structure -tok=OVERRIDE_0 | %FileCheck %s -check-prefix=OVERRIDE_0
// RUN: %complete-test %s -group=none -fuzz -structure -tok=S1_INNER_0 | %FileCheck %s -check-prefix=S1_INNER_0
// RUN: %complete-test %s -group=none -fuzz -structure -tok=INT_INNER_0 | %FileCheck %s -check-prefix=INT_INNER_0
// RUN: %complete-test %s -group=none -fuzz -structure -tok=ASSOCIATED_TYPE_1 | %FileCheck %s -check-prefix=ASSOCIATED_TYPE_1
struct S1 {
func method1() {}
func method2(_ a: Int, b: Int) -> Int { return 1 }
func method3(a a: Int, b: Int) {}
func method4(_: Int, _: Int) {}
func method5(_: inout Int, b: inout Int) {}
func method6(_ c: Int) throws {}
func method7(_ callback: () throws -> ()) rethrows {}
func method8<T, U>(_ d: (T, U) -> T, e: T -> U) {}
let v1: Int = 1
var v2: Int { return 1 }
subscript(x: Int, y: Int) -> Int { return 1 }
subscript(x x: Int, y y: Int) -> Int { return 1 }
init() {}
init(a: Int, b: Int) {}
init(_: Int, _: Int) {}
init(c: Int)? {}
}
func test1(_ x: S1) {
x.#^S1_DOT^#
}
// S1_DOT: {name:method1}()
// S1_DOT: {name:method2}({params:{l:a:}{t: Int}, {n:b:}{t: Int}})
// S1_DOT: {name:method3}({params:{n:a:}{t: Int}, {n:b:}{t: Int}})
// S1_DOT: {name:method4}({params:{t:Int}, {t:Int}})
// S1_DOT: {name:method5}({params:{t:&Int}, {n:b:}{t: &Int}})
// FIXME: put throws in a range!
// S1_DOT: {name:method6}({params:{l:c:}{t: Int}}){throws: throws}
// S1_DOT: {name:method7}({params:{l:callback:}{t: () throws -> ()}}){throws: rethrows}
// S1_DOT: {name:method8}({params:{l:d:}{t: (T, U) -> T}, {n:e:}{t: (T) -> U}})
// S1_DOT: {name:v1}
// S1_DOT: {name:v2}
func test2(_ x: S1) {
x#^S1_POSTFIX^#
}
// Subscripts!
// S1_POSTFIX: {name:.}
// S1_POSTFIX: [{params:{l:x:}{t: Int}, {l:y:}{t: Int}}]
// S1_POSTFIX: [{params:{n:x:}{t: Int}, {n:y:}{t: Int}}]
// The dot becomes part of the name
// S1_POSTFIX: {name:.method1}()
// S1_POSTFIX: {name:.method2}({params:{l:a:}{t: Int}, {n:b:}{t: Int}})
func test4() {
S1#^S1_POSTFIX_INIT^#
}
func test5() {
S1(#^S1_PAREN_INIT^#
}
// S1_INIT: ({params:{t:Int}, {t:Int}})
// S1_INIT: ({params:{n:a:}{t: Int}, {n:b:}{t: Int}})
// S1_INIT: ({params:{n:c:}{t: Int}})
func test6(_ xyz: S1, fgh: (S1) -> S1) {
#^STMT_0^#
}
// STMT_0: {name:func}
// STMT_0: {name:fgh}
// STMT_0: {name:xyz}
// STMT_0: {name:S1}
// STMT_0: {name:test6}({params:{l:xyz:}{t: S1}, {n:fgh:}{t: (S1) -> S1}})
// STMT_0: {name:try!}
enum E1 {
case C1
case C2(S1)
case C3(l1: S1, l2: S1)
}
func test7(_ x: E1) {
test7(.#^ENUM_0^#)
}
// ENUM_0: {name:C1}
// ENUM_0: {name:C2}({params:{t:S1}})
// ENUM_0: {name:C3}({params:{n:l1:}{t: S1}, {n:l2:}{t: S1}})
class C1 {
func foo(x: S1, y: S1, z: (S1) -> S1) -> S1 {}
func zap<T, U>(x: T, y: U, z: (T) -> U) -> T {}
}
class C2 : C1 {
override func #^OVERRIDE_0^#
}
// FIXME: overrides don't break out their code completion string structure.
// OVERRIDE_0: {name:foo(x: S1, y: S1, z: (S1) -> S1) -> S1}
// OVERRIDE_0: {name:zap<T, U>(x: T, y: U, z: (T) -> U) -> T}
func test8() {
#^S1_INNER_0,S1^#
}
// S1_INNER_0: {name:S1.}
// FIXME: should the ( go inside the name here?
// S1_INNER_0: {name:S1}(
func test9(_ x: inout Int) {
#^INT_INNER_0,x^#
}
// INT_INNER_0: {name:x==}
// INT_INNER_0: {name:x<}
// INT_INNER_0: {name:x+}
// INT_INNER_0: {name:x..<}
protocol P1 {
associatedtype T
}
struct S2: P1 {
#^ASSOCIATED_TYPE_1^#
}
// ASSOCIATED_TYPE_1: {name:T = }{params:{l:Type}}
|
apache-2.0
|
7c4535087267c18f4ae6efa010898f43
| 32.133858 | 132 | 0.579848 | 2.307018 | false | true | false | false |
andreamazz/AMPopTip
|
Source/PopTip+Transitions.swift
|
1
|
4898
|
//
// PopTip.swift
// AMPopTip
//
// Created by Andrea Mazzini on 01/05/2017.
// Copyright © 2017 Andrea Mazzini. All rights reserved.
//
import UIKit
public extension PopTip {
/// Triggers the chosen entrance animation
///
/// - Parameter completion: the completion handler
func performEntranceAnimation(completion: @escaping () -> Void) {
switch entranceAnimation {
case .scale:
entranceScale(completion: completion)
case .transition:
entranceTransition(completion: completion)
case .fadeIn:
entranceFadeIn(completion: completion)
case .custom:
if shouldShowMask {
addBackgroundMask(to: containerView)
}
containerView?.addSubview(self)
entranceAnimationHandler?(completion)
case .none:
if shouldShowMask {
addBackgroundMask(to: containerView)
}
containerView?.addSubview(self)
completion()
}
}
/// Triggers the chosen exit animation
///
/// - Parameter completion: the completion handler
func performExitAnimation(completion: @escaping () -> Void) {
switch exitAnimation {
case .scale:
exitScale(completion: completion)
case .fadeOut:
exitFadeOut(completion: completion)
case .custom:
exitAnimationHandler?(completion)
case .none:
completion()
}
}
private func entranceTransition(completion: @escaping () -> Void) {
transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
switch direction {
case .up:
transform = transform.translatedBy(x: 0, y: -from.origin.y)
case .down, .none:
transform = transform.translatedBy(x: 0, y: (containerView?.frame.height ?? 0) - from.origin.y)
case .left:
transform = transform.translatedBy(x: from.origin.x, y: 0)
case .right:
transform = transform.translatedBy(x: (containerView?.frame.width ?? 0) - from.origin.x, y: 0)
case .auto, .autoHorizontal, .autoVertical: break // The decision will be made at this point
}
if shouldShowMask {
addBackgroundMask(to: containerView)
}
containerView?.addSubview(self)
UIView.animate(withDuration: animationIn, delay: delayIn, usingSpringWithDamping: 0.6, initialSpringVelocity: 1.5, options: [.curveEaseInOut, .beginFromCurrentState], animations: {
self.transform = .identity
self.backgroundMask?.alpha = 1
}) { (_) in
completion()
}
}
private func entranceScale(completion: @escaping () -> Void) {
transform = CGAffineTransform(scaleX: 0, y: 0)
if shouldShowMask {
addBackgroundMask(to: containerView)
}
containerView?.addSubview(self)
UIView.animate(withDuration: animationIn, delay: delayIn, usingSpringWithDamping: 0.6, initialSpringVelocity: 1.5, options: [.curveEaseInOut, .beginFromCurrentState], animations: {
self.transform = .identity
self.backgroundMask?.alpha = 1
}) { (_) in
completion()
}
}
private func entranceFadeIn(completion: @escaping () -> Void) {
if shouldShowMask {
addBackgroundMask(to: containerView)
}
containerView?.addSubview(self)
alpha = 0
UIView.animate(withDuration: animationIn, delay: delayIn, options: [.curveEaseInOut, .beginFromCurrentState], animations: {
self.alpha = 1
self.backgroundMask?.alpha = 1
}) { (_) in
completion()
}
}
private func exitScale(completion: @escaping () -> Void) {
transform = .identity
UIView.animate(withDuration: animationOut, delay: delayOut, options: [.curveEaseInOut, .beginFromCurrentState], animations: {
self.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
self.backgroundMask?.alpha = 0
}) { (_) in
completion()
}
}
private func exitFadeOut(completion: @escaping () -> Void) {
alpha = 1
UIView.animate(withDuration: animationOut, delay: delayOut, options: [.curveEaseInOut, .beginFromCurrentState], animations: {
self.alpha = 0
self.backgroundMask?.alpha = 0
}) { (_) in
completion()
}
}
private func addBackgroundMask(to targetView: UIView?) {
guard let backgroundMask = backgroundMask, let targetView = targetView else { return }
targetView.addSubview(backgroundMask)
guard shouldCutoutMask else {
backgroundMask.backgroundColor = maskColor
return
}
let cutoutView = UIView(frame: backgroundMask.bounds)
let cutoutShapeMaskLayer = CAShapeLayer()
let cutoutPath = cutoutPathGenerator(from)
let path = UIBezierPath(rect: backgroundMask.bounds)
path.append(cutoutPath)
cutoutShapeMaskLayer.path = path.cgPath
cutoutShapeMaskLayer.fillRule = .evenOdd
cutoutView.layer.mask = cutoutShapeMaskLayer
cutoutView.clipsToBounds = true
cutoutView.backgroundColor = maskColor
cutoutView.isUserInteractionEnabled = false
backgroundMask.addSubview(cutoutView)
}
}
|
mit
|
b3fe735f446a1919c5749779feadaf29
| 29.416149 | 185 | 0.67817 | 4.43971 | false | false | false | false |
BalestraPatrick/TweetsCounter
|
Carthage/Checkouts/Whisper/Demo/WhisperDemo/WhisperDemo/TableViewController.swift
|
4
|
1930
|
import UIKit
import Whisper
class TableViewController: UITableViewController {
static let reusableIdentifier = "TableViewControllerReusableCell"
let colors = [
UIColor(red:1, green:0.67, blue:0.82, alpha:1),
UIColor(red:0.69, green:0.96, blue:0.4, alpha:1),
UIColor(red:0.29, green:0.95, blue:0.63, alpha:1),
UIColor(red:0.31, green:0.74, blue:0.95, alpha:1),
UIColor(red:0.47, green:0.6, blue:0.13, alpha:1),
UIColor(red:0.05, green:0.17, blue:0.21, alpha:1),
UIColor(red:0.9, green:0.09, blue:0.44, alpha:1)]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
tableView.register(UITableViewCell.self,
forCellReuseIdentifier: TableViewController.reusableIdentifier)
tableView.separatorStyle = .none
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let navigationController = navigationController else { return }
let message = Message(title: "This message will silent in 3 seconds.", backgroundColor: UIColor(red:0.89, green:0.09, blue:0.44, alpha:1))
Whisper.show(whisper: message, to: navigationController, action: .present)
hide(whisperFrom: navigationController, after: 3)
}
// MARK: - TableView methods
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: TableViewController.reusableIdentifier)
else { return UITableViewCell() }
let number = Int(arc4random_uniform(UInt32(colors.count)))
cell.backgroundColor = colors[number]
cell.selectionStyle = .none
return cell
}
}
|
mit
|
e205f16b28a4ec6f08ffd4b34f637796
| 32.859649 | 142 | 0.719171 | 4.020833 | false | false | false | false |
linkedin/ConsistencyManager-iOS
|
ConsistencyManager/DataStructures/WeakArray.swift
|
2
|
5713
|
// © 2016 LinkedIn Corp. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import Foundation
/**
This typealias allows you to create a `WeakArray` with any class type.
e.g.
`var weakArray = WeakArray<ConsistencyManager>()`
*/
public typealias WeakArray<T: AnyObject> = AnyWeakArray<WeakBox<T>>
/**
This typealias allows you to create a `WeakArray` with ConsistencyManagerListener.
*/
public typealias WeakListenerArray = AnyWeakArray<WeakListenerBox>
/**
This typealias allows you to create a `WeakArray` with ConsistencyManagerUpdatesListener.
*/
public typealias WeakUpdatesListenerArray = AnyWeakArray<WeakUpdatesListenerBox>
/**
This class defines an array which doesn't hold strong references to its elements.
If an element in the array gets dealloced at some point, accessing that element will just return nil.
It takes advantage of out Array+Weak extension, so all the functions here are just pass throughs to the Array class.
You cannot put structs into the WeakArray because structs cannot be declared with weak. You can only put classes into the array.
KNOWN BUGS
You can't create a WeakArray<SomeProtocol>. This is because of an Apple bug: https://bugs.swift.org/browse/SR-1176.
So, instead of this, it's recommended to create your own wrapper class and create a typealias (as seen above).
*/
public struct AnyWeakArray<T: WeakHolder>: ExpressibleByArrayLiteral {
// MARK: Internal
/// The internal data is an array of closures which return weak T's
fileprivate var data: [T]
// MARK: Initializers
/**
Creates an empty array
*/
public init() {
data = []
}
/**
Creates an array with a certain capacity. All elements in the array will be nil.
*/
public init(count: Int) {
data = Array(repeating: T(element: nil), count: count)
}
/**
Array literal initializer. Allows you to initialize a WeakArray with array notation.
*/
public init(arrayLiteral elements: T.Element?...) {
data = elements.map { element in
return T.init(element: element)
}
}
/**
Creates an array with the inner type `[T]` where T is a WeakHolder.
*/
public init(_ data: [T]) {
self.data = data
}
// MARK: Public Properties
/// How many elements the array stores
public var count: Int {
return data.count
}
// MARK: Public Methods
/**
Append an element to the array.
*/
public mutating func append(_ element: T.Element?) {
data.append(T.init(element: element))
}
/**
This method iterates through the array and removes any element which is nil.
It also returns an array of nonoptional values for convenience.
This method runs in O(n), so you should only call this method every time you need it. You should only call it once.
*/
public mutating func prune() -> [T.Element] {
return data.prune()
}
/**
This function is similar to the map function on Array.
It takes a function that maps T to U and returns a WeakArray of the same length with this function applied to each element.
It does not prune any nil elements as part of this map so the resulting count will be equal to the current count.
*/
public func map<U>(_ transform: (T.Element?) throws -> U.Element?) rethrows -> AnyWeakArray<U> {
let newArray: [U] = try data.map(transform)
return AnyWeakArray<U>(newArray)
}
/**
This function is similar to the flatMap function on Array.
It takes a function that maps T to U? and returns a WeakArray with this function applied to each element.
It automatically prunes any nil elements as part of this flatMap and removes them.
*/
public func flatMap<U>(_ transform: (T.Element?) throws -> U.Element?) rethrows -> AnyWeakArray<U> {
let newArray: [U] = try data.flatMap(transform)
return AnyWeakArray<U>(newArray)
}
/**
This function is similar to the filter function on Array.
The `isIncluded` closure simply returns whether you want the element in the array.
*/
public func filter(_ isIncluded: (T.Element?) throws -> Bool) rethrows -> AnyWeakArray<T> {
let newArray: [T] = try data.filter(isIncluded)
return AnyWeakArray<T>(newArray)
}
}
// MARK: MutableCollectionType Implementation
extension AnyWeakArray: MutableCollection {
// Required by SequenceType
public func makeIterator() -> IndexingIterator<AnyWeakArray<T>> {
// Rather than implement our own generator, let's take advantage of the generator provided by IndexingGenerator
return IndexingIterator<AnyWeakArray<T>>(_elements: self)
}
// Required by _CollectionType
public func index(after i: Int) -> Int {
return data.index(after: i)
}
// Required by _CollectionType
public var endIndex: Int {
return data.endIndex
}
// Required by _CollectionType
public var startIndex: Int {
return data.startIndex
}
/**
Getter and setter array
*/
public subscript(index: Int) -> T.Element? {
get {
return data[index].element
}
set {
data[index] = T.init(element: newValue)
}
}
}
|
apache-2.0
|
8372258729883f563e380a47de9ac01f
| 32.017341 | 129 | 0.67542 | 4.38373 | false | false | false | false |
ifLab/WeCenterMobile-iOS
|
WeCenterMobile/View/Explore/FeaturedArticleCell.swift
|
3
|
2137
|
//
// FeaturedArticleCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/3/13.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class FeaturedArticleCell: UITableViewCell {
@IBOutlet weak var userAvatarView: MSRRoundedImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var articleTitleLabel: UILabel!
@IBOutlet weak var articleTagLabel: UILabel!
@IBOutlet weak var articleUserButton: UIButton!
@IBOutlet weak var articleButton: UIButton!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var badgeLabel: UILabel!
@IBOutlet weak var separator: UIView!
@IBOutlet weak var userContainerView: UIView!
@IBOutlet weak var articleContainerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
msr_scrollView?.delaysContentTouches = false
let theme = SettingsManager.defaultManager.currentTheme
for v in [userContainerView, articleContainerView] {
v.backgroundColor = theme.backgroundColorB
}
badgeLabel.backgroundColor = theme.backgroundColorA
for v in [containerView, badgeLabel] {
v.msr_borderColor = theme.borderColorA
}
separator.backgroundColor = theme.borderColorA
for v in [articleUserButton, articleButton] {
v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted)
}
for v in [userNameLabel, articleTitleLabel] {
v.textColor = theme.titleTextColor
}
badgeLabel.textColor = theme.footnoteTextColor
}
func update(object object: FeaturedObject) {
let object = object as! FeaturedArticle
let article = object.article!
userAvatarView.wc_updateWithUser(article.user)
userNameLabel.text = article.user?.name ?? "匿名用户"
articleTitleLabel.text = article.title
articleButton.msr_userInfo = article
articleUserButton.msr_userInfo = article.user
setNeedsLayout()
layoutIfNeeded()
}
}
|
gpl-2.0
|
81d492ed984af327ff6962821a9aab1e
| 35.689655 | 99 | 0.690644 | 5.187805 | false | false | false | false |
cottonBuddha/Qsic
|
Qsic/QSWidget.swift
|
1
|
2276
|
//
// QSWidget.swift
// Qsic
//
// Created by cottonBuddha on 2017/7/8.
// Copyright © 2017年 cottonBuddha. All rights reserved.
//
import Foundation
import Darwin.ncurses
class QSWidget {
var startX : Int
var startY : Int
var width : Int
var height : Int
var window : OpaquePointer?
weak var superWidget : QSWidget?
var subWidgets : [QSWidget]?
public init(startX:Int, startY:Int, width:Int, height:Int) {
self.startX = startX
self.startY = startY
self.width = width
self.height = height
}
internal func initWidgetOnSuperwidget(superwidget:QSWidget) {
self.startX = superwidget.startX + self.startX
self.startY = superwidget.startY + self.startY
if self.width == Int(COLS) {
self.width = superwidget.width - self.startX
}
self.window = subwin(superwidget.window, Int32(self.height), Int32(self.width), Int32(self.startY), Int32(self.startX))
}
public func drawWidget() {
guard self.window != nil else {
return
}
wrefresh(self.window)
}
public func resize() {
// resizeterm(Int32, Int32)
}
public func addSubWidget(widget:QSWidget) {
widget.superWidget = self
self.subWidgets?.append(widget)
widget.initWidgetOnSuperwidget(superwidget: self)
widget.drawWidget()
widget.subWidgets?.forEach({ (widget) in
widget.addSubWidget(widget: widget)
})
}
public func removeSubWidget(widget:QSWidget) {
if let index = self.subWidgets?.index(of: widget) {
self.subWidgets?.remove(at: index)
widget.destroyWindow()
}
}
public func removeSubWidgets() {
self.subWidgets?.removeAll()
self.drawWidget()
}
public func destroyWindow() {
delwin(self.window)
}
public func eraseSelf() {
werase(self.window)
wrefresh(self.window)
}
deinit {
destroyWindow()
}
}
extension QSWidget : Equatable {
public static func ==(lhs: QSWidget, rhs: QSWidget) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
|
mit
|
af3ce7b49402e8792c5a66631645533d
| 23.978022 | 127 | 0.592609 | 3.966841 | false | false | false | false |
BabyShung/SplashWindow
|
Demo/Demo/AppDelegate.swift
|
1
|
2914
|
//
// AppDelegate.swift
// SplashWindow-Example
//
// Created by Hao Zheng on 4/30/17.
// Copyright © 2017 Hao Zheng. All rights reserved.
//
import UIKit
import SplashWindow
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var splashWindow: SplashWindow = {
let identifier = "LaunchScreen"
let vc = UIStoryboard.named(identifier, vc: identifier)
let splashWindow = SplashWindow.init(window: self.window!, launchViewController: vc)
/** Customization - otherwise default
AppAuthentication.shared.touchIDMessage = "YOUR MESSAGE"
splashWindow.touchIDBtnImage = UIImage(named: "user.png")
splashWindow.logoutBtnImage = UIImage(named: "user.png")
*/
//Auth succeeded closure
splashWindow.authSucceededClosure = { _ in }
//Return a loginVC after clicking logout
splashWindow.logoutClosure = {
return UIStoryboard.named("Login", vc: "LoginViewController")
}
return splashWindow
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let initialVC = UINavigationController(rootViewController: AuthFlowController().authSettingVC)
/*
Use your logic to determine whether your app is loggedIn
initialVC can be any of your viewController, but must make sure if it's loggedIn when showing this VC
*/
splashWindow.authenticateUser(isLoggedIn: true, initialVC: initialVC)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
splashWindow.showSplashView()
}
func applicationDidEnterBackground(_ application: UIApplication) {
splashWindow.enteredBackground()
}
func applicationDidBecomeActive(_ application: UIApplication) {
/*
Use your logic to determine whether your app is loggedIn
If you already have some code here in didBecomeActive such as refreshing
network request or load data from database, if you want to bypass
these actions before authentication, use self.splashWindow.isAuthenticating:
//1. call authenticateUser first
splashWindow.authenticateUser(isLoggedIn: true)
//2. if you are authenticating, here it skips YOUR NETWORK CODE or DATABASE CODE
guard !splashWindow.isAuthenticating else { return }
//...
//YOUR NETWORK CODE or DATABASE CODE
//...
*/
let rootIsLoginVC = window?.rootViewController is LoginViewController
splashWindow.authenticateUser(isLoggedIn: !rootIsLoginVC)
}
}
|
mit
|
9cf4ae73accbf551f27b9db3109f71d0
| 33.270588 | 144 | 0.647786 | 5.591171 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigo/Settings/Albums/CategoryImageSort.swift
|
1
|
2925
|
//
// CategoryImageSort.swift
// piwigo
//
// Created by Spencer Baker on 3/3/15.
// Copyright (c) 2015 bakercrew. All rights reserved.
//
// Converted to Swift 5 by Eddy Lelièvre-Berna on 28/06/2020.
//
import Foundation
import piwigoKit
@objc
class CategoryImageSort: NSObject {
@objc
class func getPiwigoSortObjcDescription(for typeObjc:kPiwigoSortObjc) -> String {
let type = kPiwigoSort(rawValue: Int16(typeObjc.rawValue))
let sortDesc = getPiwigoSortDescription(for: type!)
return sortDesc
}
class func getPiwigoSortDescription(for type:kPiwigoSort) -> String {
var sortDesc = ""
switch type {
case .nameAscending: // Photo title, A → Z
sortDesc = String(format: "%@ %@", kGetImageOrderName, kGetImageOrderAscending)
case .nameDescending: // Photo title, Z → A
sortDesc = String(format: "%@ %@", kGetImageOrderName, kGetImageOrderDescending)
case .fileNameAscending: // File name, A → Z
sortDesc = String(format: "%@ %@", kGetImageOrderFileName, kGetImageOrderAscending)
case .fileNameDescending: // File name, Z → A
sortDesc = String(format: "%@ %@", kGetImageOrderFileName, kGetImageOrderDescending)
case .dateCreatedAscending: // Date created, old → new
sortDesc = String(format: "%@ %@", kGetImageOrderDateCreated, kGetImageOrderAscending)
case .dateCreatedDescending: // Date created, new → old
sortDesc = String(format: "%@ %@", kGetImageOrderDateCreated, kGetImageOrderDescending)
case .datePostedAscending: // Date posted, new → old
sortDesc = String(format: "%@ %@", kGetImageOrderDatePosted, kGetImageOrderAscending)
case .datePostedDescending: // Date posted, old → new
sortDesc = String(format: "%@ %@", kGetImageOrderDatePosted, kGetImageOrderDescending)
case .ratingScoreDescending: // Rating score, high → low
sortDesc = String(format: "%@ %@", kGetImageOrderRating, kGetImageOrderDescending)
case .ratingScoreAscending: // Rating score, low → high
sortDesc = String(format: "%@ %@", kGetImageOrderRating, kGetImageOrderAscending)
case .visitsAscending: // Visits, high → low
sortDesc = String(format: "%@ %@", kGetImageOrderVisits, kGetImageOrderAscending)
case .visitsDescending: // Visits, low → high
sortDesc = String(format: "%@ %@", kGetImageOrderVisits, kGetImageOrderDescending)
case .random: // Random order
sortDesc = kGetImageOrderRandom
case .manual, // Manual order
.count:
fallthrough
default:
sortDesc = ""
}
return sortDesc
}
}
|
mit
|
4622fad052ffb7b61fb5c21014ea62aa
| 41.647059 | 99 | 0.616897 | 4.334828 | false | false | false | false |
lammertw/SevenSwitch
|
SevenSwitchExample/SevenSwitchExample/ViewController.swift
|
2
|
2858
|
//
// ViewController.swift
// SevenSwitchExample
//
// Created by Benjamin Vogelzang on 6/21/14.
// Copyright (c) 2014 Ben Vogelzang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var ibSwitch: SevenSwitch!
override func viewDidLoad() {
super.viewDidLoad()
ibSwitch.onTintColor = UIColor(red: 0.20, green: 0.42, blue: 0.86, alpha: 1)
ibSwitch.on = true
// this will create the switch with default dimensions, you'll still need to set the position though
// you also have the option to pass in a frame of any size you choose
let mySwitch = SevenSwitch(frame: CGRect.zero)
mySwitch.center = CGPoint(x: self.view.bounds.size.width * 0.5, y: self.view.bounds.size.height * 0.5)
mySwitch.addTarget(self, action: #selector(ViewController.switchChanged(_:)), for: UIControlEvents.valueChanged)
self.view.addSubview(mySwitch)
// turn the switch on
mySwitch.on = true
// Example of a bigger switch with images
let mySwitch2 = SevenSwitch(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
mySwitch2.center = CGPoint(x: self.view.bounds.size.width * 0.5, y: self.view.bounds.size.height * 0.5 - 80)
mySwitch2.addTarget(self, action: #selector(ViewController.switchChanged(_:)), for: UIControlEvents.valueChanged)
mySwitch2.offImage = UIImage(named: "cross.png")
mySwitch2.onImage = UIImage(named: "check.png")
mySwitch2.onTintColor = UIColor(hue: 0.08, saturation: 0.74, brightness: 1.00, alpha: 1.00)
mySwitch2.isRounded = false
self.view.addSubview(mySwitch2)
// turn the switch on with animation
mySwitch2.setOn(true, animated: true)
// Example of color customization
let mySwitch3 = SevenSwitch(frame: CGRect.zero)
mySwitch3.center = CGPoint(x: self.view.bounds.size.width * 0.5, y: self.view.bounds.size.height * 0.5 + 70)
mySwitch3.addTarget(self, action: #selector(ViewController.switchChanged(_:)), for: UIControlEvents.valueChanged)
self.view.addSubview(mySwitch3)
//self.view.backgroundColor = [UIColor colorWithRed:0.19f green:0.23f blue:0.33f alpha:1.00f];
mySwitch3.thumbTintColor = UIColor(red: 0.19, green: 0.23, blue: 0.33, alpha: 1)
mySwitch3.activeColor = UIColor(red: 0.07, green: 0.09, blue: 0.11, alpha: 1)
mySwitch3.inactiveColor = UIColor(red: 0.07, green: 0.09, blue: 0.11, alpha: 1)
mySwitch3.onTintColor = UIColor(red: 0.45, green: 0.58, blue: 0.67, alpha: 1)
mySwitch3.borderColor = UIColor.clear
mySwitch3.shadowColor = UIColor.black
}
func switchChanged(_ sender: SevenSwitch) {
print("Changed value to: \(sender.on)")
}
}
|
mit
|
d2bc56984bfe1963baf762f64494b121
| 45.852459 | 121 | 0.653954 | 3.692506 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformKit/BuySellKit/Core/BuyOrderDetails.swift
|
1
|
3070
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Errors
import FeatureCardPaymentDomain
import MoneyKit
public struct BuyOrderDetails: Equatable {
public typealias State = OrderDetailsState
public let fiatValue: FiatValue
public let cryptoValue: CryptoValue
public var price: FiatValue?
public var fee: FiatValue?
public let identifier: String
public let paymentMethod: PaymentMethod.MethodType
public let creationDate: Date?
public let error: String?
public let ux: UX.Dialog?
public internal(set) var paymentMethodId: String?
public let authorizationData: PartnerAuthorizationData?
public let state: State
public let paymentProcessorErrorType: PaymentProcessorErrorType?
// MARK: - Setup
// swiftlint:disable cyclomatic_complexity
init?(recorder: AnalyticsEventRecorderAPI, response: OrderPayload.Response) {
guard let state = State(rawValue: response.state) else {
return nil
}
guard let fiatCurrency = FiatCurrency(code: response.inputCurrency) else {
return nil
}
guard let cryptoCurrency = CryptoCurrency(code: response.outputCurrency) else {
return nil
}
guard let cryptoValue = CryptoValue.create(minor: response.outputQuantity, currency: cryptoCurrency) else {
return nil
}
guard let fiatValue = FiatValue.create(minor: response.inputQuantity, currency: fiatCurrency) else {
return nil
}
guard let paymentType = PaymentMethodPayloadType(rawValue: response.paymentType) else {
return nil
}
identifier = response.id
if let processingErrorType = response.processingErrorType {
switch processingErrorType {
case "ISSUER":
paymentProcessorErrorType = .issuer
default:
paymentProcessorErrorType = .unknown
}
} else {
paymentProcessorErrorType = nil
}
self.fiatValue = fiatValue
self.cryptoValue = cryptoValue
self.state = state
paymentMethod = PaymentMethod.MethodType(type: paymentType, currency: .fiat(fiatCurrency))
paymentMethodId = response.paymentMethodId
authorizationData = PartnerAuthorizationData(orderPayloadResponse: response)
if let price = response.price {
self.price = FiatValue.create(minor: price, currency: fiatCurrency)
}
if let fee = response.fee {
self.fee = FiatValue.create(minor: fee, currency: fiatCurrency)
}
creationDate = DateFormatter.utcSessionDateFormat.date(from: response.updatedAt)
if creationDate == nil {
recorder.record(event: AnalyticsEvents.DebugEvent.updatedAtParsingError(date: response.updatedAt))
}
error = response.paymentError ?? response.attributes?.error
ux = response.ux
}
}
extension OrderPayload.Response: OrderPayloadResponseAPI {}
|
lgpl-3.0
|
eec1fbcbb46550977bead148323e7e06
| 31.305263 | 115 | 0.67188 | 5.393673 | false | false | false | false |
asowers1/RevCheckIn
|
RevCheckIn/HTTPRequestSerializer.swift
|
1
|
9652
|
//
// HTTPRequestSerializer.swift
// RevCheckIn
//
// Created by Andrew Sowers on 7/29/14.
// Copyright (c) 2014 Andrew Sowers. All rights reserved.
//
import Foundation
extension String {
func escapeStr() -> String {
var raw: NSString = self
var str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,raw,"[].",":/?&=;+!@#$()',*",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
return str as NSString
}
}
class HTTPRequestSerializer: NSObject {
var headers = Dictionary<String,String>()
var stringEncoding: UInt = NSUTF8StringEncoding
var allowsCellularAccess = true
var HTTPShouldHandleCookies = true
var HTTPShouldUsePipelining = false
var timeoutInterval: NSTimeInterval = 60
var cachePolicy: NSURLRequestCachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy
var networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeDefault
let contentTypeKey = "Content-Type"
override init() {
super.init()
}
func newRequest(url: NSURL, method: HTTPMethod) -> NSMutableURLRequest {
println("NEW REQUEST")
var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
request.HTTPMethod = method.toRaw()
request.allowsCellularAccess = self.allowsCellularAccess
request.HTTPShouldHandleCookies = self.HTTPShouldHandleCookies
request.HTTPShouldUsePipelining = self.HTTPShouldUsePipelining
request.networkServiceType = self.networkServiceType
for (key,val) in self.headers {
request.addValue(val, forHTTPHeaderField: key)
}
return request
}
///creates a request from the url, HTTPMethod, and parameters
func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) {
var request = newRequest(url, method: method)
var isMultiForm = false
//do a check for upload objects to see if we are multi form
if let params = parameters {
for (name,object: AnyObject) in params {
if object is HTTPUpload {
isMultiForm = true
break
}
}
}
if isMultiForm {
if(method != .POST || method != .PUT) {
request.HTTPMethod = HTTPMethod.POST.toRaw() // you probably wanted a post
}
if parameters != nil {
request.HTTPBody = dataFromParameters(parameters!)
}
return (request,nil)
}
var queryString = ""
if parameters != nil {
queryString = self.stringFromParameters(parameters!)
}
if isURIParam(method) {
var para = (request.URL?.query != nil) ? "&" : "?"
var newUrl = "\(request.URL!.absoluteString!)\(para)\(queryString)"
println("PARAM:\(para):NEWURL:\(newUrl)")
request.URL = NSURL.URLWithString(newUrl)
} else {
var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
if request.valueForHTTPHeaderField(contentTypeKey) == nil {
request.setValue("application/x-www-form-urlencoded; charset=\(charset)",
forHTTPHeaderField:contentTypeKey)
}
request.HTTPBody = queryString.dataUsingEncoding(self.stringEncoding)
}
return (request,nil)
}
///convert the parameter dict to its HTTP string representation
func stringFromParameters(parameters: Dictionary<String,AnyObject>) -> String {
var cnt = 0
var key = "Crashlytics step "
var altRet = ""
var first = true
for (key, value) in parameters{
if (!first){
altRet += "&"
}
altRet += key
altRet += "="
altRet += value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
first = false
}
/*
Crashlytics.setObjectValue("startingStringFromParameters", forKey: "StringFromparameters step 1")
let ret = join("&", map(serializeObject(parameters, key: nil), {(pair) in
var newKey = key + String(cnt)
cnt++
Crashlytics.setObjectValue(pair.stringValue(), forKey: newKey)
return pair.stringValue()
}))
*/
Crashlytics.setObjectValue(altRet, forKey: "stringFromParams return")
return altRet
}
///check if enum is a HTTPMethod that requires the params in the URL
func isURIParam(method: HTTPMethod) -> Bool {
if(method == .GET || method == .HEAD || method == .DELETE) {
return true
}
return false
}
///the method to serialized all the objects
func serializeObject(object: AnyObject,key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
if let array = object as? Array<AnyObject> {
for nestedValue : AnyObject in array {
collect.extend(self.serializeObject(nestedValue,key: "\(key!)[]"))
}
} else if let dict = object as? Dictionary<String,AnyObject> {
for (nestedKey, nestedObject: AnyObject) in dict {
var newKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey
collect.extend(self.serializeObject(nestedObject,key: newKey))
}
} else {
collect.append(HTTPPair(value: object, key: key))
}
return collect
}
//create a multi form data object of the parameters
func dataFromParameters(parameters: Dictionary<String,AnyObject>) -> NSData {
var mutData = NSMutableData()
var files = Dictionary<String,HTTPUpload>()
var notFiles = Dictionary<String,AnyObject>()
for (key, object: AnyObject) in parameters {
if let upload = object as? HTTPUpload {
files[key] = upload
} else {
notFiles[key] = object
}
}
var multiCRLF = "\r\n"
var boundary = "Boundary+\(arc4random())\(arc4random())"
var boundSplit = "\(multiCRLF)--\(boundary)\(multiCRLF)"
mutData.appendData("--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!)
var noParams = false
if notFiles.count == 0 {
noParams = true
}
var i = files.count
for (key,upload) in files {
mutData.appendData(multiFormHeader(key, fileName: upload.fileName,
type: upload.mimeType, multiCRLF: multiCRLF).dataUsingEncoding(self.stringEncoding)!)
mutData.appendData(upload.data!)
if i == 1 && noParams {
} else {
mutData.appendData(boundSplit.dataUsingEncoding(self.stringEncoding)!)
}
}
if !noParams {
let paramStr = join(boundSplit, map(serializeObject(notFiles, key: nil), {(pair) in
return "\(self.multiFormHeader(pair.key, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.getValue())"
}))
mutData.appendData(paramStr.dataUsingEncoding(self.stringEncoding)!)
}
mutData.appendData("\(multiCRLF)--\(boundary)--\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!)
return mutData
}
///helper method to create the multi form headers
func multiFormHeader(name: String, fileName: String?, type: String?, multiCRLF: String) -> String {
var str = "Content-Disposition: form-data; name=\"\(name.escapeStr())\""
if fileName != nil {
str += "; filename=\"\(fileName!)\""
}
str += multiCRLF
if type != nil {
str += "Content-Type: \"\(type!)\"\(multiCRLF)"
}
str += multiCRLF
return str
}
}
///Local class to create key/pair of the parameters
class HTTPPair: NSObject {
var value: AnyObject
var key: String!
init(value: AnyObject, key: String?) {
self.value = value
self.key = key
}
func getValue() -> String {
var val = ""
if let str = self.value as? String {
val = str
} else if self.value.description != nil {
val = self.value.description
}
return val
}
func stringValue() -> String {
var val = getValue()
if self.key == nil {
return val.escapeStr()
}
return "\(self.key.escapeStr())=\(val.escapeStr())"
}
}
class JSONRequestSerializer: HTTPRequestSerializer {
override func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) {
if self.isURIParam(method) {
return super.createRequest(url, method: method, parameters: parameters)
}
var request = newRequest(url, method: method)
var error: NSError?
if parameters != nil {
var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: self.contentTypeKey)
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: NSJSONWritingOptions(), error:&error)
}
return (request, error)
}
}
|
mit
|
b0b6bb8448fc022c56ca1b070c826688
| 38.395918 | 171 | 0.603813 | 4.998446 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Utility/Primitives/VectorsExtensions.swift
|
1
|
5702
|
//
// Vector.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/7/19.
//
import Foundation
import CoreGraphics
import QuartzCore
/**
Single value container. Needed because lottie sometimes wraps a Double in an array.
*/
extension Vector1D: Codable {
public init(from decoder: Decoder) throws {
/// Try to decode an array of doubles
do {
var container = try decoder.unkeyedContainer()
self.value = try container.decode(Double.self)
} catch {
self.value = try decoder.singleValueContainer().decode(Double.self)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value)
}
var cgFloatValue: CGFloat {
return CGFloat(value)
}
}
extension Double {
var vectorValue: Vector1D {
return Vector1D(self)
}
}
/**
Needed for decoding json {x: y:} to a CGPoint
*/
struct Vector2D: Codable {
var x: Double
var y: Double
init(x: Double, y: Double) {
self.x = x
self.y = y
}
private enum CodingKeys : String, CodingKey {
case x = "x"
case y = "y"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Vector2D.CodingKeys.self)
do {
let xValue: [Double] = try container.decode([Double].self, forKey: .x)
self.x = xValue[0]
} catch {
self.x = try container.decode(Double.self, forKey: .x)
}
do {
let yValue: [Double] = try container.decode([Double].self, forKey: .y)
self.y = yValue[0]
} catch {
self.y = try container.decode(Double.self, forKey: .y)
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Vector2D.CodingKeys.self)
try container.encode(x, forKey: .x)
try container.encode(y, forKey: .y)
}
var pointValue: CGPoint {
return CGPoint(x: x, y: y)
}
}
extension Vector2D {
}
extension CGPoint {
var vector2dValue: Vector2D {
return Vector2D(x: Double(x), y: Double(y))
}
}
/**
A three dimensional vector.
These vectors are encoded and decoded from [Double]
*/
extension Vector3D: Codable {
init(x: CGFloat, y: CGFloat, z: CGFloat) {
self.x = Double(x)
self.y = Double(y)
self.z = Double(z)
}
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
if !container.isAtEnd {
self.x = try container.decode(Double.self)
} else {
self.x = 0
}
if !container.isAtEnd {
self.y = try container.decode(Double.self)
} else {
self.y = 0
}
if !container.isAtEnd {
self.z = try container.decode(Double.self)
} else {
self.z = 0
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(x)
try container.encode(y)
try container.encode(z)
}
}
public extension Vector3D {
var pointValue: CGPoint {
return CGPoint(x: x, y: y)
}
var sizeValue: CGSize {
return CGSize(width: x, height: y)
}
}
extension CGPoint {
var vector3dValue: Vector3D {
return Vector3D(x: x, y: y, z: 0)
}
}
extension CGSize {
var vector3dValue: Vector3D {
return Vector3D(x: width, y: height, z: 1)
}
}
extension CATransform3D {
func rotated(_ degrees: CGFloat) -> CATransform3D {
return CATransform3DRotate(self, degrees.toRadians(), 0, 0, 1)
}
func translated(_ translation: CGPoint) -> CATransform3D {
return CATransform3DTranslate(self, translation.x, translation.y, 0)
}
func scaled(_ scale: CGSize) -> CATransform3D {
return CATransform3DScale(self, scale.width, scale.height, 1)
}
func skewed(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D {
return CATransform3DConcat(CATransform3D.makeSkew(skew: skew, skewAxis: skewAxis), self)
}
static func makeSkew(skew: CGFloat, skewAxis: CGFloat) -> CATransform3D {
let mCos = cos(skewAxis.toRadians())
let mSin = sin(skewAxis.toRadians())
let aTan = tan(skew.toRadians())
let transform1 = CATransform3D(m11: mCos, m12: mSin, m13: 0, m14: 0,
m21: -mSin, m22: mCos, m23: 0, m24: 0,
m31: 0, m32: 0, m33: 1, m34: 0,
m41: 0, m42: 0, m43: 0, m44: 1)
let transform2 = CATransform3D(m11: 1, m12: 0, m13: 0, m14: 0,
m21: aTan, m22: 1, m23: 0, m24: 0,
m31: 0, m32: 0, m33: 1, m34: 0,
m41: 0, m42: 0, m43: 0, m44: 1)
let transform3 = CATransform3D(m11: mCos, m12: -mSin, m13: 0, m14: 0,
m21: mSin, m22: mCos, m23: 0, m24: 0,
m31: 0, m32: 0, m33: 1, m34: 0,
m41: 0, m42: 0, m43: 0, m44: 1)
return CATransform3DConcat(transform3, CATransform3DConcat(transform2, transform1))
}
static func makeTransform(anchor: CGPoint,
position: CGPoint,
scale: CGSize,
rotation: CGFloat,
skew: CGFloat?,
skewAxis: CGFloat?) -> CATransform3D {
if let skew = skew, let skewAxis = skewAxis {
return CATransform3DMakeTranslation(position.x, position.y, 0).rotated(rotation).skewed(skew: -skew, skewAxis: skewAxis).scaled(scale * 0.01).translated(anchor * -1)
}
return CATransform3DMakeTranslation(position.x, position.y, 0).rotated(rotation).scaled(scale * 0.01).translated(anchor * -1)
}
}
|
mit
|
a40eb439947a59d197451438b1e7e0ff
| 25.155963 | 171 | 0.592248 | 3.532838 | false | false | false | false |
zmian/xcore.swift
|
Sources/Xcore/SwiftUI/Extensions/View+Extensions.swift
|
1
|
5437
|
//
// Xcore
// Copyright © 2020 Xcore
// MIT license, see LICENSE file for details
//
import SwiftUI
extension View {
/// Embed this view in a navigation view.
///
/// - Note: This method is internal on purpose to allow the app target to
/// declare their own variant in case they want to use this method name to
/// apply any additional modifications (e.g., setting the navigation view style
/// `.navigationViewStyle(.stack)`).
func embedInNavigation() -> some View {
NavigationView { self }
}
/// Wraps this view with a type eraser.
///
/// - Returns: An `AnyView` wrapping this view.
public func eraseToAnyView() -> AnyView {
AnyView(self)
}
}
// MARK: - BackgroundColor
extension View {
/// Sets the background color behind this view.
public func backgroundColor(_ color: Color, ignoresSafeAreaEdges edges: Edge.Set = .all) -> some View {
background(
color
.ignoresSafeArea(edges: edges)
)
}
/// Sets the background color behind this view.
public func backgroundColor(ignoresSafeAreaEdges edges: Edge.Set = .all, _ color: () -> Color) -> some View {
background(
color()
.ignoresSafeArea(edges: edges)
)
}
/// Sets the background color behind this view.
@_disfavoredOverload
public func backgroundColor(_ color: UIColor, ignoresSafeAreaEdges edges: Edge.Set = .all) -> some View {
background(
Color(color)
.ignoresSafeArea(edges: edges)
)
}
/// Sets the background color behind this view.
@_disfavoredOverload
public func backgroundColor(ignoresSafeAreaEdges edges: Edge.Set = .all, _ color: () -> UIColor) -> some View {
background(
Color(color())
.ignoresSafeArea(edges: edges)
)
}
}
// MARK: - ForegroundColor
extension View {
/// Sets the color that the view uses for foreground elements.
public func foregroundColor(_ color: () -> Color) -> some View {
foregroundColor(color())
}
/// Sets the color that the view uses for foreground elements.
@_disfavoredOverload
public func foregroundColor(_ color: () -> UIColor) -> some View {
foregroundColor(Color(color()))
}
/// Sets the color that the view uses for foreground elements.
@_disfavoredOverload
public func foregroundColor(_ color: UIColor) -> some View {
foregroundColor(Color(color))
}
}
// MARK: - ForegroundColor: Text
extension Text {
/// Sets the color that the view uses for foreground elements.
public func foregroundColor(_ color: () -> Color) -> Text {
foregroundColor(color())
}
/// Sets the color that the view uses for foreground elements.
@_disfavoredOverload
public func foregroundColor(_ color: () -> UIColor) -> Text {
foregroundColor(Color(color()))
}
/// Sets the color that the view uses for foreground elements.
@_disfavoredOverload
public func foregroundColor(_ color: UIColor) -> Text {
foregroundColor(Color(color))
}
}
// MARK: - Tint & Accent Color
extension View {
@available(iOS, introduced: 14, deprecated: 15, message: "Use .tint() and .accentColor() directly.")
@ViewBuilder
func _xtint(_ tint: Color?) -> some View {
if #available(iOS 15.0, *) {
self.tint(tint)
.accentColor(tint)
} else {
self.accentColor(tint)
}
}
}
// MARK: - Shadow
extension View {
func floatingShadow() -> some View {
shadow(color: Color(white: 0, opacity: 0.08), radius: 8, x: 0, y: 4)
}
}
// MARK: - Hidden
extension View {
/// Hide or show the view based on a boolean value.
///
/// Example for visibility:
///
/// ```swift
/// Text("Label")
/// .hidden(true)
/// ```
///
/// Example for complete removal:
///
/// ```swift
/// Text("Label")
/// .hidden(true, remove: true)
/// ```
///
/// - Parameters:
/// - hidden: Set to `false` to show the view. Set to `true` to hide the view.
/// - remove: Boolean value indicating whether or not to remove the view.
@ViewBuilder
public func hidden(_ hidden: Bool, remove: Bool = false) -> some View {
if hidden {
if !remove {
self.hidden()
}
} else {
self
}
}
}
// MARK: - Accessibility
extension View {
/// Adds a label to the view that describes its contents.
///
/// Use this method to provide an accessibility label for a view that doesn’t
/// display text, like an icon. For example, you could use this method to label
/// a button that plays music with the text “Play”. Don’t include text in the
/// label that repeats information that users already have. For example, don’t
/// use the label “Play button” because a button already has a trait that
/// identifies it as a button.
public func accessibilityLabel(_ label: String?...) -> some View {
accessibilityLabel(Text(label.joined(separator: ", ")))
}
}
// MARK: - Spacer
public func Spacer(height: CGFloat) -> some View {
Spacer()
.frame(height: height)
}
public func Spacer(width: CGFloat) -> some View {
Spacer()
.frame(width: width)
}
|
mit
|
03570bf2019b8a4b9b9bf228172c6a51
| 27.387435 | 115 | 0.599963 | 4.40813 | false | false | false | false |
simonnarang/Fandom
|
Desktop/Fandom-IOS-master/Fandomm/PreferecesTableViewController.swift
|
1
|
5482
|
//
// PreferecesTableViewController.swift
// Fandomm
//
// Created by Simon Narang on 11/21/15.
// Copyright © 2015 Simon Narang. All rights reserved.
//
import UIKit
class PreferecesTableViewController: UITableViewController {
var usernameTwoTextFour = String()
override func viewDidLoad() {
super.viewDidLoad()
let redisClient:RedisClient = RedisClient(host:"localhost", port:6379, loggingBlock:{(redisClient:AnyObject, message:String, severity:RedisLogSeverity) in
var debugString:String = message
debugString = debugString.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
debugString = debugString.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
print("Log (\(severity.rawValue)): \(debugString)")
})
// performSegueWithIdentifier("logOutSegue", sender: nil)
//self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
// 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()
}
@IBAction func changePassword(sender: AnyObject) {
performSegueWithIdentifier("changePassword", sender: nil)
print("change PW screen opened")
}
@IBAction func changeusername(sender: AnyObject) {
performSegueWithIdentifier("changeUsername", sender: nil)
print("change username screen opened")
}
@IBAction func lougout(sender: AnyObject) {
performSegueWithIdentifier("logOutSegue", sender: nil)
}
let preferencesButtonsStrings = ["edit your profile", "log out", "delete account", "developer settings"]
var userameTwoTextFive = String()
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
//let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "changePassword" {
let destViewContOne: ChangePWViewController = segue.destinationViewController as! ChangePWViewController
destViewContOne.usernameFourTextOne = self.usernameTwoTextFour
}else if segue.identifier == "changeUsername" {
let destViewContOne: ChangeUsernameViewController = segue.destinationViewController as! ChangeUsernameViewController
destViewContOne.usernameFourTextTwo = self.usernameTwoTextFour
}else {
print("there is an undocumented segue form the preferences tab")
}
}
/*override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("preferencesCell", forIndexPath: indexPath)
let preferenceString = preferencesButtonsStrings[indexPath.row]
// Configure the cell...
return cell
}*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
unlicense
|
2f2b46aa19acabbac1ceef9fbca117d8
| 40.522727 | 162 | 0.690932 | 5.604294 | false | false | false | false |
dkhamsing/osia
|
Swift/osia/List/AppCell.swift
|
1
|
2758
|
//
// AppCell.swift
// osia
//
// Created by Daniel Khamsing on 5/2/20.
// Copyright © 2020 Daniel Khamsing. All rights reserved.
//
import UIKit
final class AppCell: UITableViewCell {
static let ReuseIdentifier = "AppCell"
var app: App? {
didSet {
textLabel?.text = app?.title
detailTextLabel?.text = app?.subtitle
}
}
override func prepareForReuse() {
super.prepareForReuse()
textLabel?.text = nil
detailTextLabel?.text = nil
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
textLabel?.numberOfLines = 0
detailTextLabel?.numberOfLines = 0
detailTextLabel?.textColor = .gray
}
required init?(coder: NSCoder) {
self.init()
}
}
private extension App {
var subtitle: String? {
var s: [String] = []
s.safeAppend(s: description)
s.safeAppend(s: tagDisplay)
s.safeAppend(s: dateDisplay)
return s.joined(separator: "\n")
}
}
private extension App {
var dateDisplay: String? {
return dateUpdated?.date?.yearDisplay ?? dateUpdated
}
var tagDisplay: String? {
guard
let t = tags,
t.count > 0 else { return nil }
return t.joined(separator: " ")
}
}
private extension Array {
mutating func safeAppend(s: Element?) {
guard let e = s else { return }
self.append(e)
}
}
private extension Date {
var yearDisplay: String? {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.year], from: self)
guard let year = dateComponents.year else { return nil }
return "\(year)"
}
}
extension String {
var date: Date? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "MMM d yyyy"
if let date = dateFormatter.date(from: self) {
return date
}
dateFormatter.dateFormat = "MMM d, yyyy"
if let date = dateFormatter.date(from: self) {
return date
}
dateFormatter.dateFormat = "E MMM d HH:mm:ss yyyy Z"
if let date = dateFormatter.date(from: self) {
return date
}
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
if let date = dateFormatter.date(from: self) {
return date
}
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = dateFormatter.date(from: self) {
return date
}
return nil
}
}
|
mit
|
f9d48c4c4d0160b32837993cc6e56fe9
| 22.564103 | 99 | 0.586507 | 4.274419 | false | false | false | false |
kashesoft/kjob-apple
|
Sources/Logger.swift
|
1
|
1124
|
/*
* Copyright (C) 2016 Andrey Kashaed
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
class Logger {
private static let timeFormatter: DateFormatter = {
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss.SSS"
return timeFormatter
}()
private static var enabled: Bool = false
static func setEnabled(_ enabled: Bool) {
self.enabled = enabled
}
static func log(_ message: String) {
if enabled {
print("\(timeFormatter.string(from: Date())) \(message)")
}
}
}
|
apache-2.0
|
a4c68aa2f1a8dbf0e164f6c37d608de1
| 27.820513 | 74 | 0.671708 | 4.373541 | false | false | false | false |
michaello/Aloha
|
AlohaGIF/CameraViewController.swift
|
1
|
7121
|
//
// CameraViewController.swift
// AlohaGIF
//
// Created by Michal Pyrka on 16/04/2017.
// Copyright © 2017 Michal Pyrka. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
let maximumMovieLength: CGFloat = 10.0
enum CameraType {
case front
case back
}
final class CameraViewController: UIViewController {
private enum Constants {
static let recordButtonIntervalIncrementTime = 0.1
static let recordButtonMinimumRecordingTime = 1.0
}
@IBOutlet weak var recordButton: RecordButton!
@IBOutlet private weak var previewView: PreviewView!
@IBOutlet private weak var bottomCameraView: UIView!
@IBOutlet private weak var videosButton: UIButton!
@IBOutlet fileprivate var popoverView: PopoverView!
private var effectView: UIVisualEffectView!
var isRecordingLongEnoughToProcess: Bool {
return recording.end() > Constants.recordButtonMinimumRecordingTime
}
private var recordButtonTimer: Timer?
private var recordButtonProgress: CGFloat = 0.0
private var isRecording = false
private var cameraType = CameraType.front
private var recording = Recording()
let assetController = AssetController()
fileprivate let speechController = SpeechController()
private lazy var cameraController = CameraController(previewView: self.previewView, delegate: self)
private let permissionController = PermissionController()
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
cameraController.prepareCamera()
permissionController.requestForAllPermissions { _ in }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraController.startRunning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
cameraController.stopRunning()
}
func updateRecordButtonProgress() {
recordButtonProgress = recordButtonProgress + (CGFloat(Constants.recordButtonIntervalIncrementTime) / maximumMovieLength)
recordButton.setProgress(recordButtonProgress)
if recordButtonProgress >= 1.0 {
stopRecordingAction()
}
}
func presentVideoPreviewViewController(with asset: AVAsset?, speechArray: [SpeechModel]? = nil) {
guard let asset = asset else { return }
let videoPreviewViewController = self.storyboard?.instantiateViewController(withIdentifier: String(describing: VideoPreviewViewController.self)) as! VideoPreviewViewController
videoPreviewViewController.selectedVideo = asset
if let speechArray = speechArray {
videoPreviewViewController.speechArray = speechArray
}
present(videoPreviewViewController, animated: true)
}
@IBAction func changeCameraAction(_ sender: UIButton) {
cameraController.changeCamera()
}
@IBAction func videosButtonAction(_ sender: UIButton) {
present(ImagePickerController.defaultController(delegate: self), animated: true)
}
@IBAction func startRecordingAction() {
recording.start()
isRecording = true
Logger.verbose("Started recording. \(Date())")
recordButtonTimer = .scheduledTimer(timeInterval: Constants.recordButtonIntervalIncrementTime, target: self, selector: #selector(CameraViewController.updateRecordButtonProgress), userInfo: nil, repeats: true)
cameraController.startRecording()
}
@IBAction func stopRecordingAction() {
guard isRecording else { return }
isRecording = false
Logger.verbose("Ended recording. Recording time: \(recording.end()) seconds")
recordButtonStopRecording()
guard UIDevice.isNotSimulator else { return }
cameraController.stopRecording()
}
fileprivate func performSpeechDetection(from asset: AVAsset) {
speechController.detectSpeechPromise(from: asset)
.then(on: DispatchQueue.main) { [unowned self] speechArray in
self.presentVideoPreviewViewController(with: asset, speechArray: speechArray)
}
.catch(on: DispatchQueue.main) { _ in
UIAlertController.show(.speechNotDetected)
}
.always(on: DispatchQueue.main) {
self.recordButton.stopLoading()
}
}
private func recordButtonStopRecording() {
reactRecordButtonOnEndedRecording()
recordButtonTimer?.invalidate()
recordButtonProgress = 0.0
recordButton.buttonState = .idle
}
private func reactRecordButtonOnEndedRecording() {
if isRecordingLongEnoughToProcess {
recordButton.startLoading()
} else {
popoverView.show(from: recordButton)
}
}
private func setupLayout() {
setupVideosButton()
effectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
effectView.frame = bottomCameraView.bounds
bottomCameraView.insertSubview(effectView, at: 0)
}
private func setupVideosButton() {
videosButton.setTitleColor(.themeColor, for: [])
}
}
extension CameraViewController: CameraControllerDelegate {
func didFinishRecording(asset: AVAsset) {
guard isRecordingLongEnoughToProcess else {
Logger.verbose("Recording too short to perform speech detection. Aborting.")
return
}
performSpeechDetection(from: asset)
}
}
extension CameraViewController: UINavigationControllerDelegate, UIVideoEditorControllerDelegate {
func videoEditorController(_ editor: UIVideoEditorController, didSaveEditedVideoToPath editedVideoPath: String) {
recordButton.startLoading()
editor.dismiss(animated: true) {
let asset = AVURLAsset(url: URL(fileURLWithPath: editedVideoPath))
self.performSpeechDetection(from: asset)
}
}
}
extension CameraViewController: ImagePickerDelegate {
func tooLongMovieSelected() {
Logger.info("User tapped movie that is too long.")
UIAlertController.show(.tooLongVideo(limit: Int(maximumMovieLength)))
}
func doneButtonDidPress(_ imagePicker: ImagePickerController, asset: PHAsset) {
imagePicker.dismiss(animated: true) {
self.assetController.AVAssetPromise(from: asset)
.then(on: DispatchQueue.main) { [unowned self] videoAsset in
self.presentVideoEditorViewController(videoToEdit: videoAsset)
}
}
}
private func presentVideoEditorViewController(videoToEdit video: AVAsset) {
guard let videoPath = (video as? AVURLAsset)?.url.path else { return }
recordButton.startLoading()
let videoEditorController = UIVideoEditorController.defaultController(maximumDuration: TimeInterval(maximumMovieLength), delegate: self, videoPath: videoPath)
present(videoEditorController, animated: true) { [unowned self] in
self.recordButton.stopLoading()
}
}
}
|
mit
|
d0d7a05b610db799aafac1aa09c24169
| 36.277487 | 216 | 0.691854 | 5.426829 | false | false | false | false |
arjungupta99/SwiftChess
|
SwiftChess/Game/Square.swift
|
1
|
1767
|
//
// Square.swift
// SwiftChess
//
// Created by Arjun Gupta on 3/1/16.
// Copyright © 2016 ArjunGupta. All rights reserved.
//
import Foundation
import UIKit
protocol SquareDelegate:class {
func squarePressed(square:Square, position:(Int, Int))
}
class Square:NSObject,PositionProtocol, SquareViewDelegate {
var delegate:SquareDelegate?
var view :SquareView?
var position :(Alpha, Int)!
var occupyingPiece :Piece? {
didSet {
if let pieceView = occupyingPiece?.view {
self.view!.addSubview(pieceView)
occupyingPiece!.view!.frame = CGRectMake(5, 5, self.view!.frame.size.width - 10, self.view!.frame.size.height - 10)
}
}
}
init(position:(Alpha, Int), sqWidth:CGFloat, delegate:SquareDelegate!) {
super.init()
self.delegate = delegate
self.position = position
self.occupyingPiece = nil
let i = position.0.rawValue
let j = position.1
//Square View
var isLight:Bool!
if (i % 2 == 0) { isLight = (j % 2 == 0) ? false : true }
else { isLight = (j % 2 != 0) ? false : true }
self.view = SquareView(frame: CGRectMake(CGFloat(i)*sqWidth,CGFloat(j)*sqWidth,sqWidth, sqWidth), isLight: isLight, delegate:self)
self.view!.position = (i, j)
}
func squareViewPressed(position: (Int, Int)) {
self.delegate?.squarePressed(self, position: position)
}
func changeActiveState(active:Bool) {
self.view?.changeActiveState(active, occupyingPieceColorWhite: self.occupyingPiece?.colorIsWhite)
}
}
protocol PositionProtocol {
var position:(Alpha, Int)! { get }
}
|
mit
|
4b6dadd88efe321fde605182a1527e64
| 28.45 | 138 | 0.601359 | 3.889868 | false | false | false | false |
WebAPIKit/WebAPIKit
|
Sources/WebAPIKit/Stub/StubPathTemplate.swift
|
1
|
3467
|
/**
* WebAPIKit
*
* Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows:
*
* 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
/// A url path template contains variables as `{name}`. Like "/api/v{version}/{owner}/{repo}/tags".
public struct StubPathTemplate {
fileprivate var variables: [String]
fileprivate var pattern: String?
fileprivate let template: String
public init(_ template: String) {
self.template = template
var variables = [String]()
var pattern = template as NSString
// swiftlint:disable:next force_try
let regExp = try! NSRegularExpression(pattern: "\\{\\w*?\\}", options: [])
for match in regExp.matches(in: template, options: [], range: template.nsRange).reversed() {
let range = match.range
guard range.length > 2 else { continue }
let nameRange = NSRange(location: range.location + 1, length: range.length - 2)
variables.append(pattern.substring(with: nameRange))
pattern = pattern.replacingCharacters(in: range, with: "(\\w*?)") as NSString
}
self.variables = variables.reversed()
self.pattern = pattern as String
}
}
extension StubPathTemplate {
/// Check if a path matches the template.
public func match(_ path: String) -> Bool {
guard let pattern = pattern else { return false }
let regExp = try? NSRegularExpression(pattern: "^\(pattern)$", options: [])
return regExp?.firstMatch(in: path, options: [], range: path.nsRange) != nil
}
public typealias VariableValues = [String: String]
/// Parse variables from a path.
public func parse(_ path: String) -> VariableValues {
var data = [String: String]()
guard variables.count > 0 else { return data }
guard let pattern = pattern else { return data }
let regExp = try? NSRegularExpression(pattern: "\(pattern)$", options: [])
guard let match = regExp?.firstMatch(in: path, options: [], range: path.nsRange) else { return data }
let nsPath = path as NSString
for i in 1 ..< match.numberOfRanges {
data[variables[i - 1]] = nsPath.substring(with: match.rangeAt(i))
}
return data
}
}
private extension String {
var nsRange: NSRange {
return NSRange(location: 0, length: characters.count)
}
}
|
mit
|
9a4f20ac33ebe8d407ad18a0dd03a61e
| 36.684783 | 109 | 0.666282 | 4.39417 | false | false | false | false |
masukomi/fenestro
|
Fenestro/AppDelegate.swift
|
1
|
3213
|
//
// AppDelegate.swift
// Fenestro
//
// Created by Kåre Morstøl on 21.10.15.
// Copyright © 2015 Corporate Runaways, LLC. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
/** The current location of the command line application, or nil if it was not found. */
var cliAppDirectory: NSURL? {
let path = NSUserDefaults.standardUserDefaults().URLForKey("CliAppPath")
return path.flatMap {
$0.URLByAppendingPathComponent("fenestro").checkResourceIsReachableAndReturnError(nil) ? $0 : nil
}
}
/** Install the bundled command line application to this directory. */
func installCliApp (directory: NSURL) throws {
let frompath = NSBundle.mainBundle().URLForResource("fenestro", withExtension: "")!
let topath = directory.URLByAppendingPathComponent("fenestro")
try NSFileManager.defaultManager().copyItemAtURL(frompath, toURL: topath)
NSUserDefaults.standardUserDefaults().setURL(directory, forKey: "CliAppPath")
}
func showError (error: ErrorType) {
NSAlert(error: error as NSError).runModal()
}
func applicationWillFinishLaunching(notification: NSNotification) {
// Make our subclass the sharedDocumentController.
let _ = DocumentController()
// If commandline application cannot be found, install it.
if self.cliAppDirectory == nil {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.allowsMultipleSelection = false
panel.prompt = "Select"
panel.showsHiddenFiles = true
panel.title = "Install commandline application"
panel.message = "Select the location for the commandline application. It should be a directory listed in the PATH environment variable for easy access."
panel.directoryURL = NSURL(fileURLWithPath: "/usr/local/bin")
if panel.runModal() == NSFileHandlingPanelOKButton {
do {
try installCliApp(panel.URLs.first!)
} catch {
showError(error)
}
}
}
}
}
class DocumentController: NSDocumentController {
var timeoflastopening = NSDate.distantPast()
var maxTimeWithoutNewWindow = 2.0;
/*
If they're just opening one file we don't need to be showing a sidebar.
If they're throwing lots of files at us quickly, then sidebar.
*/
override func openDocumentWithContentsOfURL (url: NSURL, display displayDocument: Bool,
completionHandler: (NSDocument?, Bool, NSError?) -> Void) {
var url = url
if url.lastPathComponent == ".fenestroreadme" {
url = Document.defaultpath
}
let lastOpenWasRecent = NSDate().timeIntervalSinceDate(timeoflastopening) < maxTimeWithoutNewWindow
if url.lastPathComponent != " .html" &&
lastOpenWasRecent,
let document = self.documents.last as? Document {
document.addFile(name: url.lastPathComponent ?? "", path: url)
completionHandler(document, true, nil)
} else {
super.openDocumentWithContentsOfURL(url, display: displayDocument, completionHandler: completionHandler)
}
timeoflastopening = url.lastPathComponent == " .html" ? NSDate.distantPast() : NSDate()
}
/** Prevent recent documents from being displayed in the dock icon menu. */
override func noteNewRecentDocument(document: NSDocument) { }
}
|
mit
|
a0eee581d61bb3dc2081cfd62293e588
| 32.789474 | 155 | 0.738941 | 3.977695 | false | false | false | false |
plivesey/SwiftGen
|
GenumKit/Parsers/ColorsFileParser.swift
|
1
|
7709
|
//
// GenumKit
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Foundation
import AppKit.NSColor
import PathKit
public protocol ColorsFileParser {
var colors: [String: UInt32] { get }
}
public enum ColorsParserError: Error, CustomStringConvertible {
case invalidHexColor(string: String, key: String?)
case invalidFile(reason: String)
public var description: String {
switch self {
case .invalidHexColor(string: let string, key: let key):
let keyInfo = key.flatMap { k in " for key \"\(k)\"" } ?? ""
return "error: Invalid hex color \"\(string)\" found\(keyInfo)."
case .invalidFile(reason: let reason):
return "error: Unable to parse file. \(reason)"
}
}
}
// MARK: - Private Helpers
fileprivate func parse(hex hexString: String, key: String? = nil) throws -> UInt32 {
let scanner = Scanner(string: hexString)
let prefixLen: Int
if scanner.scanString("#", into: nil) {
prefixLen = 1
} else if scanner.scanString("0x", into: nil) {
prefixLen = 2
} else {
prefixLen = 0
}
var value: UInt32 = 0
guard scanner.scanHexInt32(&value) else {
throw ColorsParserError.invalidHexColor(string: hexString, key: key)
}
let len = hexString.lengthOfBytes(using: .utf8) - prefixLen
if len == 6 {
// There were no alpha component, assume 0xff
value = (value << 8) | 0xff
}
return value
}
// MARK: - Text File Parser
public final class ColorsTextFileParser: ColorsFileParser {
public private(set) var colors = [String: UInt32]()
public init() {}
public func addColor(named name: String, value: String) throws {
try addColor(named: name, value: parse(hex: value, key: name))
}
public func addColor(named name: String, value: UInt32) {
colors[name] = value
}
public func keyValueDict(from path: Path, withSeperator seperator: String = ":") throws -> [String:String] {
let content = try path.read(.utf8)
let lines = content.components(separatedBy: CharacterSet.newlines)
let whitespace = CharacterSet.whitespaces
let skippedCharacters = NSMutableCharacterSet()
skippedCharacters.formUnion(with: whitespace)
skippedCharacters.formUnion(with: skippedCharacters as CharacterSet)
var dict: [String: String] = [:]
for line in lines {
let scanner = Scanner(string: line)
scanner.charactersToBeSkipped = skippedCharacters as CharacterSet
var key: NSString?
var value: NSString?
guard scanner.scanUpTo(seperator, into: &key) &&
scanner.scanString(seperator, into: nil) &&
scanner.scanUpToCharacters(from: whitespace, into: &value) else {
continue
}
if let key: String = key?.trimmingCharacters(in: whitespace),
let value: String = value?.trimmingCharacters(in: whitespace) {
dict[key] = value
}
}
return dict
}
private func colorValue(forKey key: String, onDict dict: [String: String]) -> String {
var currentKey = key
var stringValue: String = ""
while let value = dict[currentKey]?.trimmingCharacters(in: CharacterSet.whitespaces) {
currentKey = value
stringValue = value
}
return stringValue
}
// Text file expected to be:
// - One line per entry
// - Each line composed by the color name, then ":", then the color hex representation
// - Extra spaces will be skipped
public func parseFile(at path: Path, separator: String = ":") throws {
do {
let dict = try keyValueDict(from: path, withSeperator: separator)
for key in dict.keys {
try addColor(named: key, value: colorValue(forKey: key, onDict: dict))
}
} catch let error as ColorsParserError {
throw error
} catch let error {
throw ColorsParserError.invalidFile(reason: error.localizedDescription)
}
}
}
// MARK: - CLR File Parser
public final class ColorsCLRFileParser: ColorsFileParser {
public private(set) var colors = [String: UInt32]()
public init() {}
public func parseFile(at path: Path) throws {
if let colorsList = NSColorList(name: "UserColors", fromFile: path.description) {
for colorName in colorsList.allKeys {
colors[colorName] = colorsList.color(withKey: colorName)?.rgbColor?.hexValue
}
} else {
throw ColorsParserError.invalidFile(reason: "Invalid color list")
}
}
}
extension NSColor {
fileprivate var rgbColor: NSColor? {
return usingColorSpaceName(NSCalibratedRGBColorSpace)
}
fileprivate var hexValue: UInt32 {
let hexRed = UInt32(redComponent * 0xFF) << 24
let hexGreen = UInt32(greenComponent * 0xFF) << 16
let hexBlue = UInt32(blueComponent * 0xFF) << 8
let hexAlpha = UInt32(alphaComponent * 0xFF)
return hexRed | hexGreen | hexBlue | hexAlpha
}
}
// MARK: - Android colors.xml File Parser
public final class ColorsXMLFileParser: ColorsFileParser {
static let colorTagName = "color"
static let colorNameAttribute = "name"
public private(set) var colors = [String: UInt32]()
public init() {}
private class ParserDelegate: NSObject, XMLParserDelegate {
var parsedColors = [String: UInt32]()
var currentColorName: String? = nil
var currentColorValue: String? = nil
var colorParserError: Error? = nil
@objc func parser(_ parser: XMLParser, didStartElement elementName: String,
namespaceURI: String?, qualifiedName qName: String?,
attributes attributeDict: [String: String]) {
guard elementName == ColorsXMLFileParser.colorTagName else { return }
currentColorName = attributeDict[ColorsXMLFileParser.colorNameAttribute]
currentColorValue = nil
}
@objc func parser(_ parser: XMLParser, foundCharacters string: String) {
currentColorValue = (currentColorValue ?? "") + string
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String,
namespaceURI: String?, qualifiedName qName: String?) {
guard elementName == ColorsXMLFileParser.colorTagName else { return }
guard let colorName = currentColorName, let colorValue = currentColorValue else { return }
do {
parsedColors[colorName] = try parse(hex: colorValue, key: colorName)
} catch let error as ColorsParserError {
colorParserError = error
parser.abortParsing()
} catch {
parser.abortParsing()
}
currentColorName = nil
currentColorValue = nil
}
}
public func parseFile(at path: Path) throws {
let parser = XMLParser(data: try path.read())
let delegate = ParserDelegate()
parser.delegate = delegate
if parser.parse() {
colors = delegate.parsedColors
} else if let error = delegate.colorParserError {
throw error
} else {
let reason = parser.parserError?.localizedDescription ?? "Unknown XML parser error."
throw ColorsParserError.invalidFile(reason: reason)
}
}
}
// MARK: - JSON File Parser
public final class ColorsJSONFileParser: ColorsFileParser {
public private(set) var colors = [String: UInt32]()
public init() {}
public func parseFile(at path: Path) throws {
do {
let json = try JSONSerialization.jsonObject(with: try path.read(), options: [])
guard let dict = json as? [String: String] else {
throw ColorsParserError.invalidFile(reason: "Invalid structure, must be an object with string values.")
}
for (key, value) in dict {
colors[key] = try parse(hex: value, key: key)
}
} catch let error as ColorsParserError {
throw error
} catch let error {
throw ColorsParserError.invalidFile(reason: error.localizedDescription)
}
}
}
|
mit
|
3ab375c4d0d259e284a713e01a79967a
| 29.231373 | 111 | 0.67285 | 4.335771 | false | false | false | false |
artsy/Emergence
|
Emergence/Contexts/Main Menu/Getting Shows/ShowEmitter.swift
|
1
|
1092
|
import Foundation
/// A simple pattern for saying "I take some shows and will occasionally get more"
typealias EmitterUpdateCallback = ((shows: [Show]) -> ())
protocol ShowEmitter {
var title: String { get }
var numberOfShows: Int { get }
func showAtIndexPath(index: NSIndexPath) -> Show
func getShows()
func onUpdate( callback: EmitterUpdateCallback )
func isEqualTo(show: ShowEmitter) -> Bool
}
extension ShowEmitter {
func isEqualTo(show: ShowEmitter) -> Bool {
return title == show.title
}
}
class StubbyEmitter: NSObject, ShowEmitter {
let title:String
var numberOfShows = 0
var stubs = [Show]()
init(title: String) {
self.title = title
super.init()
}
func showAtIndexPath(index: NSIndexPath) -> Show {
return stubs[index.row]
}
func getShows() {
stubs = [Show.stubbedShow(),Show.stubbedShow(),Show.stubbedShow(),Show.stubbedShow()]
numberOfShows = stubs.count
}
func onUpdate( callback: EmitterUpdateCallback ) {
callback(shows:stubs)
}
}
|
mit
|
c1e06fd22c4c841148828e5609421dcb
| 22.73913 | 93 | 0.647436 | 4.2 | false | false | false | false |
acrookston/ACRAutoComplete
|
ACRAutoComplete/Classes/AutoComplete.swift
|
1
|
2818
|
//
// AutoComplete.swift
//
// Created by Andrew C on 9/19/16.
//
//
import Foundation
public protocol Searchable: Hashable {
var keywords: [String] { get }
}
open class AutoComplete<T: Searchable> {
lazy var nodes = [Character: AutoComplete<T>]()
lazy var items = [T]()
public init() { }
// MARK: - Insert / index
public func insert(_ object: T) {
for string in object.keywords {
var tokens = tokenize(string)
var currentIndex = 0
var maxIndex = tokens.count
insert(tokens: &tokens, at: ¤tIndex, max: &maxIndex, object: object)
}
}
private func insert(tokens: inout [Character],
at currentIndex: inout Int,
max maxIndex: inout Int,
object: T) {
if currentIndex < maxIndex {
let current = tokens[currentIndex]
currentIndex += 1
if nodes[current] == nil {
nodes[current] = AutoComplete<T>()
}
nodes[current]?.insert(tokens: &tokens, at: ¤tIndex, max: &maxIndex, object: object)
} else {
items.append(object)
}
}
public func insert(_ set: [T]) {
for object in set {
insert(object)
}
}
// MARK: - Search
public func search(_ string: String) -> [T] {
var merged: Set<T>?
for word in string.components(separatedBy: " ") {
var wordResults = Set<T>()
var tokens = tokenize(word)
var maxIndex = tokens.count
var currentIndex = 0
find(tokens: &tokens, at: ¤tIndex, max: &maxIndex, into: &wordResults)
if let results = merged {
merged = results.intersection(wordResults)
} else {
merged = wordResults
}
}
if let results = merged {
return Array(results)
}
return []
}
private func find(tokens: inout [Character],
at currentIndex: inout Int,
max maxIndex: inout Int,
into results: inout Set<T>) {
if currentIndex < maxIndex {
let current = tokens[currentIndex]
currentIndex += 1
nodes[current]?.find(tokens: &tokens, at: ¤tIndex, max: &maxIndex, into: &results)
} else {
insertAll(into: &results)
}
}
func insertAll(into results: inout Set<T>) {
for t in items {
results.insert(t)
}
for (_, child) in nodes {
child.insertAll(into: &results)
}
}
private func tokenize(_ string: String) -> [Character] {
return Array(string.lowercased())
}
}
|
mit
|
74f8ed475b25875a03671eb54621aa12
| 25.838095 | 102 | 0.514549 | 4.567261 | false | false | false | false |
cburrows/swift-protobuf
|
Tests/SwiftProtobufTests/Test_AllTypes_Proto3_Optional.swift
|
1
|
27425
|
// Tests/SwiftProtobufTests/Test_AllTypes.swift - Basic encoding/decoding test
//
// Copyright (c) 2014 - 2020 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This is a thorough test of the binary protobuf encoding and decoding.
/// It attempts to verify the encoded form for every basic proto type
/// and verify correct decoding, including handling of unusual-but-valid
/// sequences and error reporting for invalid sequences.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
class Test_AllTypes_Proto3_Optional: XCTestCase, PBTestHelpers {
typealias MessageTestType = ProtobufUnittest_TestProto3Optional
// Custom decodeSucceeds that also does a round-trip through the Empty
// message to make sure unknown fields are consistently preserved by proto2.
func assertDecodeSucceeds(_ bytes: [UInt8], file: XCTestFileArgType = #file, line: UInt = #line, check: (MessageTestType) -> Bool) {
baseAssertDecodeSucceeds(bytes, file: file, line: line, check: check)
do {
// Make sure unknown fields are preserved by empty message decode/encode
let empty = try ProtobufUnittest_TestEmptyMessage(serializedBytes: bytes)
do {
let newBytes = try empty.serializedBytes()
XCTAssertEqual(bytes, newBytes, "Empty decode/recode did not match", file: file, line: line)
} catch let e {
XCTFail("Reserializing empty threw an error: \(e)", file: file, line: line)
}
} catch {
XCTFail("Empty decoding threw an error", file: file, line: line)
}
}
func assertDebugDescription(_ expected: String, file: XCTestFileArgType = #file, line: UInt = #line, configure: (inout MessageTestType) -> ()) {
var m = MessageTestType()
configure(&m)
let actual = m.debugDescription
XCTAssertEqual(actual, expected, file: file, line: line)
}
//
// Optional Singular types
//
// Setting the values to zero values to ensure when encoded the values are captured.
func testEncoding_optionalInt32() {
assertEncode([8, 0]) {(o: inout MessageTestType) in o.optionalInt32 = 0}
assertDecodeSucceeds([8, 0]) {$0.hasOptionalInt32 && $0.optionalInt32 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_int32: 0\n") {(o: inout MessageTestType) in o.optionalInt32 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalInt32 = 0
o.clearOptionalInt32()
}
let empty = MessageTestType()
var a = empty
a.optionalInt32 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalInt32 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalInt32()
XCTAssertNotEqual(a, b)
b.optionalInt32 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalInt64() {
assertEncode([16, 0]) {(o: inout MessageTestType) in o.optionalInt64 = 0}
assertDecodeSucceeds([16, 0]) {$0.hasOptionalInt64 && $0.optionalInt64 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_int64: 0\n") {(o: inout MessageTestType) in o.optionalInt64 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalInt64 = 0
o.clearOptionalInt64()
}
let empty = MessageTestType()
var a = empty
a.optionalInt64 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalInt64 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalInt64()
XCTAssertNotEqual(a, b)
b.optionalInt64 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalInt64 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalInt64)
XCTAssertTrue(d.hasOptionalInt64)
d.clearOptionalInt64()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalInt64)
XCTAssertFalse(d.hasOptionalInt64)
}
func testEncoding_optionalUint32() {
assertEncode([24, 0]) {(o: inout MessageTestType) in o.optionalUint32 = 0}
assertDecodeSucceeds([24, 0]) {$0.hasOptionalUint32 && $0.optionalUint32 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_uint32: 0\n") {(o: inout MessageTestType) in o.optionalUint32 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalUint32 = 0
o.clearOptionalUint32()
}
let empty = MessageTestType()
var a = empty
a.optionalUint32 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalUint32 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalUint32()
XCTAssertNotEqual(a, b)
b.optionalUint32 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalUint32 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalUint32)
XCTAssertTrue(d.hasOptionalUint32)
d.clearOptionalUint32()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalUint32)
XCTAssertFalse(d.hasOptionalUint32)
}
func testEncoding_optionalUint64() {
assertEncode([32, 0]) {(o: inout MessageTestType) in o.optionalUint64 = 0}
assertDecodeSucceeds([32, 0]) {$0.hasOptionalUint64 && $0.optionalUint64 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_uint64: 0\n") {(o: inout MessageTestType) in o.optionalUint64 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalUint64 = 0
o.clearOptionalUint64()
}
let empty = MessageTestType()
var a = empty
a.optionalUint64 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalUint64 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalUint64()
XCTAssertNotEqual(a, b)
b.optionalUint64 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalUint64 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalUint64)
XCTAssertTrue(d.hasOptionalUint64)
d.clearOptionalUint64()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalUint64)
XCTAssertFalse(d.hasOptionalUint64)
}
func testEncoding_optionalSint32() {
assertEncode([40, 0]) {(o: inout MessageTestType) in o.optionalSint32 = 0}
assertDecodeSucceeds([40, 0]) {$0.hasOptionalSint32 && $0.optionalSint32 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_sint32: 0\n") {(o: inout MessageTestType) in o.optionalSint32 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalSint32 = 0
o.clearOptionalSint32()
}
let empty = MessageTestType()
var a = empty
a.optionalSint32 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalSint32 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalSint32()
XCTAssertNotEqual(a, b)
b.optionalSint32 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalSint32 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalSint32)
XCTAssertTrue(d.hasOptionalSint32)
d.clearOptionalSint32()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalSint32)
XCTAssertFalse(d.hasOptionalSint32)
}
func testEncoding_optionalSint64() {
assertEncode([48, 0]) {(o: inout MessageTestType) in o.optionalSint64 = 0}
assertDecodeSucceeds([48, 0]) {$0.hasOptionalSint64 && $0.optionalSint64 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_sint64: 0\n") {(o: inout MessageTestType) in o.optionalSint64 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalSint64 = 0
o.clearOptionalSint64()
}
let empty = MessageTestType()
var a = empty
a.optionalSint64 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalSint64 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalSint64()
XCTAssertNotEqual(a, b)
b.optionalSint64 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalSint64 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalSint64)
XCTAssertTrue(d.hasOptionalSint64)
d.clearOptionalSint64()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalSint64)
XCTAssertFalse(d.hasOptionalSint64)
}
func testEncoding_optionalFixed32() {
assertEncode([61, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.optionalFixed32 = 0}
assertDecodeSucceeds([61, 0, 0, 0, 0]) {$0.hasOptionalFixed32 && $0.optionalFixed32 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_fixed32: 0\n") {(o: inout MessageTestType) in o.optionalFixed32 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalFixed32 = 0
o.clearOptionalFixed32()
}
let empty = MessageTestType()
var a = empty
a.optionalFixed32 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalFixed32 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalFixed32()
XCTAssertNotEqual(a, b)
b.optionalFixed32 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalFixed32 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalFixed32)
XCTAssertTrue(d.hasOptionalFixed32)
d.clearOptionalFixed32()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalFixed32)
XCTAssertFalse(d.hasOptionalFixed32)
}
func testEncoding_optionalFixed64() {
assertEncode([65, 0, 0, 0, 0, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.optionalFixed64 = UInt64.min}
assertDecodeSucceeds([65, 0, 0, 0, 0, 0, 0, 0, 0]) {$0.hasOptionalFixed64 && $0.optionalFixed64 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_fixed64: 0\n") {(o: inout MessageTestType) in o.optionalFixed64 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalFixed64 = 0
o.clearOptionalFixed64()
}
let empty = MessageTestType()
var a = empty
a.optionalFixed64 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalFixed64 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalFixed64()
XCTAssertNotEqual(a, b)
b.optionalFixed64 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalFixed64 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalFixed64)
XCTAssertTrue(d.hasOptionalFixed64)
d.clearOptionalFixed64()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalFixed64)
XCTAssertFalse(d.hasOptionalFixed64)
}
func testEncoding_optionalSfixed32() {
assertEncode([77, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.optionalSfixed32 = 0}
assertDecodeSucceeds([77, 0, 0, 0, 0]) {$0.hasOptionalSfixed32 && $0.optionalSfixed32 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_sfixed32: 0\n") {(o: inout MessageTestType) in o.optionalSfixed32 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalSfixed32 = 0
o.clearOptionalSfixed32()
}
let empty = MessageTestType()
var a = empty
a.optionalSfixed32 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalSfixed32 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalSfixed32()
XCTAssertNotEqual(a, b)
b.optionalSfixed32 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalSfixed32 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalSfixed32)
XCTAssertTrue(d.hasOptionalSfixed32)
d.clearOptionalSfixed32()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalSfixed32)
XCTAssertFalse(d.hasOptionalSfixed32)
}
func testEncoding_optionalSfixed64() {
assertEncode([81, 0, 0, 0, 0, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.optionalSfixed64 = 0}
assertDecodeSucceeds([81, 0, 0, 0, 0, 0, 0, 0, 0]) {$0.hasOptionalSfixed64 && $0.optionalSfixed64 == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_sfixed64: 0\n") {(o: inout MessageTestType) in o.optionalSfixed64 = 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalSfixed64 = 0
o.clearOptionalSfixed64()
}
let empty = MessageTestType()
var a = empty
a.optionalSfixed64 = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalSfixed64 = 1
XCTAssertNotEqual(a, b)
b.clearOptionalSfixed64()
XCTAssertNotEqual(a, b)
b.optionalSfixed64 = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalSfixed64 = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalSfixed64)
XCTAssertTrue(d.hasOptionalSfixed64)
d.clearOptionalSfixed64()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalSfixed64)
XCTAssertFalse(d.hasOptionalSfixed64)
}
func testEncoding_optionalFloat() {
assertEncode([93, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.optionalFloat = 0.0}
assertDecodeSucceeds([93, 0, 0, 0, 0]) {$0.hasOptionalFloat && $0.optionalFloat == 0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_float: 0.0\n") {
(o: inout MessageTestType) in o.optionalFloat = 0.0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") { (o: inout MessageTestType) in
o.optionalFloat = 1.0
o.clearOptionalFloat()
}
let empty = MessageTestType()
var a = empty
a.optionalFloat = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalFloat = 1
XCTAssertNotEqual(a, b)
b.clearOptionalFloat()
XCTAssertNotEqual(a, b)
b.optionalFloat = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalFloat = 1.0
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalFloat)
XCTAssertTrue(d.hasOptionalFloat)
d.clearOptionalFloat()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalFloat)
XCTAssertFalse(d.hasOptionalFloat)
}
func testEncoding_optionalDouble() {
assertEncode([97, 0, 0, 0, 0, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.optionalDouble = 0.0}
assertDecodeSucceeds([97, 0, 0, 0, 0, 0, 0, 0, 0]) {$0.hasOptionalDouble && $0.optionalDouble == 0.0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_double: 0.0\n") {
(o: inout MessageTestType) in o.optionalDouble = 0.0}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {
(o: inout MessageTestType) in
o.optionalDouble = 0.0
o.clearOptionalDouble()
}
let empty = MessageTestType()
var a = empty
a.optionalDouble = 0
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalDouble = 1
XCTAssertNotEqual(a, b)
b.clearOptionalDouble()
XCTAssertNotEqual(a, b)
b.optionalDouble = 0
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalDouble = 1.0
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalDouble)
XCTAssertTrue(d.hasOptionalDouble)
d.clearOptionalDouble()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalDouble)
XCTAssertFalse(d.hasOptionalDouble)
}
func testEncoding_optionalBool() {
assertEncode([104, 0]) {(o: inout MessageTestType) in o.optionalBool = false}
assertDecodeSucceeds([104, 0]) { $0.hasOptionalBool && $0.optionalBool == false }
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_bool: false\n") {(o: inout MessageTestType) in o.optionalBool = false}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalBool = false
o.clearOptionalBool()
}
let empty = MessageTestType()
var a = empty
a.optionalBool = false
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalBool = true
XCTAssertNotEqual(a, b)
b.clearOptionalBool()
XCTAssertNotEqual(a, b)
b.optionalBool = false
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalBool = true
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalBool)
XCTAssertTrue(d.hasOptionalBool)
d.clearOptionalBool()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalBool)
XCTAssertFalse(d.hasOptionalBool)
}
func testEncoding_optionalString() {
assertEncode([114, 0]) {(o: inout MessageTestType) in o.optionalString = ""}
assertDecodeSucceeds([114, 0]) { $0.hasOptionalString && $0.optionalString == "" }
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_string: \"\"\n") {(o: inout MessageTestType) in o.optionalString = ""}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalString = ""
o.clearOptionalString()
}
let empty = MessageTestType()
var a = empty
a.optionalString = ""
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalString = "a"
XCTAssertNotEqual(a, b)
b.clearOptionalString()
XCTAssertNotEqual(a, b)
b.optionalString = ""
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalString = "blah"
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalString)
XCTAssertTrue(d.hasOptionalString)
d.clearOptionalString()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalString)
XCTAssertFalse(d.hasOptionalString)
}
func testEncoding_optionalBytes() {
assertEncode([122, 0]) {(o: inout MessageTestType) in o.optionalBytes = Data()}
assertDecodeSucceeds([122, 0]) { $0.hasOptionalBytes && $0.optionalBytes == Data() }
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_bytes: \"\"\n") {(o: inout MessageTestType) in o.optionalBytes = Data()}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalBytes = Data()
o.clearOptionalBytes()
}
let empty = MessageTestType()
var a = empty
a.optionalBytes = Data()
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalBytes = Data([1])
XCTAssertNotEqual(a, b)
b.clearOptionalBytes()
XCTAssertNotEqual(a, b)
b.optionalBytes = Data()
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalBytes = Data([1])
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalBytes)
XCTAssertTrue(d.hasOptionalBytes)
d.clearOptionalBytes()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalBytes)
XCTAssertFalse(d.hasOptionalBytes)
}
func testEncoding_optionalCord() {
// The `ctype = CORD` option has no meaning in SwiftProtobuf,
// but test is for completeness.
assertEncode([130, 1, 0]) {(o: inout MessageTestType) in o.optionalCord = ""}
assertDecodeSucceeds([130, 1, 0]) { $0.hasOptionalCord && $0.optionalCord == "" }
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_cord: \"\"\n") {(o: inout MessageTestType) in o.optionalCord = ""}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalCord = ""
o.clearOptionalCord()
}
let empty = MessageTestType()
var a = empty
a.optionalCord = ""
XCTAssertNotEqual(a, empty)
var b = empty
b.optionalCord = "a"
XCTAssertNotEqual(a, b)
b.clearOptionalCord()
XCTAssertNotEqual(a, b)
b.optionalCord = ""
XCTAssertEqual(a, b)
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalCord = "blah"
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalCord)
XCTAssertTrue(d.hasOptionalCord)
d.clearOptionalCord()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalCord)
XCTAssertFalse(d.hasOptionalCord)
}
func testEncoding_optionalNestedMessage() {
assertEncode([146, 1, 0]) {(o: inout MessageTestType) in
o.optionalNestedMessage = MessageTestType.NestedMessage()
}
assertDecodeSucceeds([146, 1, 0]) {$0.hasOptionalNestedMessage && $0.optionalNestedMessage == MessageTestType.NestedMessage()}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_nested_message {\n}\n") {(o: inout MessageTestType) in
o.optionalNestedMessage = MessageTestType.NestedMessage()
}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalNestedMessage = MessageTestType.NestedMessage()
o.clearOptionalNestedMessage()
}
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalNestedMessage.bb = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalNestedMessage)
XCTAssertTrue(d.hasOptionalNestedMessage)
d.clearOptionalNestedMessage()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalNestedMessage)
XCTAssertFalse(d.hasOptionalNestedMessage)
}
func testEncoding_lazyNestedMessage() {
// The `lazy = true` option has no meaning in SwiftProtobuf,
// but test is for completeness.
assertEncode([154, 1, 0]) {(o: inout MessageTestType) in
o.lazyNestedMessage = MessageTestType.NestedMessage()
}
assertDecodeSucceeds([154, 1, 0]) {$0.hasLazyNestedMessage && $0.lazyNestedMessage == MessageTestType.NestedMessage()}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\nlazy_nested_message {\n}\n") {(o: inout MessageTestType) in
o.lazyNestedMessage = MessageTestType.NestedMessage()
}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.lazyNestedMessage = MessageTestType.NestedMessage()
o.clearLazyNestedMessage()
}
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.lazyNestedMessage.bb = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasLazyNestedMessage)
XCTAssertTrue(d.hasLazyNestedMessage)
d.clearLazyNestedMessage()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasLazyNestedMessage)
XCTAssertFalse(d.hasLazyNestedMessage)
}
func testEncoding_optionalNestedEnum() throws {
assertEncode([168, 1, 0]) {(o: inout MessageTestType) in
o.optionalNestedEnum = .unspecified
}
assertDecodeSucceeds([168, 1, 0]) {
$0.hasOptionalNestedEnum && $0.optionalNestedEnum == .unspecified
}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\noptional_nested_enum: UNSPECIFIED\n") {(o: inout MessageTestType) in
o.optionalNestedEnum = .unspecified
}
assertDebugDescription("SwiftProtobufTests.ProtobufUnittest_TestProto3Optional:\n") {(o: inout MessageTestType) in
o.optionalNestedEnum = .unspecified
o.clearOptionalNestedEnum()
}
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalNestedEnum = .bar
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalNestedEnum)
XCTAssertTrue(d.hasOptionalNestedEnum)
d.clearOptionalNestedEnum()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalNestedEnum)
XCTAssertFalse(d.hasOptionalNestedEnum)
}
//
// Optionally doesn't apply to Repeated types
//
}
|
apache-2.0
|
bf8624639da627096faabc902d9eb684
| 38.517291 | 170 | 0.638979 | 4.807187 | false | true | false | false |
apple/swift
|
test/Compatibility/accessibility.swift
|
8
|
51917
|
// RUN: %target-typecheck-verify-swift -swift-version 4
// RUN: %target-typecheck-verify-swift -swift-version 4.2
public protocol PublicProto {
func publicReq()
}
// expected-note@+1 * {{type declared here}}
internal protocol InternalProto {
func internalReq()
}
fileprivate protocol FilePrivateProto {
func filePrivateReq()
}
// expected-note@+1 * {{type declared here}}
private protocol PrivateProto {
func privateReq()
}
public struct PublicStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'public' to satisfy the requirement}} {{3-10=public}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
internal struct InternalStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
fileprivate struct FilePrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
private struct PrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
public struct PublicStructWithInternalExtension: PublicProto, InternalProto, FilePrivateProto, PrivateProto {}
// expected-error@-1 {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}}
// expected-error@-2 {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}}
// expected-error@-3 {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}}
// expected-error@-4 {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}}
internal extension PublicStructWithInternalExtension {
private func publicReq() {} // expected-note {{move the instance method to another extension where it can be declared 'public' to satisfy the requirement}} {{none}}
private func internalReq() {} // expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-11=}}
private func filePrivateReq() {} // expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
}
extension PublicStruct {
public init(x: Int) { self.init() }
}
extension InternalStruct {
public init(x: Int) { self.init() }
}
extension FilePrivateStruct {
public init(x: Int) { self.init() }
}
extension PrivateStruct {
public init(x: Int) { self.init() }
}
public extension PublicStruct {
public func extMemberPublic() {} // expected-warning {{'public' modifier is redundant for instance method declared in a public extension}} {{3-10=}}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension PublicStruct {
public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension PublicStruct {
public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}}
fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}}
private func extImplFilePrivate() {}
}
private extension PublicStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public extension InternalStruct { // expected-error {{extension of internal struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension InternalStruct {
public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension InternalStruct {
public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}}
fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}}
private func extImplFilePrivate() {}
}
private extension InternalStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared internal}} {{1-10=}}
public func extMemberInternal() {}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension FilePrivateStruct {
public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}}
fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}}
private func extImplFilePrivate() {}
}
private extension FilePrivateStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public extension PrivateStruct { // expected-error {{extension of private struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension PrivateStruct { // expected-error {{extension of private struct cannot be declared internal}} {{1-10=}}
public func extMemberInternal() {}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension PrivateStruct { // expected-error {{extension of private struct cannot be declared fileprivate}} {{1-13=}}
public func extMemberFilePrivate() {}
fileprivate func extFuncFilePrivate() {}
private func extImplFilePrivate() {}
}
private extension PrivateStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public struct PublicStructDefaultMethods: PublicProto, InternalProto, PrivateProto {
func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
func internalReq() {}
func privateReq() {}
}
public class Base {
required public init() {}
// expected-note@+1 * {{overridden declaration is here}}
public func foo() {}
// expected-note@+1 * {{overridden declaration is here}}
public internal(set) var bar: Int = 0
// expected-note@+1 * {{overridden declaration is here}}
public subscript () -> () { return () }
}
public extension Base {
open func extMemberPublic() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'public'}} {{none}}
}
internal extension Base {
open func extMemberInternal() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'internal'}} {{none}}
}
public class PublicSub: Base {
private required init() {} // expected-error {{'required' initializer must be accessible wherever class 'PublicSub' can be subclassed}} {{3-10=internal}}
override func foo() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{3-3=public }}
override var bar: Int { // expected-error {{overriding property must be as accessible as the declaration it overrides}} {{3-3=public }}
get { return 0 }
set {}
}
override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{3-3=public }}
}
public class PublicSubGood: Base {
required init() {} // okay
}
internal class InternalSub: Base {
required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'InternalSub' can be subclassed}} {{12-19=internal}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=internal}}
private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=internal}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=internal}}
}
internal class InternalSubGood: Base {
required init() {} // no-warning
override func foo() {}
override var bar: Int {
get { return 0 }
set {}
}
override subscript () -> () { return () }
}
internal class InternalSubPrivateSet: Base {
required init() {}
private(set) override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-16=}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
fileprivate class FilePrivateSub: Base {
required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'FilePrivateSub' can be subclassed}} {{12-19=fileprivate}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}}
private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}}
}
fileprivate class FilePrivateSubGood: Base {
required init() {} // no-warning
override func foo() {}
override var bar: Int {
get { return 0 }
set {}
}
override subscript () -> () { return () }
}
fileprivate class FilePrivateSubGood2: Base {
fileprivate required init() {} // no-warning
fileprivate override func foo() {}
fileprivate override var bar: Int {
get { return 0 }
set {}
}
fileprivate override subscript () -> () { return () }
}
fileprivate class FilePrivateSubPrivateSet: Base {
required init() {}
private(set) override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
private class PrivateSub: Base {
required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'PrivateSub' can be subclassed}} {{12-19=fileprivate}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}}
private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}}
}
private class PrivateSubGood: Base {
required fileprivate init() {}
fileprivate override func foo() {}
fileprivate override var bar: Int {
get { return 0 }
set {}
}
fileprivate override subscript () -> () { return () }
}
private class PrivateSubPrivateSet: Base {
required fileprivate init() {}
fileprivate override func foo() {}
private(set) override var bar: Int { // expected-error {{setter of overriding property must be as accessible as its enclosing type}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
public typealias PublicTA1 = PublicStruct
public typealias PublicTA2 = InternalStruct // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias PublicTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a fileprivate type}}
public typealias PublicTA4 = PrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a private type}}
// expected-note@+1 {{type declared here}}
internal typealias InternalTA1 = PublicStruct
internal typealias InternalTA2 = InternalStruct
internal typealias InternalTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a fileprivate type}}
internal typealias InternalTA4 = PrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a private type}}
public typealias PublicFromInternal = InternalTA1 // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
typealias FunctionType1 = (PrivateStruct) -> PublicStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias FunctionType2 = (PublicStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias FunctionType3 = (PrivateStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias ArrayType = [PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias DictType = [String : PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias GenericArgs = Optional<PrivateStruct> // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
public protocol HasAssocType {
associatedtype Inferred
func test(input: Inferred)
}
public struct AssocTypeImpl: HasAssocType {
public func test(input: Bool) {}
}
public let _: AssocTypeImpl.Inferred?
public let x: PrivateStruct = PrivateStruct() // expected-error {{constant cannot be declared public because its type uses a private type}}
public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{variable cannot be declared public because its type uses a private type}}
public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{variable cannot be declared public because its type uses a private type}}
var internalVar: PrivateStruct? // expected-error {{variable must be declared private or fileprivate because its type uses a private type}}
let internalConstant = PrivateStruct() // expected-error {{constant must be declared private or fileprivate because its type 'PrivateStruct' uses a private type}}
public let publicConstant = [InternalStruct]() // expected-error {{constant cannot be declared public because its type '[InternalStruct]' uses an internal type}}
public struct Properties {
public let x: PrivateStruct = PrivateStruct() // expected-error {{property cannot be declared public because its type uses a private type}}
public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{property cannot be declared public because its type uses a private type}}
public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{property cannot be declared public because its type uses a private type}}
let y = PrivateStruct() // expected-error {{property must be declared fileprivate because its type 'PrivateStruct' uses a private type}}
}
public struct Subscripts {
subscript (a: PrivateStruct) -> Int { return 0 } // expected-error {{subscript must be declared fileprivate because its index uses a private type}}
subscript (a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript must be declared fileprivate because its element type uses a private type}}
public subscript (a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its element type uses an internal type}}
}
public struct Methods {
func foo(a: PrivateStruct) -> Int { return 0 } // expected-error {{method must be declared fileprivate because its parameter uses a private type}}
func bar(a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{method must be declared fileprivate because its result uses a private type}}
public func a(a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func b(a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func c(a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func d(a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func e(a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its result uses an internal type}}
}
func privateParam(a: PrivateStruct) {} // expected-error {{function must be declared private or fileprivate because its parameter uses a private type}}
public struct Initializers {
init(a: PrivateStruct) {} // expected-error {{initializer must be declared fileprivate because its parameter uses a private type}}
public init(a: PrivateStruct, b: Int) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: Int, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: InternalStruct, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: PrivateStruct, b: InternalStruct) { } // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
}
public class PublicClass {}
// expected-note@+2 * {{type declared here}}
// expected-note@+1 * {{superclass is declared here}}
internal class InternalClass {}
// expected-note@+1 * {{type declared here}}
private class PrivateClass {}
public protocol AssocTypes {
associatedtype Foo
associatedtype Internal: InternalClass // expected-error {{associated type in a public protocol uses an internal type in its requirement}}
associatedtype InternalConformer: InternalProto // expected-error {{associated type in a public protocol uses an internal type in its requirement}}
associatedtype PrivateConformer: PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PI: PrivateProto, InternalProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype IP: InternalProto, PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PrivateDefault = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}}
associatedtype PublicDefault = PublicStruct
associatedtype PrivateDefaultConformer: PublicProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}}
associatedtype PublicDefaultConformer: PrivateProto = PublicStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PrivatePrivateDefaultConformer: PrivateProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PublicPublicDefaultConformer: PublicProto = PublicStruct
}
public protocol RequirementTypes {
var x: PrivateStruct { get } // expected-error {{property cannot be declared public because its type uses a private type}}
subscript(x: Int) -> InternalStruct { get set } // expected-error {{subscript cannot be declared public because its element type uses an internal type}}
func foo() -> PrivateStruct // expected-error {{method cannot be declared public because its result uses a private type}}
init(x: PrivateStruct) // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
}
protocol DefaultRefinesPrivate : PrivateProto {} // expected-error {{protocol must be declared private or fileprivate because it refines a private protocol}}
public protocol PublicRefinesPrivate : PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}}
public protocol PublicRefinesInternal : InternalProto {} // expected-error {{public protocol cannot refine an internal protocol}}
public protocol PublicRefinesPI : PrivateProto, InternalProto {} // expected-error {{public protocol cannot refine a private protocol}}
public protocol PublicRefinesIP : InternalProto, PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}}
// expected-note@+1 * {{type declared here}}
private typealias PrivateInt = Int
enum DefaultRawPrivate : PrivateInt { // expected-error {{enum must be declared private or fileprivate because its raw type uses a private type}}
case A
}
public enum PublicRawPrivate : PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}}
case A
}
public enum MultipleConformance : PrivateProto, PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}} expected-error {{must appear first}} {{35-35=PrivateInt, }} {{47-59=}}
case A
func privateReq() {}
}
open class OpenSubclassInternal : InternalClass {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalClass' of open class must be open}}
public class PublicSubclassPublic : PublicClass {}
public class PublicSubclassInternal : InternalClass {} // expected-error {{class cannot be declared public because its superclass is internal}}
public class PublicSubclassPrivate : PrivateClass {} // expected-error {{class cannot be declared public because its superclass is private}}
class DefaultSubclassPublic : PublicClass {}
class DefaultSubclassInternal : InternalClass {}
class DefaultSubclassPrivate : PrivateClass {} // expected-error {{class must be declared private or fileprivate because its superclass is private}}
// expected-note@+1 * {{superclass is declared here}}
public class PublicGenericClass<T> {}
// expected-note@+2 * {{type declared here}}
// expected-note@+1 * {{superclass is declared here}}
internal class InternalGenericClass<T> {}
// expected-note@+1 * {{type declared here}}
private class PrivateGenericClass<T> {}
open class OpenConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-warning {{class should not be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<Int>' of open class must be open}}
public class PublicConcreteSubclassPublic : PublicGenericClass<Int> {}
public class PublicConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-warning {{class should not be declared public because its superclass is internal}}
public class PublicConcreteSubclassPrivate : PrivateGenericClass<Int> {} // expected-warning {{class should not be declared public because its superclass is private}}
public class PublicConcreteSubclassPublicPrivateArg : PublicGenericClass<PrivateStruct> {} // expected-warning {{class should not be declared public because its superclass uses a private type as a generic parameter}}
public class PublicConcreteSubclassPublicInternalArg : PublicGenericClass<InternalStruct> {} // expected-warning {{class should not be declared public because its superclass uses an internal type as a generic parameter}}
open class OpenConcreteSubclassPublicFilePrivateArg : PublicGenericClass<FilePrivateStruct> {} // expected-warning {{class should not be declared open because its superclass uses a fileprivate type as a generic parameter}} expected-error {{superclass 'PublicGenericClass<FilePrivateStruct>' of open class must be open}}
internal class InternalConcreteSubclassPublicFilePrivateArg : InternalGenericClass<PrivateStruct> {} // expected-warning {{class should not be declared internal because its superclass uses a private type as a generic parameter}}
open class OpenGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-warning {{class should not be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<T>' of open class must be open}}
public class PublicGenericSubclassPublic<T> : PublicGenericClass<T> {}
public class PublicGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-warning {{class should not be declared public because its superclass is internal}}
public class PublicGenericSubclassPrivate<T> : PrivateGenericClass<T> {} // expected-warning {{class should not be declared public because its superclass is private}}
public enum PublicEnumPrivate {
case A(PrivateStruct) // expected-error {{enum case in a public enum uses a private type}}
}
enum DefaultEnumPrivate {
case A(PrivateStruct) // expected-error {{enum case in an internal enum uses a private type}}
}
public enum PublicEnumPI {
case A(InternalStruct) // expected-error {{enum case in a public enum uses an internal type}}
case B(PrivateStruct, InternalStruct) // expected-error {{enum case in a public enum uses a private type}} expected-error {{enum case in a public enum uses an internal type}}
case C(InternalStruct, PrivateStruct) // expected-error {{enum case in a public enum uses a private type}} expected-error {{enum case in a public enum uses an internal type}}
}
enum DefaultEnumPublic {
case A(PublicStruct) // no-warning
}
struct DefaultGeneric<T> {}
struct DefaultGenericPrivate<T: PrivateProto> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}}
struct DefaultGenericPrivate2<T: PrivateClass> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}}
struct DefaultGenericPrivateReq<T> where T == PrivateClass {} // expected-warning {{same-type requirement makes generic parameter 'T' non-generic}}
// expected-error@-1 {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}}
struct DefaultGenericPrivateReq2<T> where T: PrivateProto {} // expected-error {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}}
public struct PublicGenericInternal<T: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses an internal type}}
public struct PublicGenericPI<T: PrivateProto, U: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericIP<T: InternalProto, U: PrivateProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericPIReq<T: PrivateProto> where T: InternalProto {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericIPReq<T: InternalProto> where T: PrivateProto {} // expected-error {{generic struct cannot be declared public because its generic requirement uses a private type}}
public func genericFunc<T: InternalProto>(_: T) {} // expected-error {{function cannot be declared public because its generic parameter uses an internal type}} {}
public class GenericClass<T: InternalProto> { // expected-error {{generic class cannot be declared public because its generic parameter uses an internal type}}
public init<T: PrivateProto>(_: T) {} // expected-error {{initializer cannot be declared public because its generic parameter uses a private type}}
public func genericMethod<T: PrivateProto>(_: T) {} // expected-error {{instance method cannot be declared public because its generic parameter uses a private type}}
}
public enum GenericEnum<T: InternalProto> { // expected-error {{generic enum cannot be declared public because its generic parameter uses an internal type}}
case A
}
public protocol PublicMutationOperations {
var size: Int { get set }
subscript (_: Int) -> Int { get set }
}
internal protocol InternalMutationOperations {
var size: Int { get set }
subscript (_: Int) -> Int { get set }
}
public struct AccessorsControl : InternalMutationOperations {
private var size = 0 // expected-error {{property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{3-10=internal}}
private subscript (_: Int) -> Int { // expected-error {{subscript must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{3-10=internal}}
get { return 42 }
set {}
}
}
public struct PrivateSettersPublic : InternalMutationOperations {
// Please don't change the formatting here; it's a precise fix-it test.
public private(set) var size = 0 // expected-error {{setter for property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{10-17=internal}}
public private(set) subscript (_: Int) -> Int { // expected-error {{subscript setter must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{10-17=internal}}
get { return 42 }
set {}
}
}
internal struct PrivateSettersInternal : PublicMutationOperations {
// Please don't change the formatting here; it's a precise fix-it test.
private(set)var size = 0 // expected-error {{setter for property 'size' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{3-15=}}
internal private(set)subscript (_: Int) -> Int { // expected-error {{subscript setter must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{12-24=}}
get { return 42 }
set {}
}
}
public protocol PublicReadOnlyOperations {
var size: Int { get }
subscript (_: Int) -> Int { get }
}
internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations {
public private(set) var size = 0
internal private(set) subscript (_: Int) -> Int { // no-warning
get { return 42 }
set {}
}
}
public struct PrivateSettersForReadOnlyPublic : PublicReadOnlyOperations {
public private(set) var size = 0 // no-warning
internal private(set) subscript (_: Int) -> Int { // expected-error {{subscript must be declared public because it matches a requirement in public protocol 'PublicReadOnlyOperations'}} {{none}} expected-note {{mark the subscript as 'public' to satisfy the requirement}} {{3-11=public}}
get { return 42 }
set {}
}
}
public protocol PublicOperatorProto {
static prefix func !(_: Self) -> Self
}
internal protocol InternalOperatorProto {
static prefix func !(_: Self) -> Self
}
fileprivate protocol FilePrivateOperatorProto {
static prefix func !(_: Self) -> Self
}
private protocol PrivateOperatorProto {
static prefix func !(_: Self) -> Self
}
public struct PublicOperatorAdopter : PublicOperatorProto {
// expected-error@-1 {{method '!' must be declared public because it matches a requirement in public protocol 'PublicOperatorProto'}} {{none}}
fileprivate struct Inner : PublicOperatorProto {
}
}
private prefix func !(input: PublicOperatorAdopter) -> PublicOperatorAdopter { // expected-note {{mark the operator function as 'public' to satisfy the requirement}} {{1-8=public}}
return input
}
private prefix func !(input: PublicOperatorAdopter.Inner) -> PublicOperatorAdopter.Inner {
return input
}
public struct InternalOperatorAdopter : InternalOperatorProto {
// expected-error@-1 {{method '!' must be declared internal because it matches a requirement in internal protocol 'InternalOperatorProto'}} {{none}}
fileprivate struct Inner : InternalOperatorProto {
}
}
private prefix func !(input: InternalOperatorAdopter) -> InternalOperatorAdopter { // expected-note {{mark the operator function as 'internal' to satisfy the requirement}} {{1-8=internal}}
return input
}
private prefix func !(input: InternalOperatorAdopter.Inner) -> InternalOperatorAdopter.Inner {
return input
}
public struct FilePrivateOperatorAdopter : FilePrivateOperatorProto {
fileprivate struct Inner : FilePrivateOperatorProto {
}
}
private prefix func !(input: FilePrivateOperatorAdopter) -> FilePrivateOperatorAdopter {
return input
}
private prefix func !(input: FilePrivateOperatorAdopter.Inner) -> FilePrivateOperatorAdopter.Inner {
return input
}
public struct PrivateOperatorAdopter : PrivateOperatorProto {
fileprivate struct Inner : PrivateOperatorProto {
}
}
private prefix func !(input: PrivateOperatorAdopter) -> PrivateOperatorAdopter {
return input
}
private prefix func !(input: PrivateOperatorAdopter.Inner) -> PrivateOperatorAdopter.Inner {
return input
}
public protocol Equatablish {
static func ==(lhs: Self, rhs: Self) /* -> bool */ // expected-note {{protocol requires function '=='}}
}
fileprivate struct EquatablishOuter {
internal struct Inner : Equatablish {}
}
private func ==(lhs: EquatablishOuter.Inner, rhs: EquatablishOuter.Inner) {}
fileprivate struct EquatablishOuter2 {
internal struct Inner : Equatablish {
fileprivate static func ==(lhs: Inner, rhs: Inner) {}
}
}
fileprivate struct EquatablishOuterProblem {
internal struct Inner : Equatablish { // expected-error {{type 'EquatablishOuterProblem.Inner' does not conform to protocol 'Equatablish'}}
private static func ==(lhs: Inner, rhs: Inner) {}
}
}
internal struct EquatablishOuterProblem2 {
public struct Inner : Equatablish {
fileprivate static func ==(lhs: Inner, rhs: Inner) {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
// expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{5-16=internal}}
}
}
internal struct EquatablishOuterProblem3 {
public struct Inner : Equatablish {
// expected-error@-1 {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
}
}
private func ==(lhs: EquatablishOuterProblem3.Inner, rhs: EquatablishOuterProblem3.Inner) {}
// expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{1-8=internal}}
internal struct EquatablishOuterProblem4 {
public struct Inner : Equatablish {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
}
internal extension EquatablishOuterProblem4.Inner {
fileprivate static func ==(lhs: EquatablishOuterProblem4.Inner, rhs: EquatablishOuterProblem4.Inner) {}
// expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{3-15=}}
}
internal struct EquatablishOuterProblem5 {
public struct Inner : Equatablish {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
}
private extension EquatablishOuterProblem5.Inner {
static func ==(lhs: EquatablishOuterProblem5.Inner, rhs: EquatablishOuterProblem5.Inner) {}
// expected-note@-1 {{move the operator function to another extension where it can be declared 'internal' to satisfy the requirement}} {{none}}
}
public protocol AssocTypeProto {
associatedtype Assoc
}
fileprivate struct AssocTypeOuter {
internal struct Inner : AssocTypeProto {
fileprivate typealias Assoc = Int
}
}
fileprivate struct AssocTypeOuterProblem {
internal struct Inner : AssocTypeProto {
private typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} expected-note {{mark the type alias as 'fileprivate' to satisfy the requirement}} {{5-12=fileprivate}}
}
}
internal struct AssocTypeOuterProblem2 {
public struct Inner : AssocTypeProto {
fileprivate typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} expected-note {{mark the type alias as 'internal' to satisfy the requirement}} {{5-16=internal}}
}
}
internal struct AssocTypeOuterProblem3 {
public struct Inner : AssocTypeProto {} // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}}
}
internal extension AssocTypeOuterProblem3.Inner {
fileprivate typealias Assoc = Int // expected-note {{mark the type alias as 'internal' to satisfy the requirement}} {{3-15=}}
}
internal struct AssocTypeOuterProblem4 {
public struct Inner : AssocTypeProto {} // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}}
}
private extension AssocTypeOuterProblem4.Inner {
typealias Assoc = Int // expected-note {{move the type alias to another extension where it can be declared 'internal' to satisfy the requirement}} {{none}}
}
internal typealias InternalComposition = PublicClass & PublicProto // expected-note {{declared here}}
public class DerivedFromInternalComposition : InternalComposition { // expected-error {{class cannot be declared public because its superclass is internal}}
public func publicReq() {}
}
internal typealias InternalGenericComposition<T> = PublicGenericClass<T> & PublicProto // expected-note {{declared here}}
public class DerivedFromInternalGenericComposition : InternalGenericComposition<Int> { // expected-warning {{class should not be declared public because its superclass is internal}}
public func publicReq() {}
}
internal typealias InternalConcreteGenericComposition = PublicGenericClass<Int> & PublicProto // expected-note {{declared here}}
public class DerivedFromInternalConcreteGenericComposition : InternalConcreteGenericComposition { // expected-warning {{class should not be declared public because its superclass is internal}}
public func publicReq() {}
}
public typealias BadPublicComposition1 = InternalClass & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition2 = PublicClass & InternalProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition3<T> = InternalGenericClass<T> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition4 = InternalGenericClass<Int> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition5 = PublicGenericClass<InternalStruct> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
open class ClassWithProperties {
open open(set) var openProp = 0 // expected-warning {{'open(set)' modifier is redundant for an open property}} {{8-18=}}
public public(set) var publicProp = 0 // expected-warning {{'public(set)' modifier is redundant for a public property}} {{10-22=}}
internal internal(set) var internalProp = 0 // expected-warning {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}}
fileprivate fileprivate(set) var fileprivateProp = 0 // expected-warning {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}}
private private(set) var privateProp = 0 // expected-warning {{'private(set)' modifier is redundant for a private property}} {{11-24=}}
internal(set) var defaultProp = 0 // expected-warning {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}}
}
extension ClassWithProperties {
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}}
internal internal(set) var defaultExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}}
internal(set) var defaultExtProp2: Int {
get { return 42 }
set {}
}
}
public extension ClassWithProperties {
// expected-warning@+2 {{'public' modifier is redundant for property declared in a public extension}} {{3-10=}}
// expected-warning@+1 {{'public(set)' modifier is redundant for a public property}} {{10-22=}}
public public(set) var publicExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'public(set)' modifier is redundant for a public property}} {{3-15=}}
public(set) var publicExtProp2: Int {
get { return 42 }
set {}
}
}
internal extension ClassWithProperties {
// expected-warning@+2 {{'internal' modifier is redundant for property declared in an internal extension}} {{3-12=}}
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}}
internal internal(set) var internalExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}}
internal(set) var internalExtProp2: Int {
get { return 42 }
set {}
}
}
fileprivate extension ClassWithProperties {
// expected-warning@+2 {{'fileprivate' modifier is redundant for property declared in a fileprivate extension}} {{3-15=}}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}}
fileprivate fileprivate(set) var fileprivateExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{3-20=}}
fileprivate(set) var fileprivateExtProp2: Int {
get { return 42 }
set {}
}
private(set) var fileprivateExtProp3: Int {
get { return 42 }
set {}
}
}
private extension ClassWithProperties {
// expected-warning@+2 {{'fileprivate' modifier is redundant for property declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}}
fileprivate fileprivate(set) var privateExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{3-20=}}
fileprivate(set) var privateExtProp2: Int {
get { return 42 }
set {}
}
private(set) var privateExtProp3: Int {
get { return 42 }
set {}
}
}
public var inferredType = PrivateStruct() // expected-error {{variable cannot be declared public because its type 'PrivateStruct' uses a private type}}
public var inferredGenericParameters: Optional = PrivateStruct() // expected-warning {{variable should not be declared public because its type uses a private type}}
public var explicitType: Optional<PrivateStruct> = PrivateStruct() // expected-error {{variable cannot be declared public because its type uses a private type}}
|
apache-2.0
|
a467379602f2adb21e463f128f6ecadf
| 60.222877 | 319 | 0.750756 | 4.892753 | false | true | false | false |
kennyweigel/estimote-proximity
|
EstimoteProximity/EstimoteProximity/ViewController.swift
|
1
|
4312
|
//
// ViewController.swift
// EstimoteProximity
//
// Created by Kenneth Weigel on 3/20/15.
// Copyright (c) 2015 Kenneth Weigel. All rights reserved.
//
import UIKit
// core location is required for estimotes
import CoreLocation
// ViewControll has CLLocationManagerDelegate delagate methods available
class ViewController: UIViewController, CLLocationManagerDelegate {
// outlet for
@IBOutlet weak var currentVisitCount: UILabel!
// core location manager instance
let locationManager = CLLocationManager()
// define the core location region, defines whic beacons our regions should care about
// uses estimote default UUIDString
// identifier is just arbitrary string
let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D"), identifier: "Estimotes")
// define colors based on Estimote Minor values
let colors = [
2638: UIColor(red: 158/255, green: 222/255, blue: 218/255, alpha: 1),// green
64528: UIColor(red: 16/255, green: 194/255, blue: 230/255, alpha: 1),//sky blue
56493: UIColor(red: 16/255, green: 105/255, blue: 230/255, alpha: 1)// dark blue
]
// holds the closest estimote
var currentBeacon: CLBeacon = CLBeacon()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// ViewController should be the delegate (where it should deliver messages) of the locationManager
locationManager.delegate = self;
// only request authorization if app hasn't already been authorized
if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse) {
locationManager.requestWhenInUseAuthorization()
}
// start monitoring region for beacons
locationManager.startRangingBeaconsInRegion(region)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// want to be notified when relative beacon is found
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [CLBeacon]!, inRegion region: CLBeaconRegion!) {
// strip unknown beacons to create a new array
// closest beacon comes in first therefore we can assume the first item in array is closest
let knownBeacons = beacons.filter{ $0.proximity != CLProximity.Unknown }
if (knownBeacons.count > 0) {
// closest beacon accuracy value
var closestAccuracy: CLLocationAccuracy = 1000
// closest beacon, defaults to first beacon
var closestBeacon: CLBeacon = knownBeacons[0]
// find closest beacon
for beacon in knownBeacons {
if (beacon.accuracy > -1 && beacon.accuracy < closestAccuracy) {
closestAccuracy = beacon.accuracy
closestBeacon = beacon
}
}
if (closestBeacon.minor != currentBeacon.minor) {
println("change")
println(closestBeacon.accuracy)
currentBeacon = closestBeacon
testPost()
}
self.view.backgroundColor = self.colors[closestBeacon.minor.integerValue]
}
}
func testPost()
{
let request = NSMutableURLRequest(URL: NSURL(string: "http://estimote-leaderboard.herokuapp.com/player/addscore")!)
request.HTTPMethod = "POST"
let postString = "estimoteMinor=test&score=1"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()
}
}
|
mit
|
56fa1624bd376b33dfa3b5048edefe90
| 36.824561 | 131 | 0.625928 | 5.330037 | false | false | false | false |
mcappadonna/swift-console-controllers
|
Sources/ConsoleViewControllers.swift
|
1
|
7733
|
import Foundation
/*
* ConsoleViewControllerProtocol
*
* Just a way to uniform different structs
*/
public protocol ConsoleViewControllerProtocol {
/*
* execute()
*
* Start the execution of the implemented ConsoleViewController
*/
func execute()
}
/*
* Here some usefull types:
*
* Parser: A function from String to a generic optional
* Completer: A function from an optional to nothing
*/
public typealias Parser <A> = (String) -> A?
public typealias Completer <A> = (A) -> ()
/*
* ConsoleViewController
*
* This emulate an UIViewController in a terminal, and it was generic over type A.
* It will require a text to display, a function to convert the input to an optional A
* and a function that will be executed if the convertion succeeded.
*
* Properties:
*
* - text: String The text displayed when the ConsoleViewController will be executed
*
* - parse: String -> A? A function to parse the String input to the desidered type.
* This function can return a nil if the conversion fail.
*
* - onComplete: A -> () A function that get the converted value and do something
*
* Methods:
*
* - execute() Perform the following operations: display the text variable and
* read the input. Then use the parse function to convert the input
* into the desidered type. If conversion succeeded, execute the
* onComplete function passing the converted value
*
* Examples:
*
* This is a ConsoleViewController which ask for the age then display the result
*
* let cvc = ConsoleViewController("How old are you?", parse: { return Int($0) }) { age in
* print("You're \(age) years old")
* }
*
* To execute that ConsoleViewController, you must call the execute function:
*
* cvc.execute()
*
* You can also concatenate more ConsoleViewController to obtain a flow:
*
* let nameVC = ConsoleViewController("What's your name?", parse: { return $0 }) { name in
* let ageVC = ConsoleViewController("How old are you?", parse: { return Int($0) }) { age in
* print("Hi \(name), you're \(age) years old'")
* }
* ageVC.execute()
* }
* nameVC.execute()
*
*/
public struct ConsoleViewController <A>: ConsoleViewControllerProtocol {
let text: String
let parse: Parser<A>
let onComplete: Completer<A>
}
public extension ConsoleViewController {
// This function execute the viewControllers
func execute () {
print(text)
let string = readLine() ?? ""
guard let value = parse(string) else { return }
onComplete(value)
}
}
/*
* ConsoleNavigationViewController
*
* The best way (I found) to do something like UINavigationController on terminal it's this implementation.
* This simply contain a ConsoleViewController and a method to execute that. In addition, if you declare it
* as a variable, you have the pushViewController method which permit to execute some other ConsoleViewController
* after the execution was done.
*
* Properties:
*
* - title: String The title of the ConsoleNavigationViewController (default: "")
*
* - animationDuration: UInt32 The push/pop animation duration (default: 2 seconds)
*
* - viewControllers: [ConsoleViewControllerProtocol]
* An array containing the stack of ConsoleViewController present into
* the navigation
*
* - topViewController: ConsoleViewControllerProtocol?
* Return (if present) the first element of the ConsoleViewController stack
*
* - visibleViewController: ConsoleViewControllerProtocol?
* Return (if present) the last element of the ConsoleNavigationController stack.
* This is the View Controller that will be executed during the
* ConsoleNavigationViewController execution
*
* Methods:
*
* - execute() Display, if available, the ConsoleNavigationViewController title and a separator, then
* call the execute method of the visible ConsoleViewControlled.
*
* - pushViewController(_:ConsoleViewControllerProtocol, animated:Bool)
* This will add a new <ConsoleViewControllerProtocol> to the stack, then execute it.
* If animated was true, then wait before pushing it (see animationDuration property).
*
* - popViewController(animated: Bool)
* This will remove the last <ConsoleViewControllerProtocol> from the stack, then execute
* the previous one (if available).
* If animated was true, then wait before pushing it (see animationDuration property).
*
* Examples:
*
* This will display a new ConsoleViewController after 2 seconds of waiting
*
* let nameVC = ConsoleViewController(text: "Enter your name:", parse: { return $0 }) {
* print("Welcome \(name)")
* }
* var navigationVC = ConsoleNavigationController()
* navigationVC.pushViewController(nameVC, animated: true)
*
*/
public struct ConsoleNavigationViewController: ConsoleViewControllerProtocol {
var title: String = ""
var animationDuration: UInt32 = 2
var viewControllers: [ConsoleViewControllerProtocol] = []
var topViewController: ConsoleViewControllerProtocol? {
get {
return viewControllers.first
}
}
var visibleViewController: ConsoleViewControllerProtocol? {
get {
return viewControllers.last
}
}
}
public extension ConsoleNavigationViewController {
mutating func pushViewController (_ vc: ConsoleViewControllerProtocol, animated: Bool) {
if animated { sleep(animationDuration) }
viewControllers.append(vc)
execute()
}
mutating func popViewController (animated: Bool) {
if viewControllers.count == 0 { return }
if animated { sleep(animationDuration) }
viewControllers.removeLast()
execute()
}
func execute () {
guard let visible = visibleViewController else { return }
if title != "" {
print(" \(title)\n---------------")
}
visible.execute()
}
}
/*
* AppDelegate
*
* A simple way to orchestrate multiple viewControllers execution. This will works with
* any struct which conforms to ConsoleViewControllerProtocol
*
* Properties:
*
* - initialViewController: ConsoleViewControllerProtocol?
* The controller that will be executed when the app will start.
*
* Methods:
*
* - run() Call the execute method of the initialViewController
*
* Examples:
*
* Executing a single ConsoleViewController it's really simple
*
* let nameVC = ConsoleViewController(text: "Enter your name:", parse: { return $0 }) {
* print("Welcome \(name)")
* }
* let app = AppDelegate(initialViewController: nameVC)
* app.run()
*
* You can also pass a ConsoleNavigationController. With this, you can execute other view controllers after
* the run() method call:
*
* let ageVC = ConsoleViewController(text: "Enter your age:", parse: { return Int($0) }) { age in
* print("You're \(age) years old")
* }
* var navVC = ConsoleNavigationViewController(viewControllers: [ageVC])
*
* let app = AppDelegate()
*
*/
public struct AppDelegate {
var initialViewController: ConsoleViewControllerProtocol?
}
public extension AppDelegate {
func run() {
if let vc = initialViewController {
vc.execute()
}
}
}
|
apache-2.0
|
4b23939857e8f9cdceec821b464f18f3
| 33.995475 | 113 | 0.648778 | 4.794172 | false | false | false | false |
mcxiaoke/learning-ios
|
LineDraw/LineDraw/Line.swift
|
1
|
2885
|
//
// Line.swift
// TouchTracker
//
// Created by Xiaoke Zhang on 2017/8/17.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import UIKit
class Line: NSObject, NSCoding, NSCopying {
var begin: CGPoint
var end: CGPoint
var width: Int = 10
var color: UIColor = UIColor.random()
init?(dict:[String:CGPoint]) {
if let begin = dict["begin"], let end = dict["end"] {
self.begin = begin
self.end = end
} else {
return nil
}
}
init(begin: CGPoint, end:CGPoint) {
self.begin = begin
self.end = end
}
func encode() -> [String:CGPoint] {
return ["begin": begin, "end": end]
}
required init?(coder aDecoder: NSCoder) {
self.begin = aDecoder.decodeCGPoint(forKey: "begin")
self.end = aDecoder.decodeCGPoint(forKey: "end")
self.width = aDecoder.decodeInteger(forKey: "width")
if let colorHex = aDecoder.decodeObject(forKey: "color") as? String {
self.color = UIColor(hex: colorHex)
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.begin, forKey: "begin")
aCoder.encode(self.end, forKey: "end")
aCoder.encode(self.width, forKey: "width")
aCoder.encode(self.color.toHexString, forKey: "color")
}
func copy(with zone: NSZone? = nil) -> Any {
return Line(begin: self.begin, end:self.end)
}
override var description: String {
return "\(self.begin)-\(self.end) \(self.width)"
}
}
/**
protocol Encodable {
var encoded: Decodable? { get }
}
protocol Decodable {
var decoded: Encodable? { get }
}
extension Line {
class Coding: NSObject, NSCoding {
let data:Line?
init(data:Line) {
self.data = data
super.init()
}
required init?(coder aDecoder: NSCoder) {
let begin = aDecoder.decodeCGPoint(forKey: "begin")
let end = aDecoder.decodeCGPoint(forKey: "end")
self.data = Line(begin: begin, end:end)
super.init()
}
func encode(with aCoder: NSCoder) {
guard let data = self.data else { return }
aCoder.encode(data.begin, forKey: "begin")
aCoder.encode(data.end, forKey: "end")
}
}
}
extension Line: Encodable {
var encoded: Decodable? {
return Coding(data: self)
}
}
extension Line.Coding: Decodable {
var decoded: Encodable? {
return self.data
}
}
extension Sequence where Iterator.Element: Encodable {
var encoded: [Decodable] {
return self.flatMap({$0.encoded})
}
}
extension Sequence where Iterator.Element: Decodable {
var decoded: [Encodable] {
return self.flatMap({$0.decoded})
}
}
**/
|
apache-2.0
|
bcbca16b4faff1967238f4846a0381f3
| 22.818182 | 77 | 0.565579 | 4.02514 | false | false | false | false |
debugsquad/nubecero
|
nubecero/Model/Store/Purchases/MStoreItemAlbums.swift
|
1
|
1207
|
import UIKit
class MStoreItemAlbums:MStoreItem
{
private let kStorePurchaseId:MStore.PurchaseId = "iturbide.nubecero.albums"
override init()
{
let title:String = NSLocalizedString("MStoreItemAlbums_title", comment:"")
let descr:String = NSLocalizedString("MStoreItemAlbums_descr", comment:"")
let image:UIImage = #imageLiteral(resourceName: "assetPurchaseAlbums")
super.init(
purchaseId:kStorePurchaseId,
title:title,
descr:descr,
image:image)
}
override init(purchaseId:MStore.PurchaseId, title:String, descr:String, image:UIImage)
{
fatalError()
}
override func purchaseAction()
{
MSession.sharedInstance.settings.current?.nubeceroAlbums = true
DManager.sharedInstance.save()
}
override func validatePurchase() -> Bool
{
var isPurchased:Bool = false
guard
let albums:Bool = MSession.sharedInstance.settings.current?.nubeceroAlbums
else
{
return isPurchased
}
isPurchased = albums
return isPurchased
}
}
|
mit
|
93a596c819f7aa22265b4afdb3e8c7f2
| 24.680851 | 90 | 0.60232 | 4.906504 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK
|
AviasalesSDKTemplate/Source/Analytics/Flights/Hotels/HotelsVariantEvent.swift
|
1
|
1449
|
//
// HotelsVariantEvent.swift
// AviasalesSDKTemplate
//
// Created by Dim on 07.09.2018.
// Copyright © 2018 Go Travel Un Limited. All rights reserved.
//
class HotelsVariantEvent: AnalyticsEvent {
let name: String = "Hotels_Variant"
let payload: [String : String]
init(variant: HLResultVariant) {
var payload = [String: String]()
let formatter = DateFormatter(format: "yyyy-MM-dd")
payload["Hotel_Search_Type"] = variant.searchInfo.searchInfoType.description()
payload["Hotel_ID"] = variant.hotel.hotelId
payload["Hotel_Name"] = variant.hotel.latinName
payload["Hotel_City_ID"] = variant.hotel.city?.cityId
payload["Hotel_City_Name"] = variant.hotel.city?.latinName
payload["Hotel_Country_ID"] = variant.hotel.city?.countryCode
payload["Hotel_Country_Name"] = variant.hotel.city?.countryLatinName
payload["Hotel_Check_In"] = format(variant.searchInfo.checkInDate, with: formatter)
payload["Hotel_Check_Out"] = format(variant.searchInfo.checkOutDate, with: formatter)
payload["Hotel_Adults_Count"] = String(variant.searchInfo.adultsCount)
payload["Hotel_Kids_Count"] = String(variant.searchInfo.kidsCount)
self.payload = payload
}
}
private func format(_ date: Date?, with formatter: DateFormatter) -> String {
guard let date = date else {
return ""
}
return formatter.string(from: date)
}
|
mit
|
2e1f5d19a347aaa8e0cf75dd2bf40ce1
| 38.135135 | 93 | 0.676796 | 3.800525 | false | false | false | false |
ccrama/Slide-iOS
|
Slide for Reddit/AppDelegate.swift
|
1
|
62345
|
//
// AppDelegate.swift
// Slide for Reddit
//
// Created by Carlos Crane on 12/22/16.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import Anchorage
import AVKit
import BiometricAuthentication
import CloudKit
import DTCoreText
import RealmSwift
import reddift
import SDWebImage
import Then
import UIKit
import UserNotifications
import WatchConnectivity
#if !os(iOS)
import WatchKit
#endif
/// Posted when the OAuth2TokenRepository object succeed in saving a token successfully into Keychain.
public let OAuth2TokenRepositoryDidSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidSaveToken")
/// Posted when the OAuth2TokenRepository object failed to save a token successfully into Keychain.
public let OAuth2TokenRepositoryDidFailToSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidFailToSaveToken")
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let name = "reddittoken"
var session: Session?
var fetcher: BackgroundFetch?
var subreddits: [Subreddit] = []
var paginator = Paginator()
var login: MainViewController?
var seenFile: String?
var commentsFile: String?
var readLaterFile: String?
var collectionsFile: String?
var iconsFile: String?
var colorsFile: String?
var totalBackground = true
var isPro = false
var transitionDelegateModal: InsetTransitioningDelegate?
var tempWindow: UIWindow?
var orientationLock = UIInterfaceOrientationMask.allButUpsideDown
/**
Corresponds to USR_DOMAIN in info.plist, which derives its value
from USR_DOMAIN in the pbxproj build settings. Default is `ccrama.me`.
*/
lazy var USR_DOMAIN: String = {
return Bundle.main.object(forInfoDictionaryKey: "USR_DOMAIN") as! String
}()
let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 13 {
/*
- Property 'RComment.gilded' has been changed from 'int' to 'bool'.
- Property 'RComment.gold' has been added.
- Property 'RComment.silver' has been added.
- Property 'RComment.platinum' has been added.
- Property 'RSubmission.gilded' has been changed from 'int' to 'bool'.
- Property 'RSubmission.gold' has been added.
- Property 'RSubmission.silver' has been added.
*/
migration.enumerateObjects(ofType: RSubmission.className()) { (old, new) in
// Change gilded from Int to Bool
guard let gildedCount = old?["gilded"] as? Int else {
fatalError("Old gilded value should Int, but is not.")
}
new?["gilded"] = gildedCount > 0
// Set new properties
new?["gold"] = gildedCount
new?["silver"] = 0
new?["platinum"] = 0
new?["oc"] = false
}
migration.enumerateObjects(ofType: RComment.className(), { (old, new) in
// Change gilded from Int to Bool
guard let gildedCount = old?["gilded"] as? Int else {
fatalError("Old gilded value should Int, but is not.")
}
new?["gilded"] = gildedCount > 0
// Set new properties
new?["gold"] = gildedCount
new?["silver"] = 0
new?["platinum"] = 0
})
}
if oldSchemaVersion < 26 {
migration.enumerateObjects(ofType: RSubmission.className()) { (old, new) in
new?["subreddit_icon"] = ""
}
}
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
if let url = notification.userInfo?["permalink"] as? String {
VCPresenter.openRedditLink(url, window?.rootViewController as? UINavigationController, window?.rootViewController)
} else {
VCPresenter.showVC(viewController: InboxViewController(), popupIfPossible: false, parentNavigationController: window?.rootViewController as? UINavigationController, parentViewController: window?.rootViewController)
}
}
static var removeDict = NSMutableDictionary()
var launchedURL: URL?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13.0, *) { return true } else {
let window = UIWindow(frame: UIScreen.main.bounds)
self.window = window
didFinishLaunching(window: window)
launchedURL = launchOptions?[UIApplication.LaunchOptionsKey.url] as? URL
let remoteNotif = launchOptions?[UIApplication.LaunchOptionsKey.localNotification] as? UILocalNotification
if remoteNotif != nil {
if let url = remoteNotif!.userInfo?["permalink"] as? String {
VCPresenter.openRedditLink(url, window.rootViewController as? UINavigationController, window.rootViewController)
} else {
VCPresenter.showVC(viewController: InboxViewController(), popupIfPossible: false, parentNavigationController: window.rootViewController as? UINavigationController, parentViewController: window.rootViewController)
}
}
return true
}
}
func didFinishLaunching(window: UIWindow) {
UIPanGestureRecognizer.swizzle()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentDirectory = paths[0] as! String
seenFile = documentDirectory.appending("/seen.plist")
commentsFile = documentDirectory.appending("/comments.plist")
readLaterFile = documentDirectory.appending("/readlater.plist")
collectionsFile = documentDirectory.appending("/collections.plist")
iconsFile = documentDirectory.appending("/icons.plist")
colorsFile = documentDirectory.appending("/subcolors.plist")
let config = Realm.Configuration(
schemaVersion: 30,
migrationBlock: migrationBlock,
deleteRealmIfMigrationNeeded: true)
Realm.Configuration.defaultConfiguration = config
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: seenFile!) {
if let bundlePath = Bundle.main.path(forResource: "seen", ofType: "plist") {
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do {
try fileManager.copyItem(atPath: bundlePath, toPath: seenFile!)
} catch {
print("copy failure.")
}
} else {
print("file myData.plist not found.")
}
} else {
print("file myData.plist already exits at path.")
}
if !fileManager.fileExists(atPath: readLaterFile!) {
if let bundlePath = Bundle.main.path(forResource: "readlater", ofType: "plist") {
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do {
try fileManager.copyItem(atPath: bundlePath, toPath: readLaterFile!)
} catch {
print("copy failure.")
}
} else {
print("file myData.plist not found.")
}
} else {
print("file myData.plist already exits at path.")
}
if !fileManager.fileExists(atPath: collectionsFile!) {
if let bundlePath = Bundle.main.path(forResource: "collections", ofType: "plist") {
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do {
try fileManager.copyItem(atPath: bundlePath, toPath: collectionsFile!)
} catch {
print("copy failure.")
}
} else {
print("file myData.plist not found.")
}
} else {
print("file myData.plist already exits at path.")
}
if !fileManager.fileExists(atPath: iconsFile!) {
if let bundlePath = Bundle.main.path(forResource: "icons", ofType: "plist") {
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do {
try fileManager.copyItem(atPath: bundlePath, toPath: iconsFile!)
} catch {
print("copy failure.")
}
} else {
print("file myData.plist not found.")
}
} else {
print("file myData.plist already exits at path.")
}
if !fileManager.fileExists(atPath: colorsFile!) {
if let bundlePath = Bundle.main.path(forResource: "subcolors", ofType: "plist") {
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do {
try fileManager.copyItem(atPath: bundlePath, toPath: colorsFile!)
} catch {
print("copy failure.")
}
} else {
print("file myData.plist not found.")
}
} else {
print("file myData.plist already exits at path.")
}
if !fileManager.fileExists(atPath: commentsFile!) {
if let bundlePath = Bundle.main.path(forResource: "comments", ofType: "plist") {
_ = NSMutableDictionary(contentsOfFile: bundlePath)
do {
try fileManager.copyItem(atPath: bundlePath, toPath: commentsFile!)
} catch {
print("copy failure.")
}
} else {
print("file myData.plist not found.")
}
} else {
print("file myData.plist already exits at path.")
}
session = Session()
History.seenTimes = NSMutableDictionary.init(contentsOfFile: seenFile!)!
History.commentCounts = NSMutableDictionary.init(contentsOfFile: commentsFile!)!
ReadLater.readLaterIDs = NSMutableDictionary.init(contentsOfFile: readLaterFile!)!
Collections.collectionIDs = NSMutableDictionary.init(contentsOfFile: collectionsFile!)!
Subscriptions.subIcons = NSMutableDictionary.init(contentsOfFile: iconsFile!)!
Subscriptions.subColors = NSMutableDictionary.init(contentsOfFile: colorsFile!)!
SettingValues.initialize()
SDImageCache.shared.config.maxDiskAge = 1209600 //2 weeks
SDImageCache.shared.config.maxDiskSize = 250 * 1024 * 1024
SDImageCache.shared.config.diskCacheReadingOptions = .mappedIfSafe // Use mmap for disk cache query
/* SDWebImageManager.shared.optionsProcessor = SDWebImageOptionsProcessor() { url, options, context in
// Disable Force Decoding in global, may reduce the frame rate
var mutableOptions = options
mutableOptions.insert(.avoidDecodeImage)
return SDWebImageOptionsResult(options: mutableOptions, context: context)
}*/
let dictionary = Bundle.main.infoDictionary!
let build = dictionary["CFBundleVersion"] as! String
let lastVersion = UserDefaults.standard.string(forKey: "LAST_BUILD") ?? ""
let lastVersionInt: Int = Int(lastVersion) ?? 0
let currentVersionInt: Int = Int(build) ?? 0
if lastVersionInt < currentVersionInt {
//Clean up broken videos
do {
var dirPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
var directoryContents: NSArray = try FileManager.default.contentsOfDirectory(atPath: dirPath) as NSArray
for path in directoryContents {
let fullPath = dirPath + "/" + (path as! String)
if fullPath.contains(".mp4") {
try FileManager.default.removeItem(atPath: fullPath)
}
}
dirPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0].substring(0, length: dirPath.length - 7)
directoryContents = try FileManager.default.contentsOfDirectory(atPath: dirPath) as NSArray
for path in directoryContents {
let fullPath = dirPath + "/" + (path as! String)
if fullPath.contains(".mp4") {
try FileManager.default.removeItem(atPath: fullPath)
}
}
} catch let e as NSError {
print(e)
}
if currentVersionInt == 142 {
SDImageCache.shared.clearMemory()
SDImageCache.shared.clearDisk()
do {
var cache_path = SDImageCache.shared.diskCachePath
cache_path += cache_path.endsWith("/") ? "" : "/"
let files = try FileManager.default.contentsOfDirectory(atPath: cache_path)
for file in files {
if file.endsWith(".mp4") {
try FileManager.default.removeItem(atPath: cache_path + file)
}
}
} catch {
print(error)
}
}
//Migration block for build 115
if currentVersionInt == 115 {
if UserDefaults.standard.string(forKey: "theme") == "custom" {
var colorString = "slide://colors"
colorString += ("#Theme Backup v3.5").addPercentEncoding
let foregroundColor = UserDefaults.standard.colorForKey(key: "customForeground") ?? UIColor.white
let backgroundColor = UserDefaults.standard.colorForKey(key: "customBackground") ?? UIColor(hexString: "#e5e5e5")
let fontColor = UserDefaults.standard.colorForKey(key: "customFont") ?? UIColor(hexString: "#000000").withAlphaComponent(0.87)
let navIconColor = UserDefaults.standard.colorForKey(key: "customNavicon") ?? UIColor(hexString: "#000000").withAlphaComponent(0.87)
let statusbarEnabled = UserDefaults.standard.bool(forKey: "customStatus")
colorString += (foregroundColor.toHexString() + backgroundColor.toHexString() + fontColor.toHexString() + navIconColor.toHexString() + "#ffffff" + "#ffffff" + "#" + String(statusbarEnabled)).addPercentEncoding
UserDefaults.standard.set(colorString, forKey: "Theme+" + ("Theme Backup v3.5").addPercentEncoding)
UserDefaults.standard.set("Theme Backup v3.5", forKey: "theme")
UserDefaults.standard.synchronize()
}
}
UserDefaults.standard.set(build, forKey: "LAST_BUILD")
}
DTCoreTextFontDescriptor.asyncPreloadFontLookupTable()
FontGenerator.initialize()
AccountController.initialize()
PostFilter.initialize()
Drafts.initialize()
RemovalReasons.initialize()
Subscriptions.sync(name: AccountController.currentName, completion: nil)
if !UserDefaults.standard.bool(forKey: "sc" + name) {
syncColors(subredditController: nil)
}
_ = ColorUtil.doInit()
UIApplication.shared.applicationIconBadgeNumber = 0
_ = resetStack(window: window)
window.makeKeyAndVisible()
WatchSessionManager.sharedManager.doInit()
if SettingValues.notifications {
UIApplication.shared.setMinimumBackgroundFetchInterval(60 * 10) // 10 minute interval
print("Application background refresh minimum interval: \(60 * 10) seconds")
print("Application background refresh status: \(UIApplication.shared.backgroundRefreshStatus.rawValue)")
} else {
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalNever)
print("Application background refresh minimum set to never")
}
#if DEBUG
SettingValues.isPro = true
UserDefaults.standard.set(true, forKey: SettingValues.pref_pro)
UserDefaults.standard.synchronize()
UIApplication.shared.isIdleTimerDisabled = true
#endif
//Stop first video from muting audio
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient, options: [])
} catch {
}
}
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print("Received: \(userInfo)")
}
var statusBar = UIView()
var splitVC = CustomSplitController()
func resetStack(_ soft: Bool = false, window: UIWindow?) -> MainViewController {
guard let window = window else {
fatalError("Window must exist when resetting the stack!")
}
if #available(iOS 14.0, *) {
return doHard14(window)
} else {
// Fallback on earlier versions
return doHard(window)
}
}
func doHard(_ window: UIWindow) -> MainViewController {
let splitViewController = NoHomebarSplitViewController()
let main = SplitMainViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
switch UIDevice.current.userInterfaceIdiom {
case .pad:
switch SettingValues.appMode {
case .SINGLE, .MULTI_COLUMN:
splitViewController.viewControllers = [
SwipeForwardNavigationController(
rootViewController: NavigationHomeViewController(controller: main)),
SwipeForwardNavigationController(
rootViewController: main),
]
case .SPLIT:
let swipeNav = SwipeForwardNavigationController(rootViewController: NavigationHomeViewController(controller: main))
swipeNav.pushViewController(main, animated: false)
splitViewController.viewControllers = [
swipeNav,
PlaceholderViewController(),
]
}
default:
let navHome = NavigationHomeViewController(controller: main)
splitViewController.viewControllers = [SwipeForwardNavigationController(rootViewController: navHome), SwipeForwardNavigationController(rootViewController: main)]
}
window.rootViewController = splitViewController
self.window = window
window.makeKeyAndVisible()
setupSplitLayout(splitViewController)
//Check if in split mode, if so reset to triple column mode
let oldSize = window.frame.size
if abs(UIScreen.main.bounds.width - oldSize.width) > 10 && abs(UIScreen.main.bounds.width - oldSize.height) > 10 { //Size changed, but not orientation
if SettingValues.appMode != .SPLIT && UIDevice.current.userInterfaceIdiom == .pad {
self.resetSplit(main, window: window, true)
}
}
return main
}
func resetSplit(_ main: SplitMainViewController, window: UIWindow, _ split: Bool) {
let splitViewController = NoHomebarSplitViewController()
if (SettingValues.appMode == .SINGLE || SettingValues.appMode == .MULTI_COLUMN) && !split {
splitViewController.viewControllers = [
SwipeForwardNavigationController(
rootViewController: NavigationHomeViewController(controller: main)),
SwipeForwardNavigationController(
rootViewController: main),
]
} else {
let swipeNav = SwipeForwardNavigationController(rootViewController: NavigationHomeViewController(controller: main))
swipeNav.pushViewController(main, animated: false)
splitViewController.viewControllers = [
swipeNav
]
}
if #available(iOS 14.0, *) {
splitViewController.preferredPrimaryColumnWidthFraction = 0.33
splitViewController.minimumPrimaryColumnWidth = UIScreen.main.bounds.width * 0.33
if splitViewController.style == .tripleColumn {
splitViewController.preferredSupplementaryColumnWidthFraction = 0.33
splitViewController.minimumSupplementaryColumnWidth = UIScreen.main.bounds.width * 0.33
}
} else {
splitViewController.preferredPrimaryColumnWidthFraction = 0.4
splitViewController.maximumPrimaryColumnWidth = UIScreen.main.bounds.width * 0.4
}
splitViewController.presentsWithGesture = true
// Set display mode and split behavior
if (SettingValues.appMode == .SINGLE || SettingValues.appMode == .MULTI_COLUMN) && !split {
splitViewController.preferredDisplayMode = .secondaryOnly
if #available(iOS 14.0, *) {
splitViewController.preferredSplitBehavior = .overlay
}
} else {
if #available(iOS 14.0, *) {
splitViewController.preferredDisplayMode = .oneBesideSecondary
splitViewController.preferredSplitBehavior = .displace
} else {
splitViewController.preferredDisplayMode = .allVisible
}
}
window.rootViewController = splitViewController
self.window = window
window.makeKeyAndVisible()
}
@available(iOS 14.0, *)
func doHard14(_ window: UIWindow) -> MainViewController {
let style: UISplitViewController.Style = SettingValues.appMode == .SPLIT ? .tripleColumn : .doubleColumn
var splitViewController: NoHomebarSplitViewController = NoHomebarSplitViewController(style: style)
let main: SplitMainViewController = SplitMainViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
switch UIDevice.current.userInterfaceIdiom {
case .pad:
switch SettingValues.appMode {
case .SINGLE, .MULTI_COLUMN:
splitViewController.setViewController(
SwipeForwardNavigationController(rootViewController: NavigationHomeViewController(controller: main)),
for: .primary)
splitViewController.setViewController(
SwipeForwardNavigationController(rootViewController: main),
for: .secondary)
let main2: SplitMainViewController = SplitMainViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
let compact = SwipeForwardNavigationController(rootViewController: NavigationHomeViewController(controller: main2))
compact.pushViewController(main2, animated: false)
splitViewController.setViewController(compact, for: .compact)
splitViewController.setViewController(
SwipeForwardNavigationController(rootViewController: main),
for: .secondary)
case .SPLIT:
splitViewController.setViewController(
SwipeForwardNavigationController(rootViewController: NavigationHomeViewController(controller: main)),
for: .primary)
splitViewController.setViewController(
SwipeForwardNavigationController(rootViewController: main),
for: .supplementary)
splitViewController.setViewController(
PlaceholderViewController(),
for: .secondary)
}
default:
splitViewController = NoHomebarSplitViewController()
let navHome = NavigationHomeViewController(controller: main)
splitViewController.viewControllers = [SwipeForwardNavigationController(rootViewController: navHome), SwipeForwardNavigationController(rootViewController: main)]
}
window.rootViewController = splitViewController
self.window = window
window.makeKeyAndVisible()
setupSplitLayout(splitViewController)
return main
}
func setupSplitLayout(_ splitViewController: UISplitViewController) {
// Set column widths
if #available(iOS 14.0, *) {
splitViewController.preferredPrimaryColumnWidthFraction = 0.33
splitViewController.minimumPrimaryColumnWidth = UIScreen.main.bounds.width * 0.33
if splitViewController.style == .tripleColumn {
splitViewController.preferredSupplementaryColumnWidthFraction = 0.33
splitViewController.minimumSupplementaryColumnWidth = UIScreen.main.bounds.width * 0.33
}
} else {
splitViewController.preferredPrimaryColumnWidthFraction = 0.4
splitViewController.maximumPrimaryColumnWidth = UIScreen.main.bounds.width * 0.4
}
splitViewController.presentsWithGesture = true
// Set display mode and split behavior
switch UIDevice.current.userInterfaceIdiom {
case .pad:
switch SettingValues.appMode {
case .SINGLE, .MULTI_COLUMN:
if UIApplication.shared.isSplitOrSlideOver {
setupSplitPaneLayout(splitViewController)
} else {
splitViewController.preferredDisplayMode = .secondaryOnly
if #available(iOS 14.0, *) {
splitViewController.preferredSplitBehavior = .overlay
}
}
case .SPLIT:
setupSplitPaneLayout(splitViewController)
}
default:
splitViewController.preferredDisplayMode = .oneOverSecondary
}
}
func setupSplitPaneLayout(_ splitViewController: UISplitViewController) {
if #available(iOS 14.0, *) {
splitViewController.preferredDisplayMode = .oneBesideSecondary
splitViewController.preferredSplitBehavior = .displace
} else {
splitViewController.preferredDisplayMode = .allVisible
}
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if let url = shortcutItem.userInfo?["sub"] {
VCPresenter.openRedditLink("/r/\(url)", window?.rootViewController as? UINavigationController, window?.rootViewController)
} else if shortcutItem.userInfo?["clipboard"] != nil {
var clipUrl: URL?
if let url = UIPasteboard.general.url {
if ContentType.getContentType(baseUrl: url) == .REDDIT {
clipUrl = url
}
}
if clipUrl == nil {
if let urlS = UIPasteboard.general.string {
if let url = URL.init(string: urlS) {
if ContentType.getContentType(baseUrl: url) == .REDDIT {
clipUrl = url
}
}
}
}
if clipUrl != nil {
VCPresenter.openRedditLink(clipUrl!.absoluteString, window?.rootViewController as? UINavigationController, window?.rootViewController)
}
}
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
getData(completionHandler)
}
var backgroundTaskId: UIBackgroundTaskIdentifier?
func getData(_ completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
self.backgroundTaskId = UIApplication.shared.beginBackgroundTask(withName: "Download New Messages") {
UIApplication.shared.endBackgroundTask(self.backgroundTaskId!)
self.backgroundTaskId = UIBackgroundTaskIdentifier(rawValue: convertFromUIBackgroundTaskIdentifier(UIBackgroundTaskIdentifier.invalid))
}
func cleanup() {
UIApplication.shared.endBackgroundTask(self.backgroundTaskId!)
self.backgroundTaskId = UIBackgroundTaskIdentifier(rawValue: convertFromUIBackgroundTaskIdentifier(UIBackgroundTaskIdentifier.invalid))
}
NSLog("getData running...")
guard let session = session,
let request = try? session.getMessageRequest(.unread) else {
completionHandler(.failed)
cleanup()
return
}
func handler (_ response: HTTPURLResponse?, _ dataURL: URL?, _ error: NSError?) {
guard error == nil else {
print(String(describing: error?.localizedDescription))
completionHandler(.failed)
cleanup()
return
}
guard let response = response,
let dataURL = dataURL,
response.statusCode == HttpStatus.ok.rawValue else {
completionHandler(.failed)
cleanup()
return
}
let data: Data
do {
data = try Data(contentsOf: dataURL)
} catch {
print(error.localizedDescription)
completionHandler(.failed)
cleanup()
return
}
switch messagesInResult(from: data, response: response) {
case .success(let listing):
var newCount: Int = 0
let lastMessageUpdateTime = UserDefaults.standard.object(forKey: "lastMessageUpdate") as? TimeInterval ?? Date().timeIntervalSince1970
for case let message as Message in listing.children.reversed() {
if Double(message.createdUtc) > lastMessageUpdateTime {
newCount += 1
// TODO: - If there's more than one new notification, maybe just post
// a message saying "You have new unread messages."
postLocalNotification(message.body, message.author, message.wasComment ? message.context : nil, message.id)
}
}
UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: "lastMessageUpdate")
NSLog("Unread count: \(newCount)")
DispatchQueue.main.sync {
UIApplication.shared.applicationIconBadgeNumber = newCount
}
if newCount > 0 {
NSLog("getData completed with new data.")
completionHandler(.newData)
} else {
NSLog("getData completed with no new data.")
completionHandler(.noData)
}
cleanup()
return
case .failure(let error):
print(error.localizedDescription)
completionHandler(.failed)
cleanup()
return
}
}
if self.fetcher != nil && self.backgroundTaskId != nil {
UIApplication.shared.endBackgroundTask(self.backgroundTaskId!)
fetcher = nil
}
if self.fetcher == nil {
self.fetcher = BackgroundFetch(current: session,
request: request,
taskHandler: handler)
}
self.fetcher?.resume()
}
func postLocalNotification(_ message: String, _ author: String = "", _ permalink: String? = nil, _ id: String) {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
let content = UNMutableNotificationContent()
content.categoryIdentifier = "SlideMail"
if author.isEmpty() {
content.title = "New message!"
} else {
content.title = "New message from \(author)"
}
content.body = message
if permalink != nil {
content.userInfo = ["permalink": "https://www.reddit.com" + permalink!]
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2,
repeats: false)
let identifier = "SlideNewMessage" + id
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if error != nil {
print(error!.localizedDescription)
// Something went wrong
}
})
} else {
// Fallback on earlier versions
}
}
func syncColors(subredditController: MainViewController?) {
let defaults = UserDefaults.standard
var toReturn: [String] = []
defaults.set(true, forKey: "sc" + name)
defaults.synchronize()
do {
if !AccountController.isLoggedIn {
try session?.getSubreddit(.default, paginator: paginator, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!)
case .success(let listing):
self.subreddits += listing.children.compactMap({ $0 as? Subreddit })
self.paginator = listing.paginator
for sub in self.subreddits {
toReturn.append(sub.displayName)
Subscriptions.subIcons[sub.displayName.lowercased()] = sub.iconImg == "" ? sub.communityIcon : sub.iconImg
Subscriptions.subColors[sub.displayName.lowercased()] = sub.keyColor
/* Not needed, we pull from the key color now
if sub.keyColor.hexString() != "#FFFFFF" {
let color = ColorUtil.getClosestColor(hex: sub.keyColor.hexString())
if defaults.object(forKey: "color" + sub.displayName) == nil {
defaults.setColor(color: color, forKey: "color+" + sub.displayName)
}
}*/
}
}
if subredditController != nil {
DispatchQueue.main.async(execute: { () -> Void in
subredditController?.complete(subs: toReturn)
})
}
})
} else {
if UserDefaults.standard.array(forKey: "subs" + (subredditController?.tempToken?.name ?? "")) != nil {
Subscriptions.sync(name: (subredditController?.tempToken?.name ?? ""), completion: nil)
if subredditController != nil {
DispatchQueue.main.async(execute: { () -> Void in
subredditController?.complete(subs: Subscriptions.subreddits)
})
}
} else {
Subscriptions.getSubscriptionsFully(session: session!, completion: { (subs, multis) in
for sub in subs {
toReturn.append(sub.displayName)
/*if sub.keyColor.hexString() != "#FFFFFF" {
let color = ColorUtil.getClosestColor(hex: sub.keyColor.hexString())
if defaults.object(forKey: "color" + sub.displayName) == nil {
defaults.setColor(color: color, forKey: "color+" + sub.displayName)
}
}*/
}
for m in multis {
toReturn.append("/m/" + m.displayName)
if !m.keyColor.isEmpty {
let color = (UIColor.init(hexString: m.keyColor))
if defaults.object(forKey: "color" + m.displayName) == nil {
defaults.setColor(color: color, forKey: "color+" + m.displayName)
}
}
}
toReturn = toReturn.sorted {
$0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending
}
toReturn.insert("all", at: 0)
toReturn.insert("frontpage", at: 0)
if subredditController != nil {
DispatchQueue.main.async(execute: { () -> Void in
subredditController?.complete(subs: toReturn)
})
}
})
}
}
} catch {
print(error)
if subredditController != nil {
DispatchQueue.main.async(execute: { () -> Void in
subredditController?.complete(subs: toReturn)
})
}
}
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
return handleURL(url)
}
func handleURL(_ url: URL) -> Bool {
print("Handling URL \(url)")
let bUrl = url.absoluteString
if bUrl.startsWith("googlechrome://") || bUrl.startsWith("firefox://") || bUrl.startsWith("opera-http://") {
return false
}
if url.absoluteString.contains("/r/") {
VCPresenter.openRedditLink(url.absoluteString.replacingOccurrences(of: "slide://", with: ""), window?.rootViewController as? UINavigationController, window?.rootViewController)
return true
} else if url.absoluteString.contains("colors") {
let themeName = url.absoluteString.removingPercentEncoding!.split("#")[1]
let alert = UIAlertController(title: "Save \"\(themeName.replacingOccurrences(of: "<H>", with: "#"))\"", message: "You can set it as your theme in Settings > Theme\n\n\n\n\n", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Save", style: .default, handler: { (_) in
let colorString = url.absoluteString.removingPercentEncoding!
let title = colorString.split("#")[1]
UserDefaults.standard.set(colorString, forKey: "Theme+" + title)
}))
alert.addCancelButton()
let themeView = ThemeCellView().then {
$0.setTheme(colors: url.absoluteString.removingPercentEncoding!)
}
let cv = themeView.contentView
alert.view.addSubview(cv)
cv.leftAnchor == alert.view.leftAnchor + 8
cv.rightAnchor == alert.view.rightAnchor - 8
cv.topAnchor == alert.view.topAnchor + 90
cv.heightAnchor == 60
alert.showWindowless()
return true
} else if url.absoluteString.contains("reddit.com") || url.absoluteString.contains("google.com/amp") || url.absoluteString.contains("redd.it") {
VCPresenter.openRedditLink(url.absoluteString.replacingOccurrences(of: "slide://", with: ""), window?.rootViewController as? UINavigationController, window?.rootViewController)
return true
} else if url.query?.components(separatedBy: "&").count ?? 0 < 0 {
print("Returning \(url.absoluteString)")
let parameters: [String: String] = url.getKeyVals()!
if let code = parameters["code"], let state = parameters["state"] {
print(state)
if code.length > 0 {
print(code)
}
}
return OAuth2Authorizer.sharedInstance.receiveRedirect(url, completion: { (result) -> Void in
print(result)
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
do {
try LocalKeystore.save(token: token, of: token.name)
self.login?.setToken(token: token)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
} catch {
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidFailToSaveTokenName, object: nil, userInfo: nil)
print(error)
}
})
}
})
} else {
return true
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
if #available(iOS 13.0, *) { return } else {
didBecomeActive()
}
}
func didBecomeActive() {
if AccountController.current == nil && UserDefaults.standard.string(forKey: "name") != "GUEST" {
AccountController.initialize()
}
if let url = launchedURL {
handleURL(url)
launchedURL = nil
}
UIView.animate(withDuration: 0.25, animations: {
self.backView?.alpha = 0
}, completion: { (_) in
self.backView?.alpha = 1
self.backView?.isHidden = true
})
if totalBackground && SettingValues.biometrics && !TopLockViewController.presented {
let topLock = TopLockViewController()
topLock.modalPresentationStyle = .overFullScreen
UIApplication.shared.keyWindow?.topViewController()?.present(topLock, animated: false, completion: nil)
}
fetchFromiCloud("readlater", dictionaryToAppend: ReadLater.readLaterIDs) { (record) in
self.readLaterRecord = record
}
fetchFromiCloud("collections", dictionaryToAppend: Collections.collectionIDs) { (record) in
self.collectionRecord = record
let removeDict = NSMutableDictionary()
self.fetchFromiCloud("removed", dictionaryToAppend: removeDict) { (record) in
self.deletedRecord = record
let removeKeys = removeDict.allKeys as! [String]
for item in removeKeys {
Collections.collectionIDs.removeObject(forKey: item)
ReadLater.readLaterIDs.removeObject(forKey: item)
}
}
}
}
var backView: UIView?
func applicationWillResignActive(_ application: UIApplication) {
if #available(iOS 13.0, *) { return } else {
willResignActive()
}
}
func willResignActive() {
if SettingValues.biometrics {
if backView == nil {
backView = UIView.init(frame: self.window!.frame)
backView?.backgroundColor = ColorUtil.theme.backgroundColor
if let window = self.window {
window.insertSubview(backView!, at: 0)
backView!.edgeAnchors == window.edgeAnchors
backView!.layer.zPosition = 1
}
}
self.backView?.isHidden = false
}
totalBackground = false
}
var readLaterRecord: CKRecord?
var collectionRecord: CKRecord?
var deletedRecord: CKRecord?
func saveToiCloud(_ dictionary: NSDictionary, _ key: String, _ record: CKRecord?) {
let collectionsRecord: CKRecord
if record != nil {
collectionsRecord = record!
} else {
collectionsRecord = CKRecord(recordType: key)
}
do {
let data: NSData = try PropertyListSerialization.data(fromPropertyList: dictionary, format: PropertyListSerialization.PropertyListFormat.xml, options: 0) as NSData
if let datastring = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) {
collectionsRecord.setValue(datastring, forKey: "data_xml")
} else {
print("Could not turn nsdata to string")
}
print("Saving to iCloud \(key)")
CKContainer(identifier: "iCloud.\(USR_DOMAIN).redditslide").privateCloudDatabase.save(collectionsRecord) { (_, error) in
if error != nil {
print("iCloud error")
print(error.debugDescription)
}
}
} catch {
print("Error serializing dictionary")
}
}
func fetchFromiCloud(_ key: String, dictionaryToAppend: NSMutableDictionary, completion: ((_ record: CKRecord) -> Void)? = nil) {
let privateDatabase = CKContainer(identifier: "iCloud.\(USR_DOMAIN).redditslide").privateCloudDatabase
let query = CKQuery(recordType: CKRecord.RecordType(stringLiteral: key), predicate: NSPredicate(value: true))
print("Reading from iCloud")
privateDatabase.perform(query, inZoneWith: nil) { (records, error) in
if error != nil {
print("Error fetching records...")
print(error?.localizedDescription ?? "")
} else {
if let unwrappedRecord = records?[0] {
if let object = unwrappedRecord.object(forKey: "data_xml") as? String {
if let data = object.data(using: String.Encoding.utf8) {
do {
let dict = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions.mutableContainersAndLeaves, format: nil) as? NSMutableDictionary
for item in dict ?? [:] {
dictionaryToAppend[item.key] = item.value
}
completion?(unwrappedRecord)
return
} catch {
print("Could not de-serialize list")
}
}
}
} else {
print("No record found!")
}
}
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
if #available(iOS 13.0, *) { return } else {
didEnterBackground()
}
}
func didEnterBackground() {
totalBackground = true
History.seenTimes.write(toFile: seenFile!, atomically: true)
History.commentCounts.write(toFile: commentsFile!, atomically: true)
ReadLater.readLaterIDs.write(toFile: readLaterFile!, atomically: true)
Collections.collectionIDs.write(toFile: collectionsFile!, atomically: true)
Subscriptions.subIcons.write(toFile: iconsFile!, atomically: true)
Subscriptions.subColors.write(toFile: colorsFile!, atomically: true)
saveToiCloud(Collections.collectionIDs, "collections", self.collectionRecord)
saveToiCloud(ReadLater.readLaterIDs, "readlater", self.readLaterRecord)
saveToiCloud(AppDelegate.removeDict, "removed", self.deletedRecord)
// 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) {
self.refreshSession()
}
func refreshSession() {
// refresh current session token
do {
try self.session?.refreshTokenLocal({ (result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
print(token)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
})
}
})
} catch {
print(error)
}
}
func reloadSession() {
// reddit username is save NSUserDefaults using "currentName" key.
// create an authenticated or anonymous session object
if let currentName = UserDefaults.standard.object(forKey: "name") as? String {
do {
let token: OAuth2Token
if AccountController.isMigrated(currentName) {
token = try LocalKeystore.token(of: currentName)
} else {
token = try OAuth2TokenRepository.token(of: currentName)
}
self.session = Session(token: token)
self.refreshSession()
} catch {
print(error)
}
} else {
self.session = Session()
}
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
}
}
extension URL {
func getKeyVals() -> [String: String]? {
var results = [String: String]()
let keyValues = self.query?.components(separatedBy: "&")
if (keyValues?.count) ?? 0 > 0 {
for pair in keyValues! {
let kv = pair.components(separatedBy: "=")
if kv.count > 1 {
results.updateValue(kv[1], forKey: kv[0])
}
}
}
return results
}
}
extension Session {
/**
Refresh own token.
- parameter completion: The completion handler to call when the load request is complete.
*/
public func refreshTokenLocal(_ completion: @escaping (Result<Token>) -> Void) throws {
guard let currentToken = token as? OAuth2Token
else { throw ReddiftError.tokenIsNotAvailable as NSError }
do {
try currentToken.refresh({ (result) -> Void in
switch result {
case .failure(let error):
completion(Result(error: error as NSError))
case .success(let newToken):
DispatchQueue.main.async(execute: { () -> Void in
self.token = newToken
do {
try LocalKeystore.save(token: newToken)
completion(Result(value: newToken))
} catch { completion(Result(error: error as NSError)) }
})
}
})
} catch { throw error }
}
/**
Revoke own token. After calling this function, this object must be released becuase it has lost any conection.
- parameter completion: The completion handler to call when the load request is complete.
*/
public func revokeTokenLocal(_ completion: @escaping (Result<Token>) -> Void) throws {
guard let currentToken = token as? OAuth2Token
else { throw ReddiftError.tokenIsNotAvailable as NSError }
do {
try currentToken.revoke({ (result) -> Void in
switch result {
case .failure(let error):
completion(Result(error: error as NSError))
case .success:
DispatchQueue.main.async(execute: { () -> Void in
do {
try LocalKeystore.removeToken(of: currentToken.name)
completion(Result(value: currentToken))
} catch { completion(Result(error: error as NSError)) }
})
}
})
} catch { throw error }
}
/**
Set an expired token to self.
This method is implemented in order to test codes to automatiaclly refresh an expired token.
*/
public func setDummyExpiredToken() {
if let path = Bundle.main.path(forResource: "expired_token.json", ofType: nil), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] {
let token = OAuth2Token(json)
self.token = token
}
} catch { print(error) }
}
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromUIBackgroundTaskIdentifier(_ input: UIBackgroundTaskIdentifier) -> Int {
return input.rawValue
}
class CustomSplitController: UISplitViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
if ColorUtil.theme.isLight && SettingValues.reduceColor {
if #available(iOS 13, *) {
return .darkContent
} else {
return .default
}
} else {
return .lightContent
}
}
}
@available(iOS 13.0, *)
extension AppDelegate: UIWindowSceneDelegate {
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
handleURL(url)
}
}
func sceneDidBecomeActive(_ scene: UIScene) {
didBecomeActive()
}
func sceneWillEnterForeground(_ scene: UIScene) {
self.refreshSession()
}
func sceneDidEnterBackground(_ scene: UIScene) {
didEnterBackground()
}
func sceneWillResignActive(_ scene: UIScene) {
willResignActive()
}
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if let url = shortcutItem.userInfo?["sub"] {
VCPresenter.openRedditLink("/r/\(url)", window?.rootViewController as? UINavigationController, window?.rootViewController)
} else if shortcutItem.userInfo?["clipboard"] != nil {
var clipUrl: URL?
if let url = UIPasteboard.general.url {
if ContentType.getContentType(baseUrl: url) == .REDDIT {
clipUrl = url
}
}
if clipUrl == nil {
if let urlS = UIPasteboard.general.string {
if let url = URL.init(string: urlS) {
if ContentType.getContentType(baseUrl: url) == .REDDIT {
clipUrl = url
}
}
}
}
if clipUrl != nil {
VCPresenter.openRedditLink(clipUrl!.absoluteString, window?.rootViewController as? UINavigationController, window?.rootViewController)
}
}
}
//Siri shortcuts and deep links
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
print(userActivity.userInfo)
if (userActivity.userInfo?["TYPE"] as? NSString) ?? "" == "SUBREDDIT" {
VCPresenter.openRedditLink("/r/\(userActivity.title ?? "")", window?.rootViewController as? UINavigationController, window?.rootViewController)
} else if (userActivity.userInfo?["TYPE"] as? NSString) ?? "" == "INBOX" {
VCPresenter.showVC(viewController: InboxViewController(), popupIfPossible: false, parentNavigationController: window?.rootViewController as? UINavigationController, parentViewController: window?.rootViewController)
} else if let url = userActivity.webpageURL {
handleURL(url)
} else if let permalink = userActivity.userInfo?["permalink"] as? String {
VCPresenter.openRedditLink(permalink, window?.rootViewController as? UINavigationController, window?.rootViewController)
}
}
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
if let url = connectionOptions.urlContexts.first?.url {
launchedURL = url
}
if let notification = connectionOptions.notificationResponse {
let userInfo = notification.notification.request.content.userInfo as? NSDictionary
if let url = userInfo?["permalink"] as? String {
launchedURL = URL(string: url)
}
}
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
self.window = window
didFinishLaunching(window: window)
/* TODO This launchedURL = launchOptions?[UIApplication.LaunchOptionsKey.url] as? URL
let remoteNotif = launchOptions?[UIApplication.LaunchOptionsKey.localNotification] as? UILocalNotification
if remoteNotif != nil {
if let url = remoteNotif!.userInfo?["permalink"] as? String {
VCPresenter.openRedditLink(url, window?.rootViewController as? UINavigationController, window?.rootViewController)
} else {
VCPresenter.showVC(viewController: InboxViewController(), popupIfPossible: false, parentNavigationController: window?.rootViewController as? UINavigationController, parentViewController: window?.rootViewController)
}restore
}*/
}
if let userActivity = connectionOptions.userActivities.first {
if (userActivity.userInfo?["TYPE"] as? NSString) ?? "" == "SUBREDDIT" {
VCPresenter.openRedditLink("/r/\(userActivity.title ?? "")", window?.rootViewController as? UINavigationController, window?.rootViewController)
} else if (userActivity.userInfo?["TYPE"] as? NSString) ?? "" == "INBOX" {
VCPresenter.showVC(viewController: InboxViewController(), popupIfPossible: false, parentNavigationController: window?.rootViewController as? UINavigationController, parentViewController: window?.rootViewController)
} else if let url = userActivity.webpageURL {
handleURL(url)
}
}
}
}
@available(iOS 10.0, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo as? NSDictionary
if let url = userInfo?["permalink"] as? String {
if #available(iOS 13, *) {
guard var rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? AppDelegate)?.window?.rootViewController else { return }
VCPresenter.openRedditLink(url, rootViewController as? UINavigationController, rootViewController)
} else {
VCPresenter.openRedditLink(url, window?.rootViewController as? UINavigationController, window?.rootViewController)
}
} else {
if #available(iOS 13, *) {
guard var rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? AppDelegate)?.window?.rootViewController else { return }
VCPresenter.showVC(viewController: InboxViewController(), popupIfPossible: false, parentNavigationController: rootViewController as? UINavigationController, parentViewController: rootViewController)
} else {
VCPresenter.showVC(viewController: InboxViewController(), popupIfPossible: false, parentNavigationController: window?.rootViewController as? UINavigationController, parentViewController: window?.rootViewController)
}
}
}
}
class NoHomebarSplitViewController: UISplitViewController {
override var prefersHomeIndicatorAutoHidden: Bool {
return true
}
override var childForHomeIndicatorAutoHidden: UIViewController? {
return nil
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if ColorUtil.theme.isLight && SettingValues.reduceColor {
if #available(iOS 13, *) {
return .darkContent
} else {
return .default
}
} else {
return .lightContent
}
}
override var prefersStatusBarHidden: Bool {
return SettingValues.fullyHideNavbar
}
}
|
apache-2.0
|
163601918477511967331afec446e2ab
| 43.467903 | 234 | 0.581499 | 5.754477 | false | false | false | false |
reza-ryte-club/firefox-ios
|
Sync/Synchronizers/ClientsSynchronizer.swift
|
8
|
14119
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
private let log = Logger.syncLogger
let ClientsStorageVersion = 1
// TODO
public protocol Command {
static func fromName(command: String, args: [JSON]) -> Command?
func run(synchronizer: ClientsSynchronizer) -> Success
static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command?
}
// Shit.
// We need a way to wipe or reset engines.
// We need a way to log out the account.
// So when we sync commands, we're gonna need a delegate of some kind.
public class WipeCommand: Command {
public init?(command: String, args: [JSON]) {
return nil
}
public class func fromName(command: String, args: [JSON]) -> Command? {
return WipeCommand(command: command, args: args)
}
public func run(synchronizer: ClientsSynchronizer) -> Success {
return succeed()
}
public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? {
let json = JSON.parse(syncCommand.value)
if let name = json["command"].asString,
args = json["args"].asArray {
return WipeCommand.fromName(name, args: args)
}
return nil
}
}
public class DisplayURICommand: Command {
let uri: NSURL
let title: String
public init?(command: String, args: [JSON]) {
if let uri = args[0].asString?.asURL,
title = args[2].asString {
self.uri = uri
self.title = title
} else {
// Oh, Swift.
self.uri = "http://localhost/".asURL!
self.title = ""
return nil
}
}
public class func fromName(command: String, args: [JSON]) -> Command? {
return DisplayURICommand(command: command, args: args)
}
public func run(synchronizer: ClientsSynchronizer) -> Success {
synchronizer.delegate.displaySentTabForURL(uri, title: title)
return succeed()
}
public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? {
let json = JSON.parse(syncCommand.value)
if let name = json["command"].asString,
args = json["args"].asArray {
return DisplayURICommand.fromName(name, args: args)
}
return nil
}
}
let Commands: [String: (String, [JSON]) -> Command?] = [
"wipeAll": WipeCommand.fromName,
"wipeEngine": WipeCommand.fromName,
// resetEngine
// resetAll
// logout
"displayURI": DisplayURICommand.fromName,
]
public class ClientsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "clients")
}
override var storageVersion: Int {
return ClientsStorageVersion
}
var clientRecordLastUpload: Timestamp {
set(value) {
self.prefs.setLong(value, forKey: "lastClientUpload")
}
get {
return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0
}
}
public func getOurClientRecord() -> Record<ClientPayload> {
let guid = self.scratchpad.clientGUID
let json = JSON([
"id": guid,
"version": "0.1", // TODO
"protocols": ["1.5"],
"name": self.scratchpad.clientName,
"os": "iOS",
"commands": [JSON](),
"type": "mobile",
"appPackage": NSBundle.mainBundle().bundleIdentifier ?? "org.mozilla.ios.FennecUnknown",
"application": DeviceInfo.appName(),
"device": DeviceInfo.deviceModel(),
// Do better here: Bug 1157518.
"formfactor": DeviceInfo.isSimulator() ? "simulator" : "phone",
])
let payload = ClientPayload(json)
return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds)
}
private func clientRecordToLocalClientEntry(record: Record<ClientPayload>) -> RemoteClient {
let modified = record.modified
let payload = record.payload
return RemoteClient(json: payload, modified: modified)
}
// If this is a fresh start, do a wipe.
// N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!)
// N.B., but perhaps we should discard outgoing wipe/reset commands!
private func wipeIfNecessary(localClients: RemoteClientsAndTabs) -> Success {
if self.lastFetched == 0 {
return localClients.wipeClients()
}
return succeed()
}
/**
* Returns whether any commands were found (and thus a replacement record
* needs to be uploaded). Also returns the commands: we run them after we
* upload a replacement record.
*/
private func processCommandsFromRecord(record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> {
log.debug("Processing commands from downloaded record.")
// TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead.
if let record = record {
let commands = record.payload.commands
if !commands.isEmpty {
func parse(json: JSON) -> Command? {
if let name = json["command"].asString,
args = json["args"].asArray,
constructor = Commands[name] {
return constructor(name, args)
}
return nil
}
// TODO: can we do anything better if a command fails?
return deferMaybe((true, optFilter(commands.map(parse))))
}
}
return deferMaybe((false, []))
}
private func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
return localClients.getCommands() >>== { clientCommands in
return clientCommands.map { (clientGUID, commands) -> Success in
self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient)
}.allSucceed()
}
}
private func syncClientCommands(clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
let deleteCommands: () -> Success = {
return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() })
}
log.debug("Fetching current client record for client \(clientGUID).")
let fetch = storageClient.get(clientGUID)
return fetch.bind() { result in
if let response = result.successValue {
let record = response.value
if var clientRecord = record.payload.asDictionary {
clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON.parse($0.value) })
let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds)
return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified)
>>== { resp in
log.debug("Client \(clientGUID) commands upload succeeded.")
// Always succeed, even if we couldn't delete the commands.
return deleteCommands()
}
}
} else {
if let failure = result.failureValue {
log.warning("Failed to fetch record with GUID \(clientGUID).")
if failure is NotFound<NSHTTPURLResponse> {
log.debug("Not waiting to see if the client comes back.")
// TODO: keep these around and retry, expiring after a while.
// For now we just throw them away so we don't fail every time.
return deleteCommands()
}
if failure is BadRequestError<NSHTTPURLResponse> {
log.debug("We made a bad request. Throwing away queued commands.")
return deleteCommands()
}
}
}
log.error("Client \(clientGUID) commands upload failed: No remote client for GUID")
return deferMaybe(UnknownError())
}
}
/**
* Upload our record if either (a) we know we should upload, or (b)
* our own notes tell us we're due to reupload.
*/
private func maybeUploadOurRecord(should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
let lastUpload = self.clientRecordLastUpload
let expired = lastUpload < (NSDate.now() - (2 * OneDayInMilliseconds))
log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).")
if !should && !expired {
return succeed()
}
let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload)
return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS)
>>== { resp in
if let ts = resp.metadata.lastModifiedMilliseconds {
// Protocol says this should always be present for success responses.
log.debug("Client record upload succeeded. New timestamp: \(ts).")
self.clientRecordLastUpload = ts
}
return succeed()
}
}
private func applyStorageResponse(response: StorageResponse<[Record<ClientPayload>]>, toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
log.debug("Applying clients response.")
let records = response.value
let responseTimestamp = response.metadata.lastModifiedMilliseconds
log.debug("Got \(records.count) client records.")
let ourGUID = self.scratchpad.clientGUID
var toInsert = [RemoteClient]()
var ours: Record<ClientPayload>? = nil
for (rec) in records {
if rec.id == ourGUID {
if rec.modified == self.clientRecordLastUpload {
log.debug("Skipping our own unmodified record.")
} else {
log.debug("Saw our own record in response.")
ours = rec
}
} else {
toInsert.append(self.clientRecordToLocalClientEntry(rec))
}
}
// Apply remote changes.
// Collect commands from our own record and reupload if necessary.
// Then run the commands and return.
return localClients.insertOrUpdateClients(toInsert)
>>== { self.processCommandsFromRecord(ours, withServer: storageClient) }
>>== { (shouldUpload, commands) in
return self.maybeUploadOurRecord(shouldUpload, ifUnmodifiedSince: ours?.modified, toServer: storageClient)
>>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) }
>>> {
log.debug("Running \(commands.count) commands.")
for (command) in commands {
command.run(self)
}
self.lastFetched = responseTimestamp!
return succeed()
}
}
}
public func synchronizeLocalClients(localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult {
log.debug("Synchronizing clients.")
if let reason = self.reasonToNotSync(storageClient) {
switch reason {
case .EngineRemotelyNotEnabled:
// This is a hard error for us.
return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?"))
default:
return deferMaybe(SyncStatus.NotStarted(reason))
}
}
let keys = self.scratchpad.keys?.value
let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0 })
let encrypter = keys?.encrypter(self.collection, encoder: encoder)
if encrypter == nil {
log.error("Couldn't make clients encrypter.")
return deferMaybe(FatalError(message: "Couldn't make clients encrypter."))
}
let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!)
if !self.remoteHasChanges(info) {
log.debug("No remote changes for clients. (Last fetched \(self.lastFetched).)")
return self.maybeUploadOurRecord(false, ifUnmodifiedSince: nil, toServer: clientsClient)
>>> { self.uploadClientCommands(toLocalClients: localClients, withServer: clientsClient) }
>>> { deferMaybe(.Completed) }
}
// TODO: some of the commands we process might involve wiping collections or the
// entire profile. We should model this as an explicit status, and return it here
// instead of .Completed.
return clientsClient.getSince(self.lastFetched)
>>== { response in
return self.wipeIfNecessary(localClients)
>>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient) }
}
>>> { deferMaybe(.Completed) }
}
}
|
mpl-2.0
|
4df40a4c0a895656a6e5564d24897f03
| 40.283626 | 218 | 0.603513 | 5.264355 | false | false | false | false |
mattadatta/sulfur
|
Sulfur/Gradient.swift
|
1
|
4364
|
/*
This file is subject to the terms and conditions defined in
file 'LICENSE.txt', which is part of this source code package.
*/
import UIKit
// MARK: - Gradient
public struct Gradient {
fileprivate struct Constants {
static let defaultStops = [
Stop(color: .black, percent: 0.0),
Stop(color: .white, percent: 1.0),
]
}
public struct Stop: Hashable {
public var color: UIColor
public var percent: Double
public init(color: UIColor, percent: Double) {
self.color = color
self.percent = max(0.0, min(1.0, percent))
}
public var hashValue: Int {
return Hasher()
.adding(hashable: self.color)
.adding(part: self.percent)
.hashValue
}
public static func ==(lhs: Stop, rhs: Stop) -> Bool {
return lhs.color == rhs.color && lhs.percent == rhs.percent
}
}
public var stops: [Stop] {
didSet {
if self.stops.count < 2 {
self.stops = Constants.defaultStops
}
self.stops.sort(by: { $0.percent <= $1.percent })
}
}
public var colors: [UIColor] {
get { return self.stops.map({ $0.color }) }
set {
guard newValue.count > 1 else {
self.stops = Constants.defaultStops
return
}
let increment = 1.0 / Double(newValue.count - 1)
self.stops = newValue.mapPass(0.0) { color, percentage in
return (Stop(color: color, percent: percentage), percentage + increment)
}
}
}
public init() {
self.init(stops: Constants.defaultStops)
}
public init(stops: [Stop]) {
self.stops = (stops.count > 2) ? stops : Constants.defaultStops
}
public init(colors: [UIColor]) {
self.stops = Constants.defaultStops
self.colors = colors
}
public func interpolatedColorForPercentage(_ percent: Double) -> UIColor {
let percent = max(self.stops.first!.percent, min(self.stops.last!.percent, percent))
var firstIndex = 0, lastIndex = 1
while !(self.stops[firstIndex].percent <= percent &&
self.stops[lastIndex].percent >= percent) &&
lastIndex < self.stops.count
{
firstIndex = firstIndex + 1
lastIndex = lastIndex + 1
}
let stop1 = self.stops[firstIndex]
let stop2 = self.stops[lastIndex]
let interpolatedPercent = CGFloat((percent - stop1.percent) / (stop2.percent - stop1.percent))
let color1 = stop1.color
let color2 = stop2.color
let resultRed = color1.red + (interpolatedPercent * (color2.red - color1.red))
let resultGreen = color1.green + (interpolatedPercent * (color2.green - color1.green))
let resultBlue = color1.blue + (interpolatedPercent * (color2.blue - color1.blue))
let resultAlpha = color1.alpha + (interpolatedPercent * (color2.alpha - color1.alpha))
return UIColor(red: resultRed, green: resultGreen, blue: resultBlue, alpha: resultAlpha)
}
}
// MARK: - GradientView
public final class GradientView: UIView {
override public class var layerClass: AnyClass {
return CAGradientLayer.self
}
public var gradientLayer: CAGradientLayer {
return self.layer as! CAGradientLayer
}
public var gradient: Gradient = Gradient() {
didSet {
self.gradientLayer.colors = self.gradient.colors.map({ $0.cgColor })
self.gradientLayer.locations = self.gradient.stops.map({ NSNumber(value: $0.percent) })
}
}
public var startPoint: CGPoint {
get { return self.gradientLayer.startPoint }
set { self.gradientLayer.startPoint = newValue }
}
public var endPoint: CGPoint {
get { return self.gradientLayer.endPoint }
set { self.gradientLayer.endPoint = newValue }
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
fileprivate func commonInit() {
self.gradient = Gradient() // Trigger didSet
}
}
|
mit
|
353665b04c7c294d28cb2275c24a2a50
| 28.687075 | 102 | 0.586618 | 4.350947 | false | false | false | false |
carabina/ActionSwift3
|
ActionSwiftSK/GameViewController.swift
|
1
|
6048
|
//
// GameViewController.swift
// ActionSwiftSK
//
// Created by Craig on 5/05/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
let walkingTextures = ["walking1","walking2","walking3","walking4","walking5","walking6","walking7","walking8","walking9"]
var movieClip:MovieClip!
var sound:Sound = Sound(name: "")
override func viewDidLoad() {
super.viewDidLoad()
//create stage
let stage = Stage(self.view as! SKView)
//------------------------------------------------------------------------------------------------------------------
//create a simple stop button
//create two sprites for up and down states for the stop button
//add a couple of rectangles to its graphics property to make a stop symbol
let stopUpState = Sprite()
stopUpState.graphics.beginFill(UIColor.whiteColor())
stopUpState.graphics.drawRect(0,0,44,44)
stopUpState.graphics.beginFill(UIColor(hex:"#B21212"))
stopUpState.graphics.drawRect(10,10,24,24)
let stopDownState = Sprite()
stopDownState.graphics.beginFill(UIColor.whiteColor())
stopDownState.graphics.drawRect(0,0,44,44)
stopDownState.graphics.beginFill(UIColor(hex:"#FF0000"))
stopDownState.graphics.drawRect(8,8,28,28)
let stop = SimpleButton(upState: stopUpState, downState: stopDownState)
stop.x = 10
stop.y = 10
stop.name = "stop"
stop.addEventListener(InteractiveEventType.TouchBegin.rawValue, EventHandler(spriteTouched, "spriteTouched"))
stage.addChild(stop)
//------------------------------------------------------------------------------------------------------------------
//create a simple play button
//create two sprites for up and down states for the play button
//add a circle and triangle to its graphics property to make a play symbol
let playUpState = Sprite()
playUpState.graphics.beginFill(UIColor.whiteColor())
playUpState.graphics.drawCircle(22, 22, 22)
playUpState.graphics.beginFill(UIColor(hex:"#0971B2"))
playUpState.graphics.drawTriangle(14, 12, 14, 32, 34, 22)
let playDownState = Sprite()
playDownState.graphics.beginFill(UIColor.whiteColor())
playDownState.graphics.drawCircle(22, 22, 22)
playDownState.graphics.beginFill(UIColor(hex:"#1485CC"))
playDownState.graphics.drawTriangle(12, 10, 12, 34, 38, 22)
let play = SimpleButton(upState: playUpState, downState: playDownState)
play.x = Stage.size.width - 54
play.y = 10
play.name = "play"
play.addEventListener(InteractiveEventType.TouchBegin.rawValue, EventHandler(spriteTouched, "spriteTouched"))
stage.addChild(play)
//------------------------------------------------------------------------------------------------------------------
//create a movieclip, add textures from 'images.atlas', then control it just as you would in AS3
movieClip = MovieClip(textureNames: walkingTextures)
movieClip.x = 0
movieClip.y = Stage.size.height - movieClip.height
movieClip.addEventListener(InteractiveEventType.TouchBegin.rawValue, EventHandler(spriteTouched, "spriteTouched"))
movieClip.addEventListener(InteractiveEventType.TouchEnd.rawValue, EventHandler(spriteTouched, "spriteTouched"))
movieClip.name = "walkingman"
stage.addChild(movieClip)
//------------------------------------------------------------------------------------------------------------------
//create a textfield, apply text formatting with a TextFormat object
let text = TextField()
text.width = 200
text.text = "Walking man"
let textFormat = TextFormat(font: "ArialMT", size: 20, leading: 20, color: UIColor.blackColor(),align:.Center)
text.defaultTextFormat = textFormat
text.x = (Stage.stageWidth / 2) - 100
text.y = 20
stage.addChild(text)
}
func spriteAdded(event:Event) -> Void {
trace("sprite added ")
}
func spriteTouched(event:Event) -> Void {
if let touchEvent = event as? TouchEvent {
if let currentTarget = touchEvent.currentTarget as? DisplayObject {
if (currentTarget.name == "walkingman") {
//drag/drop
if let currentTarget = currentTarget as? Sprite {
if touchEvent.type == InteractiveEventType.TouchBegin.rawValue {
currentTarget.startDrag()
} else if touchEvent.type == InteractiveEventType.TouchEnd.rawValue {
currentTarget.stopDrag()
}
}
} else if (currentTarget.name == "play") {
sound = Sound(name: "ButtonTap.wav")
sound.play()
movieClip.play()
} else if (currentTarget.name == "stop") {
sound = Sound(name: "SecondBeep.wav")
sound.play()
movieClip.stop()
}
}
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
45e1ed4ca3a3073618e4a839968dbac3
| 41 | 126 | 0.566138 | 4.889248 | false | false | false | false |
iOSWizards/AwesomeData
|
AwesomeData/Classes/CoreData/NSManagedObject+Awesome.swift
|
1
|
12501
|
//
// NSManagedObject+Awesome.swift
// AwesomeData
//
// Created by Evandro Harrison Hoffmann on 02/08/2016.
// Copyright © 2016 It's Day Off. All rights reserved.
//
import CoreData
// MARK: - Coredata Configuration
extension NSManagedObject {
/*
* Saves context. (commits database)
* @param managedContext: context for wanted database | as default, will get the standard Coredata shared instance for the App
*/
public static func save(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext){
do {
if managedContext.hasChanges {
try managedContext.save()
}
} catch {
let nserror = error as NSError
NSLog("Could not save \(nserror), \(nserror.userInfo)")
abort()
}
}
/**
It saves the managedContext asynchronisly.
## Important Notes ##
* If something goes wrong **false** is returned on the saved block.
*/
public static func saveAsync(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext, saved: @escaping (Bool) -> Void) {
managedContext.perform({
do {
if managedContext.hasChanges {
try managedContext.save()
saved(true)
}
} catch {
let nserror = error as NSError
NSLog("Could not save \(nserror), \(nserror.userInfo)")
saved(false)
abort()
}
})
}
/*
* Creates a new instance of the current NSManagedObject
* @param managedContext: as default, will get the standard Coredata shared instance for the App
*/
public static func newInstance(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext) -> NSManagedObject{
let entity = NSEntityDescription.entity(forEntityName: String(describing: self), in:managedContext)
return NSManagedObject(entity: entity!, insertInto:managedContext)
}
/*
* Deletes the instance of the current instance of NSManagedObject
* @param managedContext: context for wanted database | as default, will get the standard Coredata shared instance for the App
*/
public func deleteInstance(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext){
managedContext.delete(self)
}
/*
* Deletes all instances of current NSManagedObject Class
* @param managedContext: context for wanted database | as default, will get the standard Coredata shared instance for the App
*/
public static func deleteAllInstances() {
let list = self.list()
for object in list {
object.deleteInstance()
}
do {
let managedContext = AwesomeDataAccess.sharedInstance.managedObjectContext
try managedContext.save()
} catch {
let nserror = error as NSError
NSLog("Could not delete \(nserror), \(nserror.userInfo)")
abort()
}
}
/*
* Lists all instances of the current NSManagedObject with sortDescriptor
* @param managedContext: context for wanted database | as default, will get the standard Coredata shared instance for the App
* @param sortDescriptor: NSSortDescriptor with sort params
*/
public static func list(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext, sortDescriptor: NSSortDescriptor? = nil, predicate: NSPredicate? = nil) -> [NSManagedObject]{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: self))
if let sortDescriptor = sortDescriptor {
fetchRequest.sortDescriptors = [sortDescriptor]
}
if let predicate = predicate {
fetchRequest.predicate = predicate
}
var fetchedResults: [NSManagedObject]!
do {
try fetchedResults = managedContext.fetch(fetchRequest) as! [NSManagedObject]
if let results: [NSManagedObject] = fetchedResults {
return results
}
}catch{
let nserror = error as NSError
print("Could not fetch \(nserror), \(nserror.userInfo)")
}
return fetchedResults
}
/**
It lists the domain associated with the managedContext asynchronisly.
- Parameter withContext: the ***NSManagedObjectContext***, if not provided the default one is used.
- Parameter sortDescriptor: the ***NSSortDescriptor***, if not provided no sort is guaranteed.
- Parameter predicate: the ***NSPredicate***, if not provided all records of this domain are listed.
- Parameter successFetch: the response block to retrieve the objects listed.
*/
public static func listAsync(
withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext,
sortDescriptor: NSSortDescriptor? = nil,
predicate: NSPredicate? = nil,
successFetch: @escaping ([NSManagedObject]) -> Void,
failure:@escaping (()->Void)) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: self))
if let sortDescriptor = sortDescriptor {
fetchRequest.sortDescriptors = [sortDescriptor]
}
if let predicate = predicate {
fetchRequest.predicate = predicate
}
// Initialize Asynchronous Fetch Request
let asynchronousFetchRequest = NSAsynchronousFetchRequest.init(fetchRequest: fetchRequest, completionBlock: { (asyncFetchResult) in
DispatchQueue.main.async {
if let result = asyncFetchResult.finalResult as? [NSManagedObject] {
successFetch(result)
} else {
failure()
}
}
})
do {
try managedContext.execute(asynchronousFetchRequest)
} catch {
let nserror = error as NSError
print("Could not fetch \(nserror), \(nserror.userInfo)")
failure()
}
}
/*
* Returns the first instance of a list of Fetched NSManagedObject based on predicate filtering
* @param managedContext: context for wanted database | as default, will get the standard Coredata shared instance for the App
* @param predicate: NSPredicate for filtering results
* @param createIfNil: if set to true, it will return a new instance of the NSManagedObject in case it doesn't find a match
*/
public static func getObject(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext, predicate: NSPredicate, createIfNil: Bool = false) -> NSManagedObject? {
let fetchedObjects: [NSManagedObject]? = list(withContext: managedContext, predicate: predicate)
if let fetchedObjects = fetchedObjects {
if fetchedObjects.count > 0{
if AwesomeData.showLogs { print("fetched \(fetchedObjects.count) \(String(describing: self)) with predicate \(predicate)") }
return fetchedObjects.first
}
}
if createIfNil {
if AwesomeData.showLogs { print("creating new instance of \(String(describing: self))") }
return newInstance(withContext: managedContext)
}
return nil
}
public static func getAsyncObject(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext, predicate: NSPredicate, createIfNil: Bool = false, successFetch: @escaping (NSManagedObject?) -> Void, failure:@escaping (()->Void)) {
listAsync(withContext: managedContext, predicate: predicate, successFetch: { (fetchedObjects) in
// if let fetchedObjects = fetchedObjects as? [NSManagedObject] {
if fetchedObjects.count > 0{
if AwesomeData.showLogs { print("fetched \(fetchedObjects.count) \(String(describing: self)) with predicate \(predicate)") }
successFetch(fetchedObjects.first)
return
}
// }
if createIfNil {
if AwesomeData.showLogs { print("creating new instance of \(String(describing: self))") }
successFetch(newInstance(withContext: managedContext))
return
}
successFetch(nil)
}) {
print("error fetching objects asyncronous from core data")
failure()
}
}
/*
* Lists all instances of the current NSManagedObject with sort property
* @param managedContext:context for wanted database | as default, will get the standard Coredata shared instance for the App
* @param property: Name of the property to sort data
* @param ascending: Sets either the sort is *true for ascending* or *false for descending*
*/
public static func list(withContext managedContext: NSManagedObjectContext = AwesomeDataAccess.sharedInstance.managedObjectContext, sortWith property:String, ascending:Bool) -> [NSManagedObject]{
let sortDescriptor = NSSortDescriptor(key:property, ascending:ascending)
return list(withContext: managedContext, sortDescriptor: sortDescriptor)
}
/*
* Sorts an NSArray with NSManagedObjects based on property
* @param array: array of NSManagedObjects
* @param property: Name of the property to sort data
* @param ascending: Sets either the sort is *true for ascending* or *false for descending*
*/
public static func sort(nsArray array:NSArray, sortWith property:String, ascending:Bool) -> [Any]{
let sortDescriptor = NSSortDescriptor(key:property, ascending:ascending)
let sortDescriptors = [sortDescriptor]
return array.sortedArray(using: sortDescriptors)
}
/*
* Sorts an Array with NSManagedObjects based on property
* @param array: array of NSManagedObjects
* @param property: Name of the property to sort data
* @param ascending: Sets either the sort is *true for ascending* or *false for descending*
*/
public static func sort(setArray array:[NSManagedObject], sortWith property:String, ascending:Bool) -> [Any]{
return sort(nsArray: array as NSArray, sortWith: property, ascending: ascending)
}
/*
* Sorts a Set with NSManagedObjects based on property
* @param set: set of NSManagedObjects
* @param property: Name of the property to sort data
* @param ascending: Sets either the sort is *true for ascending* or *false for descending*
*/
public static func sort(setSet set: Set<NSManagedObject>, sortWith property:String, ascending:Bool) -> [Any]{
var array = [NSManagedObject]()
for object in set {
array.append(object)
}
return sort(nsArray: array as NSArray, sortWith: property, ascending: ascending)
}
}
// MARK: - Json parsing
extension NSManagedObject {
public class func parseDouble(_ jsonObject: [String: AnyObject], key: String) -> NSNumber {
return NSNumber(value: AwesomeParser.doubleValue(jsonObject, key: key) as Double)
}
public class func parseInt(_ jsonObject: [String: AnyObject], key: String) -> NSNumber {
return NSNumber(value: AwesomeParser.intValue(jsonObject, key: key) as Int)
}
public class func parseBool(_ jsonObject: [String: AnyObject], key: String) -> NSNumber {
return NSNumber(value: AwesomeParser.boolValue(jsonObject, key: key) as Bool)
}
public class func parseString(_ jsonObject: [String: AnyObject], key: String) -> String {
return AwesomeParser.stringValue(jsonObject, key: key)
}
public class func parseDate(_ jsonObject: [String: AnyObject], key: String, format: String = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") -> Date? {
return AwesomeParser.dateValue(jsonObject, key: key, format: format)
}
}
|
mit
|
4165a850196307451ea9b73f2d9233ee
| 41.662116 | 280 | 0.64472 | 5.463287 | false | false | false | false |
editfmah/AeonAPI
|
Sources/UserRequestHandler.swift
|
1
|
6510
|
//
// UserRequestHandler.swift
// AeonAPI
//
// Created by Adrian Herridge on 19/06/2017.
//
//
import Foundation
import SwiftyJSON
import CryptoSwift
class UserRequestHandler {
func makeUsername(_ username: String) -> String {
let salt = settings.salt()
return (username.lowercased() + salt).sha512()
}
func makePassword(_ password: String) -> String {
let salt = settings.salt()
return (password.lowercased() + salt).sha512()
}
func HandleCreateUser(data: JSON) -> ResponseObject {
let paramUsername = data["username"].stringValue
let paramPassword = data["password"].stringValue
let validationSecret = data["secret"].stringValue
if validationSecret != settings.secret() {
let response = ResponseObject()
response.responseCode = .forbidden
return response
}
if paramUsername.characters.count < 3 || paramPassword.characters.count < 3 {
// user record already exists, return an error
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","username or password are invalid"))
return response
}
let username = makeUsername(paramUsername)
let password = makePassword(paramPassword)
let email = data["email"].string
let telno = data["telno"].string
let result = usersdb.query(sql: "SELECT NULL FROM User WHERE user_name = ?", params: [username])
if result.error == nil && result.results.count > 0 {
// user record already exists, return an error
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","user record already exists"))
return response
} else {
// this record does not exist, so create it and return the pk of the record
let newUser = User()
newUser.user_name = username
newUser.user_email = email
newUser.user_telno = telno
newUser.user_password_hash = password
if(usersdb.execute(compiledAction: newUser.Commit()).error == nil) {
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("user_id",newUser._id_),("auth_token",auth.newTokenForUser(username, user_id: newUser._id_ ,expiryMinutes: 60).token!))
if Wallet.CreateWallet(user_id: newUser._id_, name: "Default") {
return response
} else {
_ = usersdb.execute(compiledAction: newUser.Delete())
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","failed to create wallet"))
return response
}
} else {
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","failed to create user"))
return response
}
}
}
func HandleUserAuth(data: JSON) -> ResponseObject {
let paramUsername = data["username"].stringValue
let paramPassword = data["password"].stringValue
if paramUsername.characters.count < 3 || paramPassword.characters.count < 3 {
// user record already exists, return an error
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","username or password are invalid"))
return response
}
let username = makeUsername(paramUsername)
let password = makePassword(paramPassword)
let result = usersdb.query(sql: "SELECT * FROM User WHERE user_name = ? AND user_password_hash = ?", params: [username,password])
if result.error == nil && result.results.count > 0 {
// auth pass, generate a token and return it.
let u = User(result.results[0])
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("auth_token",auth.newTokenForUser(username, user_id: u._id_, expiryMinutes: 60).token!),("user_id",u._id_))
return response
} else {
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","user validation failed"))
return response
}
}
func HandleUpdateUser(data: JSON) -> ResponseObject {
let user_id = data["user_id"].stringValue
let password = makePassword(data["password"].stringValue)
let email = data["email"].string
let telno = data["telno"].string
let result = usersdb.query(sql: "SELECT * FROM User WHERE _id_ = ? LIMIT 1", params: [user_id])
if result.error == nil && result.results.count > 0 {
let updatedUser = User(result.results[0])
updatedUser.user_email = email
updatedUser.user_password_hash = password
updatedUser.user_telno = telno
if usersdb.execute(compiledAction: updatedUser.Commit()).error == nil {
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("user_id",updatedUser._id_),("auth_token",auth.newTokenForUser(updatedUser.user_name!, user_id: updatedUser._id_, expiryMinutes: 60)))
return response
} else {
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","error updating user record"))
return response
}
} else {
// user record already exists, return an error
let response = ResponseObject()
response.responseJSON = JSON(dictionaryLiteral: ("error","user record does not exist"))
return response
}
}
}
|
mit
|
1ff515cd84ccd8b82c33bcfa79ddd306
| 35.988636 | 199 | 0.546237 | 5.420483 | false | false | false | false |
Constructor-io/constructorio-client-swift
|
UserApplication/CustomViews/Cell/Nib/CustomTableViewCellOne.swift
|
1
|
1710
|
//
// CustomTableViewCellOne.swift
// UserApplication
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import UIKit
import ConstructorAutocomplete
class CustomTableViewCellOne: UITableViewCell, CIOAutocompleteCell {
@IBOutlet weak var imageViewIcon: UIImageView!
@IBOutlet weak var labelText: UILabel!
var randomImage: UIImage {
var imageNames = ["icon_clock", "icon_error_yellow", "icon_help", "icon_sign_error", "icon_star"]
let name = imageNames[Int(arc4random()) % imageNames.count]
return UIImage(named: name)!
}
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
}
func setup(result: CIOAutocompleteResult, searchTerm: String, highlighter: CIOHighlighter) {
if let group = result.group{
let groupString = NSMutableAttributedString()
groupString.append(NSAttributedString(string: " in ", attributes: highlighter.attributesProvider.defaultSubstringAttributes()))
groupString.append(NSAttributedString(string: group.displayName, attributes: highlighter.attributesProvider.highlightedSubstringAttributes()))
self.labelText.attributedText = groupString
self.imageViewIcon.image = nil
}else{
self.labelText.attributedText = highlighter.highlight(searchTerm: searchTerm, itemTitle: result.result.value)
self.imageViewIcon.image = self.randomImage
}
}
}
|
mit
|
27b5c399dc0252d759d0386607c3298a
| 33.877551 | 154 | 0.685781 | 4.91092 | false | false | false | false |
ontouchstart/swift3-playground
|
xcode8/jsonURLiOS.playground/Contents.swift
|
2
|
2792
|
//: Based on Apple blog [Working with JSON in Swift](https://developer.apple.com/swift/blog/?id=37)
import Foundation
import PlaygroundSupport
struct Restaurant {
enum Meal: String {
case breakfast, lunch, dinner
}
let name: String
let coordinates: (latitude: Double, longitude: Double)
let meals: Set<Meal>
}
enum SerializationError: Error {
case missing(String)
case invalid(String, Any)
}
extension Restaurant {
init(json: [String: Any]) throws {
// Extract name
guard let name = json["name"] as? String else {
throw SerializationError.missing("name")
}
// Extract and validate coordinates
guard let coordinatesJSON = json["coordinates"] as? [String: Double],
let latitude = coordinatesJSON["lat"],
let longitude = coordinatesJSON["lng"]
else {
throw SerializationError.missing("coordinates")
}
let coordinates = (latitude, longitude)
guard case (-90...90, -180...180) = coordinates else {
throw SerializationError.invalid("coordinates", coordinates)
}
// Extract and validate meals
guard let mealsJSON = json["meals"] as? [String] else {
throw SerializationError.missing("meals")
}
var meals: Set<Meal> = []
for string in mealsJSON {
guard let meal = Meal(rawValue: string) else {
throw SerializationError.invalid("meals", string)
}
meals.insert(meal)
}
// Initialize properties
self.name = name
self.coordinates = coordinates
self.meals = meals
}
}
let link = "https://gist.githubusercontent.com/ontouchstart/2223ccc1e29df33f9577e71279d40548/raw/a8735eee4ba061265c07bdd286f2600aae70bfce/data.json"
if let url = URL(string: link) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse , httpURLResponse.statusCode == 200,
let data = data , error == nil
else {
print("error")
return
}
DispatchQueue.main.async() {
() -> Void in
print(data)
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
print(json)
let restaurant = try Restaurant(json: json)
print(restaurant)
}
} catch let error as NSError {
print(error)
}
}
}.resume()
}
PlaygroundPage.current.needsIndefiniteExecution = true
|
mit
|
8d72bae193afd9b7085469b72af04bad
| 31.103448 | 148 | 0.566261 | 4.780822 | false | false | false | false |
AlexRamey/mbird-iOS
|
iOS Client/Models/MBPodcast.swift
|
1
|
3692
|
//
// MBPodcast.swift
// iOS Client
//
// Created by Jonathan Witten on 12/10/17.
// Copyright © 2017 Mockingbird. All rights reserved.
//
import Foundation
import UIKit
struct PodcastDTO: Codable {
let author: String?
let duration: String?
let guid: String?
let image: String?
let keywords: String?
let summary: String?
let pubDate: String?
let title: String?
}
struct Podcast: Codable {
let author: String?
let duration: String?
let guid: String?
let image: String
let keywords: String?
let summary: String?
let pubDate: Date
let title: String?
let feed: PodcastStream
}
public enum PodcastStream: String, Codable {
case pz = "https://pzspodcast.fireside.fm/rss"
case mockingCast = "https://themockingcast.fireside.fm/rss"
case mockingPulpit = "https://themockingpulpit.fireside.fm/rss"
case talkingbird = "https://talkingbird.fireside.fm/rss"
case sameOldSong = "https://thesameoldsong.fireside.fm/rss"
case brothersZahl = "https://thebrotherszahl.fireside.fm/rss"
var imageName: String {
switch self {
case .pz: return "pzcast"
case .mockingPulpit: return "mockingpulpit"
case .mockingCast: return "mockingcast"
case .talkingbird: return "talkingbird"
case .sameOldSong: return "sameoldsong"
case .brothersZahl: return "brotherszahl"
}
}
var title: String {
switch self {
case .pz: return "PZ's Podcast"
case .mockingCast: return "The Mockingcast"
case .mockingPulpit: return "The Mockingpulpit"
case .talkingbird: return "Talkingbird"
case .sameOldSong: return "Same Old Song"
case .brothersZahl: return "The Brothers Zahl"
}
}
var shortTitle: String {
switch self {
case .pz: return "PZ's Podcast"
case .mockingCast: return "Mockingcast"
case .mockingPulpit: return "Mockingpulpit"
case .talkingbird: return "Talkingbird"
case .sameOldSong: return "Same Old Song"
case .brothersZahl: return "Brothers Zahl"
}
}
var description: String {
switch self {
case .pz:
return "Grace-based impressions and outré correlations from the author of Grace in Practice, Paul F.M. Zahl."
case .mockingCast:
return "A bi-weekly roundtable on culture, faith and grace, co-hosted by RJ Heijmen, Sarah Condon and David Zahl."
case .mockingPulpit:
return "Sermons from Mockingbird contributors, singing that “same song” of God’s grace in different keys, week after week."
case .talkingbird:
return "Your destination for talks given at Mbird events, both present and past. Subjects run the gamut from religion and theology to psychology and literature to pop culture and relationships and everything in between."
case .sameOldSong:
return "A weekly discussion of the texts assigned for Sunday in the lectionary, hosted by Jacob Smith and Aaron Zimmerman. As always, grace abounds. Not just for preachers!"
case .brothersZahl:
return "A long overdue collaboration between John, David and Simeon Zahl, three siblings engaged in \"the God business\"--one as a writer, one as a professor, one as a priest. They tackle some big subjects, in hopes of sketching an overarching picture of grace and everyday life (and making some decent jokes in the process)"
}
}
var dateFormat: String {
// this used to vary per podcast before they were all hosted on Fireside
return "E, d MMM yyyy HH:mm:ss Z"
}
}
|
mit
|
9f3cbf6bb558a7204eef1194f3d123d5
| 36.979381 | 337 | 0.664495 | 3.881981 | false | false | false | false |
hejunbinlan/GRDB.swift
|
GRDB/Migrations/DatabaseMigrator.swift
|
1
|
3843
|
/**
A DatabaseMigrator registers and applies database migrations.
Migrations are named blocks of SQL statements that are guaranteed to be applied
in order, once and only once.
When a user upgrades your application, only non-applied migration are run.
Usage:
var migrator = DatabaseMigrator()
// v1.0 database
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"creationDate TEXT, " +
"name TEXT NOT NULL" +
")")
}
migrator.registerMigration("createBooks") { db in
try db.execute(
"CREATE TABLE books (" +
"uuid TEXT PRIMARY KEY, " +
"ownerID INTEGER NOT NULL " +
" REFERENCES persons(id) " +
" ON DELETE CASCADE ON UPDATE CASCADE, " +
"title TEXT NOT NULL" +
")")
}
// v2.0 database
migrator.registerMigration("AddAgeToPersons") { db in
try db.execute("ALTER TABLE persons ADD COLUMN age INT")
}
try migrator.migrate(dbQueue)
*/
public struct DatabaseMigrator {
/// A new migrator.
public init() {
}
/**
Registers a migration.
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"creationDate TEXT, " +
"name TEXT NOT NULL" +
")")
}
- parameter identifier: The migration identifier. It must be unique.
- parameter block: The migration block that performs SQL statements.
*/
public mutating func registerMigration(identifier: String, _ block: (db: Database) throws -> Void) {
guard migrations.map({ $0.identifier }).indexOf(identifier) == nil else {
fatalError("Already registered migration: \"\(identifier)\"")
}
migrations.append(Migration(identifier: identifier, block: block))
}
/**
Iterate migrations in the same order as they were registered. If a migration
has not yet been applied, its block is executed in a transaction.
- parameter dbQueue: The Database Queue where migrations should apply.
- throws: An eventual error thrown by the registered migration blocks.
*/
public func migrate(dbQueue: DatabaseQueue) throws {
try setupMigrations(dbQueue)
try runMigrations(dbQueue)
}
// MARK: - Non public
private struct Migration {
let identifier: String
let block: (db: Database) throws -> Void
}
private var migrations: [Migration] = []
private func setupMigrations(dbQueue: DatabaseQueue) throws {
try dbQueue.inDatabase { db in
try db.execute(
"CREATE TABLE IF NOT EXISTS grdb_migrations (" +
"identifier VARCHAR(128) PRIMARY KEY NOT NULL," +
"position INT" +
")")
}
}
private func runMigrations(dbQueue: DatabaseQueue) throws {
let appliedMigrationIdentifiers = dbQueue.inDatabase { db in
String.fetch(db, "SELECT identifier FROM grdb_migrations").map { $0! }
}
for (position, migration) in self.migrations.enumerate() {
if appliedMigrationIdentifiers.indexOf(migration.identifier) == nil {
try dbQueue.inTransaction { db in
try migration.block(db: db)
try db.execute("INSERT INTO grdb_migrations (position, identifier) VALUES (?, ?)", arguments: [position, migration.identifier])
return .Commit
}
}
}
}
}
|
mit
|
55658d7dc524060bdecac545a443627c
| 31.576271 | 147 | 0.575592 | 5.043307 | false | false | false | false |
audrl1010/EasyMakePhotoPicker
|
Example/EasyMakePhotoPicker/KaKaoPhotoCell.swift
|
1
|
4578
|
//
// KaKaoPhotoCell.swift
// EasyMakePhotoPicker
//
// Created by myung gi son on 2017. 7. 5..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import UIKit
import EasyMakePhotoPicker
import PhotosUI
import RxSwift
class KaKaoPhotoCell: BaseCollectionViewCell, PhotoCellable {
// MARK: - Constant
struct Constant {
static let selectedViewBorderWidth = CGFloat(2)
}
struct Color {
static let selectedViewBorderColor = UIColor(
red: 255/255,
green: 255/255,
blue: 0/255,
alpha: 1.0)
static let selectedViewBGColor = UIColor(
red: 0,
green: 0,
blue: 0,
alpha: 0.6)
}
struct Metric {
static let orderLabelWidth = CGFloat(30)
static let orderLabelHeight = CGFloat(30)
static let orderLabelRight = CGFloat(-10)
static let orderLabelTop = CGFloat(10)
static let checkImageViewWidth = CGFloat(30)
static let checkImageViewHeight = CGFloat(30)
static let checkImageViewRight = CGFloat(-10)
static let checkImageViewTop = CGFloat(10)
}
// MARK: - Properties
var checkView = CheckImageView().then {
$0.isHidden = true
}
var selectedView = UIView().then {
$0.layer.borderWidth = Constant.selectedViewBorderWidth
$0.layer.borderColor = Color.selectedViewBorderColor.cgColor
$0.backgroundColor = Color.selectedViewBGColor
$0.isHidden = true
}
var orderLabel = NumberLabel().then {
$0.isHidden = true
}
var imageView = UIImageView().then {
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
var disposeBag: DisposeBag = DisposeBag()
var viewModel: PhotoCellViewModel? {
didSet {
guard let viewModel = viewModel else { return }
bind(viewModel: viewModel)
}
}
// MARK: - Life Cycle
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
viewModel = nil
imageView.image = nil
orderLabel.label.text = nil
orderLabel.isHidden = true
selectedView.isHidden = true
}
override func addSubviews() {
addSubview(imageView)
addSubview(selectedView)
addSubview(orderLabel)
addSubview(checkView)
}
override func setupConstraints() {
imageView
.fs_leftAnchor(equalTo: leftAnchor)
.fs_topAnchor(equalTo: topAnchor)
.fs_rightAnchor(equalTo: rightAnchor)
.fs_bottomAnchor(equalTo: bottomAnchor)
.fs_endSetup()
selectedView
.fs_leftAnchor(equalTo: leftAnchor)
.fs_topAnchor(equalTo: topAnchor)
.fs_rightAnchor(equalTo: rightAnchor)
.fs_bottomAnchor(equalTo: bottomAnchor)
.fs_endSetup()
orderLabel
.fs_widthAnchor(
equalToConstant: Metric.orderLabelWidth)
.fs_heightAnchor(
equalToConstant: Metric.orderLabelHeight)
.fs_rightAnchor(
equalTo: rightAnchor,
constant: Metric.orderLabelRight)
.fs_topAnchor(
equalTo: topAnchor,
constant: Metric.orderLabelTop)
.fs_endSetup()
checkView
.fs_widthAnchor(
equalToConstant: Metric.checkImageViewWidth)
.fs_heightAnchor(
equalToConstant: Metric.checkImageViewHeight)
.fs_rightAnchor(
equalTo: rightAnchor,
constant: Metric.checkImageViewRight)
.fs_topAnchor(
equalTo: topAnchor,
constant: Metric.checkImageViewTop)
.fs_endSetup()
}
// MARK: - Bind
func bind(viewModel: PhotoCellViewModel) {
viewModel.isSelect
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self, weak viewModel] isSelect in
guard let `self` = self,
let `viewModel` = viewModel else { return }
self.selectedView.isHidden = !isSelect
if viewModel.configure.allowsMultipleSelection {
self.orderLabel.isHidden = !isSelect
self.checkView.isHidden = isSelect
}
else {
self.orderLabel.isHidden = true
self.checkView.isHidden = true
}
})
.disposed(by: disposeBag)
viewModel.selectedOrder
.subscribe(onNext: { [weak self] selectedOrder in
guard let `self` = self else { return }
self.orderLabel.number = selectedOrder
})
.disposed(by: disposeBag)
viewModel.image.asObservable()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] image in
guard let `self` = self else { return }
self.imageView.image = image
})
.disposed(by: disposeBag)
}
}
|
mit
|
1c122ef9ea88b6b20db0c0991da25317
| 22.95288 | 66 | 0.645464 | 4.516288 | false | false | false | false |
juliangrosshauser/ToDo
|
ToDo/Sources/Classes/Application/AppDelegate.swift
|
1
|
1276
|
//
// AppDelegate.swift
// ToDo
//
// Created by Julian Grosshauser on 16/07/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
lazy var window: UIWindow? = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.backgroundColor = .whiteColor()
return window
}()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let listTableController = ListTableController()
let todoTableController = TodoTableController()
listTableController.delegate = todoTableController
let masterViewController = UINavigationController(rootViewController: listTableController)
let detailViewController = UINavigationController(rootViewController: todoTableController)
let splitViewController = UISplitViewController()
splitViewController.viewControllers = [masterViewController, detailViewController]
splitViewController.delegate = listTableController
window?.rootViewController = splitViewController
window?.makeKeyAndVisible()
return true
}
}
|
mit
|
61cd6caec21663d93dbecaac5f26b977
| 32.552632 | 127 | 0.721569 | 6.343284 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io
|
RedBus/RedBus/Controller/MyBookingsViewController.swift
|
1
|
4104
|
//
// MyBookingsViewController.swift
// RedBus
//
// Created by Anirudh Das on 8/22/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import UIKit
class MyBookingsViewController: BaseViewController {
@IBOutlet weak var tblViewBookings: UITableView!
var alertController: UIAlertController?
var dataController = appDelegate.dataController
var busesDataSource: [Bus] = [] {
didSet {
tblViewBookings.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
tblViewBookings.delegate = self
tblViewBookings.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fetchBuses()
}
@objc func fetchBuses() {
busesDataSource = dataController.getAllBookings()
}
}
extension MyBookingsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return busesDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let bookingCell = tableView.dequeueReusableCell(withIdentifier: Constants.bookingCell, for: indexPath) as? BookingTableViewCell else {
return UITableViewCell()
}
bookingCell.selectionStyle = .none
bookingCell.configureCell(busDetail: busesDataSource[indexPath.row])
return bookingCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let bookingCell = tableView.cellForRow(at: indexPath) as? BookingTableViewCell, let bus = bookingCell.bus else {
return
}
showUpdateRatingAlert(bus: bus)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
_ = Utility.showAlertMessage(title: Constants.cancelAlertTitle, message: Constants.cancelAlertMessage, viewController: self, okButtonTitle: Constants.cancelAlertOK, okHandler: { [weak self] _ in
guard let weakSelf = self else { return }
guard let bookingCell = tableView.cellForRow(at: indexPath) as? BookingTableViewCell, let bus = bookingCell.bus else {
return
}
weakSelf.dataController.deleteBooking(bus: bus)
weakSelf.fetchBuses()
weakSelf.view.makeToast(Constants.cancelSuccessful, duration: 3.0, position: .bottom)
}, cancelButtonTitle: Constants.cancelAlertCancel, cancelHandler: { [weak self] _ in
guard let weakSelf = self else { return }
weakSelf.tblViewBookings.reloadData()
})
}
}
func showUpdateRatingAlert(bus: Bus) {
let ratingTxtField = { (textField: UITextField) in
textField.placeholder = Constants.updateAlertPlaceholder
}
self.alertController = Utility.showAlertMessage(title: Constants.updateAlertTitle, message: Constants.updateAlertMessage, viewController: self, cancelButtonTitle: Constants.updateAlertCancel, textField: ratingTxtField)
let action = UIAlertAction(title: Constants.updateAlertOK, style: UIAlertActionStyle.default, handler: { [weak self] (alertController) -> Void in
guard let weakSelf = self else { return }
guard let ratingStr = weakSelf.alertController?.textFields?.first?.text, let rating = Double(ratingStr), rating >= 0, rating <= 5 else {
weakSelf.view.makeToast(Constants.invalidRatingInput, duration: 3.0, position: .bottom)
return
}
weakSelf.dataController.updateBooking(bus: bus, rating: rating)
weakSelf.fetchBuses()
weakSelf.view.makeToast(Constants.ratingUpdateSuccess, duration: 3.0, position: .bottom)
})
alertController?.addAction(action)
}
}
|
apache-2.0
|
b6f292f58e59519cc4610fc990b136ac
| 41.298969 | 226 | 0.663904 | 5.167506 | false | false | false | false |
richardpiazza/SOSwift
|
Sources/SOSwift/Question.swift
|
1
|
2503
|
import Foundation
/// A specific question - e.g. from a user seeking answers online, or collected in
/// a Frequently Asked Questions (FAQ) document.
public class Question: CreativeWork {
/// The answer that has been accepted as best, typically on a
/// Question/Answer site. Sites vary in their selection mechanisms, e.g.
/// drawing on community opinion and/or the view of the Question author.
public var acceptedAnswer: Answer?
/// The number of answers this question has received.
public var answerCount: Int?
/// The number of downvotes this question, answer or comment has received
/// from the community.
public var downvoteCount: Int?
/// An answer (possibly one of several, possibly incorrect) to a Question, e.g.
/// on a Question/Answer site.
public var suggestedAnswer: Answer?
/// The number of upvotes this question, answer or comment has received
/// from the community.
public var upvoteCount: Int?
internal enum QuestionCodingKeys: String, CodingKey {
case acceptedAnswer
case answerCount
case downvoteCount
case suggestedAnswer
case upvoteCount
}
public override init() {
super.init()
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: QuestionCodingKeys.self)
acceptedAnswer = try container.decodeIfPresent(Answer.self, forKey: .acceptedAnswer)
answerCount = try container.decodeIfPresent(Int.self, forKey: .answerCount)
downvoteCount = try container.decodeIfPresent(Int.self, forKey: .downvoteCount)
suggestedAnswer = try container.decodeIfPresent(Answer.self, forKey: .suggestedAnswer)
upvoteCount = try container.decodeIfPresent(Int.self, forKey: .upvoteCount)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: QuestionCodingKeys.self)
try container.encodeIfPresent(acceptedAnswer, forKey: .acceptedAnswer)
try container.encodeIfPresent(answerCount, forKey: .answerCount)
try container.encodeIfPresent(downvoteCount, forKey: .downvoteCount)
try container.encodeIfPresent(suggestedAnswer, forKey: .suggestedAnswer)
try container.encodeIfPresent(upvoteCount, forKey: .upvoteCount)
try super.encode(to: encoder)
}
}
|
mit
|
abad51fe0ea50db94ad65838bf1c3428
| 39.370968 | 94 | 0.69157 | 4.888672 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/Root/Models/ZSUserDetail.swift
|
1
|
2129
|
//
// ZSUserDetail.swift
// zhuishushenqi
//
// Created by yung on 2018/10/20.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
import HandyJSON
class ZSUserDetail: HandyJSON {
var _id:String = ""
var nickname:String = ""
var avatar:String = ""
var exp:CGFloat = 25
var rank:CLongLong = 0
var lv:Int = 0
var vipLv:Int = 0
var mobile:CLongLong = 0
var type:String = ""
var gender:String = ""
var genderChanged = false
var today_tasks:ZSUserDetailTodayTask?
var this_week_tasks:ZSUserDetailThisWeekTask?
var post_count:ZSUserDetailPostCount?
var book_list_count:ZSUserDetailTodayTask?
var lastDay = 0
var ok = true
required init() {}
}
class ZSUserDetailTodayTask: HandyJSON {
var launch = false
var post = false
var comment = false
var vote = false
var share = false
var share_book = false
var flopen = false
required init() {}
}
class ZSUserDetailThisWeekTask: HandyJSON {
var rate = false
required init() {
}
}
class ZSUserDetailPostCount: HandyJSON {
var posted = 0
var collected = 0
required init() {
}
}
class ZSUserDetailBookListCount: HandyJSON {
var posted = 0
var collected = 0
required init() {
}
}
//{
// "_id": "5bc9c8706900af100060ea21",
// "nickname": "神偷520",
// "avatar": "/icon/avatar.png",
// "exp": 25,
// "rank": 0.003558718861209953,
// "lv": 2,
// "vipLv": 0,
// "vipExp": 0,
// "mobile": 0,
// "type": "normal",
// "gender": "female",
// "genderChanged": false,
// "today_tasks": {
// "launch": false,
// "post": false,
// "comment": true,
// "vote": true,
// "share": false,
// "share_book": false,
// "fl-open": true
// },
// "this_week_tasks": {
// "rate": true
// },
// "post_count": {
// "posted": 0,
// "collected": 0
// },
// "book_list_count": {
// "posted": 0,
// "collected": 0
// },
// "lastDay": 0,
// "ok": true
//}
|
mit
|
866198109a1b9010067f615262e5c9e4
| 18.831776 | 49 | 0.542413 | 3.28483 | false | false | false | false |
e-Sixt/Swible
|
Example/Tests/DesignableSegmentedControlTests.swift
|
1
|
1901
|
//
// DesignableSegmentedControlTests.swift
// Swible
//
// Created by franz busch on 26/04/2017.
//
import Quick
import Nimble
import Swible
class TestDesignableSegmentedControl: DesignableSegmentedControl {
var didSetup = false
var didApplyStyle = false
override func setup() {
super.setup()
didSetup = true
}
override func applyStyling() {
super.applyStyling()
didApplyStyle = true
}
}
class DesignableSegmentedControlTests: QuickSpec {
override func spec() {
describe("a DesignableTextView") {
context("created programmatically") {
it("is setup") {
let view = TestDesignableSegmentedControl(frame: .zero)
expect(view.didSetup).to(beTrue())
}
it("is setup") {
let view = TestDesignableSegmentedControl(items: nil)
expect(view.didSetup).to(beTrue())
}
it("is styled") {
let view = TestDesignableSegmentedControl(frame: .zero)
expect(view.didApplyStyle).to(beTrue())
}
it("is styled") {
let view = TestDesignableSegmentedControl(items: nil)
expect(view.didApplyStyle).to(beTrue())
}
}
context("created from storyboard") {
it("is setup") {
let view = TestViewController.createFromStoryboard()?.testDesignableSegmentedControl
expect(view?.didSetup).to(beTrue())
}
it("is styled") {
let view = TestViewController.createFromStoryboard()?.testDesignableSegmentedControl
expect(view?.didApplyStyle).to(beTrue())
}
}
}
}
}
|
mit
|
5b6ed17805734b77bd81c519dfe0a9ce
| 25.402778 | 104 | 0.529721 | 5.370056 | false | true | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode
|
精通Swift设计模式/Chapter 23/SportsStore/SportsStore/ViewController.swift
|
1
|
5911
|
import UIKit
class ProductTableCell : UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var stockStepper: UIStepper!
@IBOutlet weak var stockField: UITextField!
var product:Product?;
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "handleStockLevelUpdate:", name: "stockUpdate", object: nil);
}
func handleStockLevelUpdate(notification:NSNotification) {
if let updatedProduct = notification.object as? Product {
if updatedProduct.name == self.product?.name {
stockStepper.value = Double(updatedProduct.stockLevel);
stockField.text = String(updatedProduct.stockLevel);
}
}
}
}
var handler = { (p:Product) in
println("Change: \(p.name) \(p.stockLevel) items in stock");
};
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var totalStockLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var productStore = ProductDataStore();
override func viewDidLoad() {
super.viewDidLoad();
displayStockTotal();
let bridge = EventBridge(callback: updateStockLevel);
productStore.callback = bridge.inputCallback;
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
if (event.subtype == UIEventSubtype.MotionShake) {
println("Shake motion detected");
undoManager?.undo();
}
}
func updateStockLevel(name:String, level:Int) {
for cell in self.tableView.visibleCells() {
if let pcell = cell as? ProductTableCell {
if pcell.product?.name == name {
pcell.stockStepper.value = Double(level);
pcell.stockField.text = String(level);
}
}
}
self.displayStockTotal();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return productStore.products.count;
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let product = productStore.products[indexPath.row];
let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell")
as ProductTableCell;
cell.product = productStore.products[indexPath.row];
cell.nameLabel.text = product.name;
cell.descriptionLabel.text = product.productDescription;
cell.stockStepper.value = Double(product.stockLevel);
cell.stockField.text = String(product.stockLevel);
CellFormatter.createChain().formatCell(cell);
return cell;
}
@IBAction func stockLevelDidChange(sender: AnyObject) {
if var currentCell = sender as? UIView {
while (true) {
currentCell = currentCell.superview!;
if let cell = currentCell as? ProductTableCell {
if let product = cell.product? {
// let dict = NSDictionary(objects: [product.stockLevel],
// forKeys: [product.name]);
undoManager?.registerUndoWithTarget(self,
selector: "resetState",
object: nil);
if let stepper = sender as? UIStepper {
product.stockLevel = Int(stepper.value);
} else if let textfield = sender as? UITextField {
if let newValue = textfield.text.toInt()? {
product.stockLevel = newValue;
}
}
// cell.stockStepper.value = Double(product.stockLevel);
// cell.stockField.text = String(product.stockLevel);
productLogger.logItem(product);
StockServerFactory.getStockServer()
.setStockLevel(product.name, stockLevel: product.stockLevel);
}
break;
}
}
displayStockTotal();
}
}
func resetState() {
self.productStore.resetState();
}
// func undoStockLevel(data:[String:Int]) {
// let productName = data.keys.first;
// if (productName != nil) {
// let stockLevel = data[productName!];
// if (stockLevel != nil) {
//
// for nproduct in productStore.products {
// if nproduct.name == productName! {
// nproduct.stockLevel = stockLevel!;
// }
// }
//
// updateStockLevel(productName!, level: stockLevel!);
// }
// }
// }
func displayStockTotal() {
let finalTotals:(Int, Double) = productStore.products.reduce((0, 0.0),
{(totals, product) -> (Int, Double) in
return (
totals.0 + product.stockLevel,
totals.1 + product.stockValue
);
});
let formatted = StockTotalFacade.formatCurrencyAmount(finalTotals.1,
currency: StockTotalFacade.Currency.EUR);
totalStockLabel.text = "\(finalTotals.0) Products in Stock. "
+ "Total Value: \(formatted!)";
}
}
|
mit
|
c4ef8c15a3623aa64969d4cf5fb53715
| 35.94375 | 89 | 0.539672 | 5.272971 | false | false | false | false |
EricHein/Swift3.0Practice2016
|
01.Applicatons/MyFavouriteNumber-PermanentDataStorage/MyFavouriteNumber-PermanentDataStorage/ViewController.swift
|
1
|
2715
|
//
// ViewController.swift
// MyFavouriteNumber-PermanentDataStorage
//
// Created by Eric H on 14/10/2016.
// Copyright © 2016 FabledRealm. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var saveButton: UIButton!
@IBOutlet var favouriteNumberLabel: UILabel!
@IBOutlet var numberEntryTF: UITextField!
let favouriteNumber = "favouriteNumber"
let defaultNumber = 0
var enteredNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
let toolbarDone = UIToolbar.init()
toolbarDone.sizeToFit()
let barBtnDone = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.done,
target: self, action: #selector(ViewController.doneButtonAction))
let flexible = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
toolbarDone.items = [flexible,barBtnDone]
numberEntryTF.inputAccessoryView = toolbarDone
saveButton.layer.cornerRadius = 5
saveButton.layer.borderWidth = 1
saveButton.layer.borderColor = UIColor.clear.cgColor
saveButton.layer.shadowColor = UIColor.black.cgColor
saveButton.layer.shadowOffset = CGSize(width: 3.0, height: 3.0)
saveButton.layer.shadowOpacity = 0.5
saveButton.layer.shadowRadius = 5
let favouriteNumberObject = UserDefaults.standard.object(forKey: favouriteNumber)
if let favNum = favouriteNumberObject as? Int{
favouriteNumberLabel.text = "Your Favourite number is: \(favNum)"
print(favNum)
}else{
favouriteNumberLabel.text = " "
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func doneButtonAction(){
numberEntryTF.resignFirstResponder()
}
@IBAction func numberEntryTFDidEnd(_ sender: UITextField) {
guard let TFTextData = sender.text, let value1 = Int(TFTextData) else {
enteredNumber = 0
return
}
enteredNumber = value1
}
@IBAction func saveButtonTapped(_ sender: AnyObject) {
UserDefaults.standard.set(enteredNumber, forKey: favouriteNumber)
let favouriteNumberObject = UserDefaults.standard.object(forKey: favouriteNumber)
if let favNum = favouriteNumberObject as? Int{
favouriteNumberLabel.text = "Your Favourite number is: \(favNum)"
print(favNum)
}
}
}
|
gpl-3.0
|
7cf590b526ee67baec9512bb5486fb4f
| 28.824176 | 128 | 0.628592 | 5.269903 | false | false | false | false |
dpricha89/DrApp
|
Source/TableCells/SlideshowCell.swift
|
1
|
1230
|
//
// SlideshowCell.swift
// Venga
//
// Created by David Richards on 7/22/17.
// Copyright © 2017 David Richards. All rights reserved.
//
import UIKit
import SnapKit
import ImageSlideshow
open class SlideshowCell: UITableViewCell {
let slideshow = ImageSlideshow()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Make the select color none
self.selectionStyle = .none
//self.backgroundColor = .clear
self.slideshow.zoomEnabled = true
self.slideshow.pageControlPosition = .insideScrollView
self.slideshow.slideshowInterval = 5
// image view and make it the same size at the cell
self.contentView.addSubview(self.slideshow)
self.slideshow.snp.makeConstraints { (make) -> Void in
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.top.equalTo(self.contentView)
make.bottom.equalTo(self.contentView)
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
efebf53b47dbd7b9aeb226a86608f1ee
| 28.97561 | 81 | 0.656631 | 4.620301 | false | false | false | false |
ajsnow/Shear
|
Shear/AllElementsCollection.swift
|
1
|
4044
|
// Copyright 2016 The Shear Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
import Foundation
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
/// AllElementsCollection is a collection
struct AllElementsCollection<A: TensorProtocol>: Collection, BidirectionalCollection, RandomAccessCollection {
let array: A
let stride: [Int]
let count: Int
init(array: A) {
self.array = array
stride = calculateStride(array.shape)
count = array.shape.isEmpty ? 1 : array.shape.reduce(*)
}
public func index(after i: Int) -> Int {
return i + 1
}
func index(before i: Int) -> Int {
return i - 1
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return count
}
subscript(_ position: Int) -> A.Element {
return array[linear: position]
}
}
/// BoundedAccumulator is a generalization of binary addition to cover non-binary, non-uniform-capacity digits.
/// E.g.
/// var a = BoundedAccumulator([4, 2, 5], onOverflow: .Ignore)
/// # a.current == [0, 0, 0]
/// a.inc() # a.current == [1, 0, 0]
/// a.add(10) # a.current == [3, 0, 1]
///
/// We use it to convert linear indices into their cartesian equivilants.
/// (N.B. this requires setting the bounds to the reversed shape & reversing the output since our mapping is row-major.)
struct BoundedAccumulator {
enum OverflowBehavior {
case `nil`
case ignore
case fatalError
}
fileprivate let bounds: [Int]
fileprivate(set) var current: [Int]?
fileprivate let onOverflow: OverflowBehavior
init(bounds: [Int], onOverflow: OverflowBehavior) {
self.bounds = bounds
self.current = [Int](repeating: 0, count: bounds.count)
self.onOverflow = onOverflow
}
mutating func add(_ amount: Int, position pos: Int = 0) {
guard pos < bounds.count else {
switch onOverflow {
case .nil: current = nil; fallthrough
case .ignore: return
case .fatalError: fatalError("overflow")
}
}
guard var curValue = current?[pos] else { return }
curValue += amount
let bound = bounds[pos]
let nextIncrement = curValue / bound
curValue %= bound
current?[pos] = curValue
if nextIncrement > 0 {
self.add(nextIncrement, position: pos + 1)
}
}
mutating func inc() {
add(1, position: 0)
}
}
// We reverse the shape so that we can reverse the BoundedAccumulator's output.
// We reverse that because we need row major order, which means incrementing the rows (indices.first) last.
func makeRowMajorIndexGenerator(_ shape: [Int]) -> AnyIterator<[Int]> {
var accRev = BoundedAccumulator(bounds: shape.reversed(), onOverflow: .nil)
return AnyIterator { () -> [Int]? in
let elementRev = accRev.current
accRev.inc()
return elementRev?.reversed()
}
}
func makeColumnMajorIndexGenerator(_ shape: [Int]) -> AnyIterator<[Int]> {
var accRev = BoundedAccumulator(bounds: shape, onOverflow: .nil)
return AnyIterator { () -> [Int]? in
let elementRev = accRev.current
accRev.inc()
return elementRev
}
}
|
mit
|
1a2679c2ad362f58cf064f9140c804c7
| 28.955556 | 120 | 0.615727 | 4.080727 | false | false | false | false |
J1aDong/GoodBooks
|
GoodBooks/BookTabBar.swift
|
1
|
2079
|
//
// BookTabBar.swift
// GoodBooks
//
// Created by J1aDong on 2017/2/3.
// Copyright © 2017年 J1aDong. All rights reserved.
//
import UIKit
protocol BookTabBarDelegate {
func comment()
func commentController()
func likeBook(_ btn:UIButton)
func shareAction()
}
class BookTabBar: UIView {
var delegate:BookTabBarDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
let imageName = ["Pen 4","chat 3","heart","box outgoing"]
for i in 0..<4{
let btn = UIButton(frame: CGRect(x: CGFloat(i)*frame.size.width/4, y: 0, width: frame.size.width/4, height: frame.size.height))
btn.setImage(UIImage(named: imageName[i]), for: .normal)
self.addSubview(btn)
btn.tag = i
btn.addTarget(self, action: #selector(bookTabbarAction), for: .touchUpInside)
}
}
func bookTabbarAction(_ btn:UIButton){
switch btn.tag {
case 0:
delegate?.comment()
break
case 1:
delegate?.commentController()
break
case 2:
delegate?.likeBook(btn)
break
case 3:
delegate?.shareAction()
break
default:
break
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(0.5)
context?.setStrokeColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1)
for i in 0..<4{
context?.move(to: CGPoint(x: CGFloat(i)*rect.size.width/4, y: rect.size.height*0.1))
context?.addLine(to: CGPoint(x: CGFloat(i)*rect.size.width/4, y: rect.size.height*0.9))
}
context?.move(to: CGPoint(x: 8, y: 0))
context?.addLine(to: CGPoint(x: rect.size.width - 8, y: 0))
context?.strokePath()
}
}
|
mit
|
fd5e8208f249fdcc5076a7a1a7807f3a
| 27.438356 | 139 | 0.567919 | 3.916981 | false | false | false | false |
Aadeshp/AsyncKit
|
AsyncKit/Classes/Task.swift
|
1
|
13591
|
//
// AsyncKit
// Task.swift
//
// Copyright (c) 2016 Aadesh Patel. All rights reserved.
//
//
import Foundation
/**
Builds and returns a Task object from the block provided
- parameter block: Closure to execute asynchronously
- returns: Task object with the same type as the result of the block parameter
*/
public func task<T>(block: () throws -> T) -> Task<T> {
let manager = TaskManager<T>()
let executor = Executor(type: .Async)
executor.execute {
do {
let ret = try block()
manager.complete(ret)
} catch {
manager.completeWithError(error)
}
}
return manager.task
}
/// Simple wrapper class of a task's result
public class TaskResultWrapper<T> {
private var result: T!
public init(result: T) {
self.result = result
}
}
/// Generic result of a Task object
/// - Success
/// - Failure with NSError
/// - Failure with NSException
/// - Canceled
public enum TaskResult<T> {
/// Task completed successfully
case Success(TaskResultWrapper<T>)
/// Task failed with an error
case FailWithError(NSError)
/// Task failed with an error type
case FailWithErrorType(ErrorType)
/// Task failed with an exception
case FailWithException(NSException)
/// Task was canceled
case Cancel
public var isSuccess: Bool {
get {
switch(self) {
case .Success:
return true
default:
return false
}
}
}
public var isFail: Bool {
get {
switch(self) {
case .FailWithError:
return true
case .FailWithErrorType:
return true
case .FailWithException:
return true
default:
return false
}
}
}
public var isCancel: Bool {
get {
switch(self) {
case .Cancel:
return true
default:
return false
}
}
}
public var result: T! {
get {
switch(self) {
case let .Success(r):
return r.result
default:
return nil
}
}
}
public var error: NSError! {
get {
switch(self) {
case let .FailWithError(e):
return e
default:
return nil
}
}
}
public var errorType: ErrorType! {
get {
switch(self) {
case let .FailWithErrorType(e):
return e
default:
return nil
}
}
}
public var exception: NSException! {
get {
switch(self) {
case let .FailWithException(e):
return e
default:
return nil
}
}
}
}
public class Task<T> {
public var result: TaskResult<T>!
private var callbackQueue: TaskQueue<((TaskResult<T>) -> Void)>?
private var callbacks: [(TaskResult<T>) -> Void]!
//private var errorBlock: ((NSError) -> Void)!
public init() {
self.callbacks = []
}
public func completeWithResult(result: TaskResult<T>) {
self.completeWithBlock({ () -> TaskResult<T> in
return result
})
}
private func completeWithBlock(block: (() -> TaskResult<T>)) {
synchronized(self) {
if (self.result != nil) {
return
}
self.result = block()
for callback in self.callbacks {
callback(self.result)
}
}
}
/**
Closure to execute if the task is completed successfully
- parameter executorType: Queue to run the block in
- parameter block: Task returning closure that executes within the queue determined by the executorType
parameter, only if the task is completed successfully
- returns: Task object of the result of the closure provided
*/
public func then<K>(executorType: ExecutorType = ExecutorType.Current, _ block: ((T) -> Task<K>)) -> Task<K> {
let manager = TaskManager<K>()
self.then(executorType) { (ret: T) in
let nextTask = block(ret)
nextTask.then { ret2 in
manager.complete(ret2)
}.error { (error: NSError) in
manager.completeWithError(error)
}.error { (error: ErrorType) in
manager.completeWithError(error)
}.error { (ex: NSException) in
manager.completeWithException(ex)
}
}
return manager.task
}
/**
Closure to execute if the task is completed successfully
- parameter executorType: Queue to run the block in
- parameter block: Closure that executes within the queue determined by the executorType parameter,
only if the task is completed successfully
- returns: Task object of the result of the closure provided
*/
public func then<K>(executorType: ExecutorType = ExecutorType.Current, _ block: ((T) -> K)) -> Task<K> {
let executor: Executor = Executor(type: executorType)
return self.thenWithResultBlock(executor) { (t: T) -> TaskResult<K> in
return TaskResult<K>.Success(TaskResultWrapper(result: block(t)))
}
}
private func thenWithResultBlock<K>(executor: Executor, _ block: (T) -> TaskResult<K>) -> Task<K> {
return self.taskForBlock(executor) { (result: TaskResult<T>) -> TaskResult<K> in
switch(result) {
case .Success:
return block(result.result)
case .FailWithError:
return .FailWithError(result.error)
case .FailWithErrorType:
return .FailWithErrorType(result.errorType)
case .FailWithException:
return .FailWithException(result.exception)
case .Cancel:
return .Cancel
}
}
}
/**
Closure to execute if the task fails with an error of type NSError
- parameter block: Closure that executes only if the task fails with an error of type NSError
- returns: Self Task object
*/
public func error(block: (NSError) -> Void) -> Task<T> {
self.queueTaskCallback { (result: TaskResult<T>) -> Void in
if (result.error != nil) {
block(result.error)
}
}
return self
}
/**
Closure to execute if the task fails with an error of type ErrorType
- parameter block: Closure that executes only if the task fails with an error of type ErrorType
- returns: Self Task object
*/
public func error(block: (ErrorType) -> Void) -> Task<T> {
self.queueTaskCallback { (result: TaskResult<T>) -> Void in
if (result.errorType != nil) {
block(result.errorType)
}
}
return self
}
/**
Closure to execute if the task fails with an exception
- parameter block: Closure that executes only if the task fails with an exception
- returns: Self Task object
*/
public func error(block: (NSException) -> Void) -> Task<T> {
self.queueTaskCallback { (result: TaskResult<T>) -> Void in
if (result.exception != nil) {
block(result.exception)
}
}
return self
}
/**
Closure that always executes after a task is completed, regardless of whether or not the task
was a success or failure
- parameter block: Closure that always executes after a task is completed
- returns: Self Task object
*/
public func finally(block: () -> Void) -> Task<T> {
self.queueTaskCallback { (_: TaskResult<T>) -> Void in
block()
}
return self
}
private func taskForBlock<K>(executor: Executor, _ block: (TaskResult<T>) -> TaskResult<K>) -> Task<K> {
let taskManager: TaskManager<K> = TaskManager<K>()
let taskCallback: ((TaskResult<T>) -> Void) = { (result: TaskResult<T>) -> Void in
taskManager.complete(block(result))
return
}
let execBlock = executor.executionBlock(taskCallback)
self.queueTaskCallback(execBlock)
return taskManager.task
}
private func queueTaskCallback(callback: (TaskResult<T>) -> Void) {
synchronized(self) {
if (self.result != nil) {
callback(self.result)
return
}
self.callbacks.append(callback)
}
}
}
extension Task {
/**
Converts this instance of Task to Task<Void>
- returns: Task<Void> of this instance of Task
*/
private func toVoidTask() -> Task<Void> {
return self.then { _ -> Void in }
}
}
/// Static functions to use with Tasks
extension Task {
/**
Executes multiple tasks simultaneously and returns void Task object
that only becomes available when all input tasks are completed
- parameter tasks: Tasks to complete simultaneously
- returns: Void Task object that becomes available only when all input tasks
have been completed
*/
public static func join(tasks: Task...) -> Task<Void> {
let manager = TaskManager<Void>()
guard tasks.count > 0 else {
manager.complete()
return manager.task
}
let numTasks = Atomic<Int>(tasks.count)
let numErrors = Atomic<Int>(0)
tasks.forEach { task in
task.then(.Current) { (Void) -> Void in
}.error { (error: NSError) in
numErrors.value += 1
}.error { (error: ErrorType) in
numErrors.value += 1
}.error { (ex: NSException) in
numErrors.value += 1
}.finally {
numTasks.value -= 1
guard numTasks.value == 0 else { return }
if (numErrors.value > 0) {
manager.completeWithError(NSError(domain: "Task Error", code: 0, userInfo: nil))
} else {
manager.complete()
}
}
}
return manager.task
}
/*public static func join<T, U, V>(taskT: Task<T>, _ taskU: Task<U>, _ taskV: Task<V>)-> Task<(T, U, V)> {
let manager = TaskManager<(T, U, V)>()
var ret: (T, U, V)!
let numTasks = Atomic<Int>(3)
let numErrors = Atomic<Int>(0)
taskT.then(.Current) { taskRet in
ret.0 = taskRet
}.error { (error: NSError) in
numErrors.value += 1
}.finally {
numTasks.value -= 1
guard numTasks.value == 0 else { return }
if (numErrors.value > 0) {
manager.completeWithError(NSError(domain: "Task Error", code: 0, userInfo: nil))
} else {
manager.complete(ret)
}
}
taskU.then(.Current) { taskRet in
ret.1 = taskRet
}.error { (error: NSError) in
numErrors.value += 1
}.finally {
numTasks.value -= 1
guard numTasks.value == 0 else { return }
if (numErrors.value > 0) {
manager.completeWithError(NSError(domain: "Task Error", code: 0, userInfo: nil))
} else {
manager.complete(ret)
}
}
taskV.then(.Current) { taskRet in
ret.2 = taskRet
}.error { (error: NSError) in
numErrors.value += 1
}.finally {
numTasks.value -= 1
guard numTasks.value == 0 else { return }
if (numErrors.value > 0) {
manager.completeWithError(NSError(domain: "Task Error", code: 0, userInfo: nil))
} else {
manager.complete(ret)
}
}
/*let tasks = [taskT, taskU, taskV]
tasks.forEach { task in
task.then(.Current) { ret in
}.error { (error: NSError) in
numErrors.value += 1
}.finally {
numTasks.value -= 1
guard numTasks.value == 0 else { return }
if (numErrors.value > 0) {
manager.completeWithError(NSError(domain: "Task Error", code: 0, userInfo: nil))
} else {
manager.complete()
}
}
}*/
return manager.task
}*/
/*
private static func join<U>(tasks: [Task<U>]) -> Task<Void> {
return self.join(tasks)
}
public static func join<U, V>(taskT: Task<U>, _ taskK: Task<V>) -> Task<(U, V)> {
let manager = TaskManager<(U, V)>()
Task.join([taskT.toVoidTask(), taskK.toVoidTask()]).then {
manager.complete((taskT.result.result, taskK.result.result))
}
return manager.task
}
public static func join<U, V, W>(taskT: Task<U>, _ taskK: Task<V>, _ taskU: Task<W>) -> Task<(U, V, W)> {
let manager = TaskManager<(U, V, W)>()
Task.join([taskT.toVoidTask(), taskK.toVoidTask(), taskU.toVoidTask()]).then {
manager.complete((taskT.result.result, taskK.result.result, taskU.result.result))
}
return manager.task
}*/
}
|
mit
|
084b7c444655bf7b9c891d2c20e4581e
| 27.02268 | 114 | 0.533662 | 4.519787 | false | false | false | false |
benlangmuir/swift
|
test/AutoDiff/validation-test/array.swift
|
7
|
14148
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// Would fail due to unavailability of swift_autoDiffCreateLinearMapContext.
import StdlibUnittest
import _Differentiation
var ArrayAutoDiffTests = TestSuite("ArrayAutoDiff")
typealias FloatArrayTan = Array<Float>.TangentVector
extension Array.DifferentiableView {
/// A subscript that always fatal errors.
///
/// The differentiation transform should never emit calls to this.
subscript(alwaysFatalError: Int) -> Element {
fatalError("wrong subscript")
}
}
ArrayAutoDiffTests.test("ArrayIdentity") {
func arrayIdentity(_ x: [Float]) -> [Float] {
return x
}
let backprop = pullback(at: [5, 6, 7, 8], of: arrayIdentity)
expectEqual(
FloatArrayTan([1, 2, 3, 4]),
backprop(FloatArrayTan([1, 2, 3, 4])))
}
ArrayAutoDiffTests.test("ArraySubscript") {
func sumFirstThree(_ array: [Float]) -> Float {
return array[0] + array[1] + array[2]
}
expectEqual(
FloatArrayTan([1, 1, 1, 0, 0, 0]),
gradient(at: [2, 3, 4, 5, 6, 7], of: sumFirstThree))
}
ArrayAutoDiffTests.test("ArrayLiteral") {
do {
func twoElementLiteral(_ x: Float, _ y: Float) -> [Float] {
return [x, y]
}
let pb = pullback(at: 1, 1, of: twoElementLiteral)
expectEqual((1, 2), pb(FloatArrayTan([Float(1), Float(2)])))
}
do {
// TF-952: Test array literal initialized from an address (e.g. `var`).
func twoElementLiteralAddress(_ x: Float, _ y: Float) -> [Float] {
var result = x
result = result * y
return [result, result]
}
let pb = pullback(at: 3, 4, of: twoElementLiteralAddress)
expectEqual((8, 6), pb(FloatArrayTan([1, 1])))
}
do {
// TF-952: Test array literal initialized with function call results.
func twoElementLiteralFunctionResult(_ x: Float, _ y: Float) -> [Float] {
return [x * y, x * y]
}
let pb = pullback(at: 3, 4, of: twoElementLiteralFunctionResult)
expectEqual((8, 6), pb(FloatArrayTan([1, 1])))
}
do {
// TF-975: Test multiple array literals.
func twoElementLiterals(_ x: Float, _ y: Float) -> [Float] {
let array = [x * y, x * y]
return [array[0], array[1]]
}
let pb = pullback(at: 3, 4, of: twoElementLiterals)
expectEqual((8, 6), pb(FloatArrayTan([1, 1])))
}
}
ArrayAutoDiffTests.test("ArrayLiteralIndirect") {
do {
func twoElementLiteralIndirect<T: Differentiable>(_ x: T, _ y: T) -> [T] {
return [x, y]
}
let pb = pullback(at: Float(1), 1, of: { twoElementLiteralIndirect($0, $1) })
expectEqual((1, 2), pb(FloatArrayTan([1, 2])))
}
do {
func twoElementLiteralIndirectVar<T: Differentiable>(_ x: T, _ y: T) -> [T] {
var result: [T] = []
result = result + [x]
result = result + [y]
return result
}
let pb = pullback(at: Float(1), 1, of: { twoElementLiteralIndirectVar($0, $1) })
expectEqual((1, 2), pb(FloatArrayTan([1, 2])))
}
}
struct Struct<T> {
var x, y: T
}
extension Struct: Differentiable where T: Differentiable {}
ArrayAutoDiffTests.test("ArrayLiteralStruct") {
typealias TV = Struct<Float>.TangentVector
let s = Struct<Float>(x: 3, y: 4)
do {
func structElementLiteral<T>(_ s: Struct<T>) -> [T] {
return [s.x, s.y]
}
func structGeneric<T>(_ s: Struct<T>) -> T {
return structElementLiteral(s)[0]
}
func structConcrete1(_ s: Struct<Float>) -> Float {
return structElementLiteral(s)[0] * structElementLiteral(s)[1]
}
func structConcrete2(_ s: Struct<Float>) -> Float {
let array = structElementLiteral(s)
return array[0] * array[1]
}
expectEqual(TV(x: 1, y: 0), gradient(at: s, of: { s in structGeneric(s) }))
expectEqual(TV(x: 4, y: 3), gradient(at: s, of: structConcrete1))
expectEqual(TV(x: 4, y: 3), gradient(at: s, of: structConcrete2))
}
do {
func structElementAddressLiteral<T>(_ s: Struct<T>) -> [T] {
var s2 = Struct<T>(x: s.x, y: s.y)
return [s2.x, s2.y]
}
func structGeneric<T>(_ s: Struct<T>) -> T {
return structElementAddressLiteral(s)[0]
}
func structConcrete1(_ s: Struct<Float>) -> Float {
return structElementAddressLiteral(s)[0] *
structElementAddressLiteral(s)[1]
}
func structConcrete2(_ s: Struct<Float>) -> Float {
let array = structElementAddressLiteral(s)
return array[0] * array[1]
}
expectEqual(TV(x: 1, y: 0), gradient(at: s, of: { s in structGeneric(s) }))
expectEqual(TV(x: 4, y: 3), gradient(at: s, of: structConcrete1))
expectEqual(TV(x: 4, y: 3), gradient(at: s, of: structConcrete2))
}
do {
func structElementAddressLiteral2<T>(_ s: Struct<T>) -> [T] {
var s2 = Struct<T>(x: s.x, y: s.y)
let array = [s2.x, s2.y]
return [array[0], array[1]]
}
func structGeneric<T>(_ s: Struct<T>) -> T {
return structElementAddressLiteral2(s)[0]
}
func structConcrete1(_ s: Struct<Float>) -> Float {
return structElementAddressLiteral2(s)[0] *
structElementAddressLiteral2(s)[1]
}
func structConcrete2(_ s: Struct<Float>) -> Float {
let array = structElementAddressLiteral2(s)
return array[0] * array[1]
}
expectEqual(TV(x: 1, y: 0), gradient(at: s, of: { s in structGeneric(s) }))
expectEqual(TV(x: 4, y: 3), gradient(at: s, of: structConcrete1))
expectEqual(TV(x: 4, y: 3), gradient(at: s, of: structConcrete2))
}
// TF-978: Test array literal initialized with `apply` indirect results.
do {
func applyIndirectResult<T>(_ x: T, _ y: T) -> [Struct<T>] {
return [Struct(x: x, y: y), Struct(x: x, y: y)]
}
let pb = pullback(at: Float(3), 4, of: { applyIndirectResult($0, $1) })
let v = TV(x: 1, y: 1)
expectEqual((2, 2), pb(.init([v, v])))
}
}
ArrayAutoDiffTests.test("ArrayLiteralTuple") {
do {
func tupleElementGeneric<T>(_ x: T, _ y: T) -> [T] {
var tuple = (x, y)
return [tuple.0, tuple.1]
}
let pb = pullback(at: Float(3), 4, of: { tupleElementGeneric($0, $1) })
// FIXME(TF-977): Fix incorrect derivative for array literal with
// `tuple_element_addr` elements.
// expectEqual((1, 1), pb(FloatArrayTan([1, 1])))
expectEqual((0, 2), pb(FloatArrayTan([1, 1])))
}
}
ArrayAutoDiffTests.test("ArrayLiteralNested") {
do {
func nested0(
_ x: Float, _ y: Float, _ bool: Bool = true
) -> [Float] {
let result = [[[[x, y]]]]
return result[0][0][0]
}
let pb = pullback(at: 3, 4, of: { nested0($0, $1) })
expectEqual((1, 1), pb(FloatArrayTan([1, 1, 1, 1])))
}
do {
func nested1(
_ x: Float, _ y: Float, _ bool: Bool = true
) -> [Float] {
var result = [[x, y], [x, y]]
return result[0] + result[1]
}
let pb = pullback(at: 3, 4, of: { nested1($0, $1) })
expectEqual((2, 2), pb(FloatArrayTan([1, 1, 1, 1])))
}
do {
// Convoluted function computing `[x + y]`.
func nested2(
_ x: Float, _ y: Float, _ bool: Bool = true
) -> [Float] {
var result = [[], [x]]
result = result + []
result = result + [[]]
result = result + [[y]]
var nested = [result, [], result]
return nested[0][1] + result[3]
}
let (value, pb) = valueWithPullback(at: 3, 4, of: { nested2($0, $1) })
expectEqual([3, 4], value)
expectEqual((1, 1), pb(FloatArrayTan([1, 1])))
}
}
ArrayAutoDiffTests.test("ArrayLiteralControlFlow") {
do {
// TF-922: Test array literal and control flow.
func controlFlow(
_ x: Float, _ y: Float, _ bool: Bool = true
) -> [Float] {
var result = [x * y, x * y]
let result2 = bool ? result : result
var result3 = bool ? (bool ? result2 : result) : result2
return result3
}
let pb = pullback(at: 3, 4, of: { controlFlow($0, $1) })
expectEqual((8, 6), pb(FloatArrayTan([1, 1])))
}
do {
// TF-922: Test array literal and control flow.
func controlFlowAddress(
_ x: Float, _ y: Float, _ bool: Bool = true
) -> [Float] {
var product = x * y // initial value is an address
var result = [product, product]
let result2 = bool ? result : result
var result3 = bool ? (bool ? result2 : result) : result2
return result3
}
let pb = pullback(at: 3, 4, of: { controlFlowAddress($0, $1) })
expectEqual((8, 6), pb(FloatArrayTan([1, 1])))
}
do {
// TF-922: Test array literal and control flow.
func controlFlowGeneric<T>(_ x: T, _ y: T, _ bool: Bool = true) -> [T] {
var result = [x, y] // initial values are addresses
let result2 = bool ? result : result
var result3 = bool ? (bool ? result2 : result) : result2
return result3
}
let pb = pullback(at: Float(3), 4, of: { controlFlowGeneric($0, $1) })
expectEqual((1, 1), pb(FloatArrayTan([1, 1])))
}
do {
// Test nested array literal and control flow.
func controlFlowNestedLiteral(
_ x: Float, _ y: Float, _ bool: Bool = true
) -> [Float] {
var result: [[Float]] = []
var result2 = bool ? result + [[x]] : result + [[x]]
var result3 = bool ? (bool ? result2 + [[y]] : result2 + [[y]]) : result2 + [[y]]
return result3[0] + [result3[1][0]]
}
let pb = pullback(at: 3, 4, of: { controlFlowNestedLiteral($0, $1) })
expectEqual((1, 1), pb(FloatArrayTan([1, 1])))
}
}
ArrayAutoDiffTests.test("ExpressibleByArrayLiteralIndirect") {
struct Indirect<T: Differentiable>: Differentiable & ExpressibleByArrayLiteral {
var x: T
typealias ArrayLiteralElement = T
init(arrayLiteral: T...) {
assert(arrayLiteral.count > 1)
self.x = arrayLiteral[0]
}
}
func testArrayUninitializedIntrinsic<T>(_ x: T, _ y: T) -> Indirect<T> {
return [x, y]
}
let (gradX, gradY) = pullback(at: Float(1), Float(1), of: {
x, y in testArrayUninitializedIntrinsic(x, y)
})(Indirect<Float>.TangentVector(x: 1))
expectEqual(1, gradX)
expectEqual(0, gradY)
}
ArrayAutoDiffTests.test("Array.+") {
func sumFirstThreeConcatenating(_ a: [Float], _ b: [Float]) -> Float {
let c = a + b
return c[0] + c[1] + c[2]
}
expectEqual(
(.init([1, 1]), .init([1, 0])),
gradient(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating))
expectEqual(
(.init([1, 1, 1, 0]), .init([0, 0])),
gradient(at: [0, 0, 0, 0], [0, 0], of: sumFirstThreeConcatenating))
expectEqual(
(.init([]), .init([1, 1, 1, 0])),
gradient(at: [], [0, 0, 0, 0], of: sumFirstThreeConcatenating))
func identity(_ array: [Float]) -> [Float] {
var results: [Float] = []
for i in withoutDerivative(at: array.indices) {
results = results + [array[i]]
}
return results
}
let v = FloatArrayTan([4, -5, 6])
expectEqual(v, pullback(at: [1, 2, 3], of: identity)(v))
let v1: [Float] = [1, 1]
let v2: [Float] = [1, 1, 1]
expectEqual((.zero, .zero), pullback(at: v1, v2, of: +)(.zero))
}
ArrayAutoDiffTests.test("Array.+=") {
func sumFirstThreeConcatenating(_ a: [Float], _ b: [Float]) -> Float {
var c = a
c += b
return c[0] + c[1] + c[2]
}
expectEqual(
(.init([1, 1]), .init([1, 0])),
gradient(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating))
expectEqual(
(.init([1, 1, 1, 0]), .init([0, 0])),
gradient(at: [0, 0, 0, 0], [0, 0], of: sumFirstThreeConcatenating))
expectEqual(
(.init([]), .init([1, 1, 1, 0])),
gradient(at: [], [0, 0, 0, 0], of: sumFirstThreeConcatenating))
func identity(_ array: [Float]) -> [Float] {
var results: [Float] = []
for i in withoutDerivative(at: array.indices) {
results += [array[i]]
}
return results
}
let v = FloatArrayTan([4, -5, 6])
expectEqual(v, pullback(at: [1, 2, 3], of: identity)(v))
}
ArrayAutoDiffTests.test("Array.append") {
func appending(_ array: [Float], _ element: Float) -> [Float] {
var result = array
result.append(element)
return result
}
do {
let v = FloatArrayTan([1, 2, 3, 4])
expectEqual((.init([1, 2, 3]), 4),
pullback(at: [0, 0, 0], 0, of: appending)(v))
}
func identity(_ array: [Float]) -> [Float] {
var results: [Float] = []
for i in withoutDerivative(at: array.indices) {
results.append(array[i])
}
return results
}
do {
let v = FloatArrayTan([4, -5, 6])
expectEqual(v, pullback(at: [1, 2, 3], of: identity)(v))
}
}
ArrayAutoDiffTests.test("Array.init(repeating:count:)") {
@differentiable(reverse)
func repeating(_ x: Float) -> [Float] {
Array(repeating: x, count: 10)
}
expectEqual(Float(10), gradient(at: .zero) { x in
repeating(x).differentiableReduce(0, {$0 + $1})
})
expectEqual(Float(20), pullback(at: .zero, of: { x in
repeating(x).differentiableReduce(0, {$0 + $1})
})(2))
}
ArrayAutoDiffTests.test("Array.DifferentiableView.init") {
@differentiable(reverse)
func constructView(_ x: [Float]) -> Array<Float>.DifferentiableView {
return Array<Float>.DifferentiableView(x)
}
let backprop = pullback(at: [5, 6, 7, 8], of: constructView)
expectEqual(
FloatArrayTan([1, 2, 3, 4]),
backprop(FloatArrayTan([1, 2, 3, 4])))
}
ArrayAutoDiffTests.test("Array.DifferentiableView.base") {
@differentiable(reverse)
func accessBase(_ x: Array<Float>.DifferentiableView) -> [Float] {
return x.base
}
let backprop = pullback(
at: Array<Float>.DifferentiableView([5, 6, 7, 8]),
of: accessBase)
expectEqual(
FloatArrayTan([1, 2, 3, 4]),
backprop(FloatArrayTan([1, 2, 3, 4])))
}
ArrayAutoDiffTests.test("Array.DifferentiableView.move") {
var v: [Float] = [1, 2, 3]
v.move(by: .zero)
expectEqual(v, [1, 2, 3])
var z: [Float] = []
z.move(by: .zero)
expectEqual(z, [])
}
ArrayAutoDiffTests.test("Array.DifferentiableView reflection") {
let tan = [Float].DifferentiableView([41, 42])
let children = Array(Mirror(reflecting: tan).children)
expectEqual(2, children.count)
if let child1 = expectNotNil(children[0].value as? Float),
let child2 = expectNotNil(children[1].value as? Float) {
expectEqual(41, child1)
expectEqual(42, child2)
}
}
runAllTests()
|
apache-2.0
|
13839506aabb1b9ff69530daf14d039c
| 29.360515 | 87 | 0.592734 | 3.21838 | false | true | false | false |
leizh007/HiPDA
|
HiPDA/HiPDA/General/Views/PageNumberSelectionViewController.swift
|
1
|
2724
|
//
// PageNumberSelectionViewController.swift
// HiPDA
//
// Created by leizh007 on 2017/6/6.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import UIKit
typealias PageNumberSelectedCompletion = (Int) -> Void
class PageNumberSelectionViewController: BaseViewController {
var completion: PageNumberSelectedCompletion?
var totalPageNumber = 1
var updateSliderValue = true
var currentPageNumber = 1 {
didSet {
if let label = pageNumberLabel {
label.text = "\(currentPageNumber)"
}
if let slider = slider, updateSliderValue {
slider.value = Float(currentPageNumber)
}
}
}
@IBOutlet fileprivate weak var pageNumberLabel: UILabel!
@IBOutlet fileprivate weak var maxPageNumberLabel: UILabel!
@IBOutlet fileprivate weak var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
pageNumberLabel.text = "\(currentPageNumber)"
maxPageNumberLabel.text = "\(totalPageNumber)"
slider.maximumValue = Float(totalPageNumber)
slider.value = Float(currentPageNumber)
}
@IBAction fileprivate func cancelButtonPressed(_ sender: UIBarButtonItem) {
presentingViewController?.dismiss(animated: true, completion: nil)
}
@IBAction fileprivate func confirmButtonPressed(_ sender: UIBarButtonItem) {
presentingViewController?.dismiss(animated: true, completion: nil)
completion?(currentPageNumber)
}
@IBAction fileprivate func firstPageButtonPressed(_ sender: UIButton) {
updateSliderValue = true
currentPageNumber = 1
}
@IBAction fileprivate func previousPageButtonPressed(_ sender: UIButton) {
updateSliderValue = true
currentPageNumber = currentPageNumber - 1 <= 0 ? 1 : currentPageNumber - 1
}
@IBAction fileprivate func nextPageButtonPressed(_ sender: UIButton) {
updateSliderValue = true
currentPageNumber = currentPageNumber + 1 > totalPageNumber ? currentPageNumber : currentPageNumber + 1
}
@IBAction fileprivate func lastPageButtonPressed(_ sender: UIButton) {
updateSliderValue = true
currentPageNumber = totalPageNumber
}
@IBAction fileprivate func sliderValueChanged(_ sender: UISlider) {
updateSliderValue = false
currentPageNumber = Int(round(sender.value))
}
@IBAction fileprivate func sliderDidFinishDragging(_ sender: UISlider) {
updateSliderValue = true
currentPageNumber = Int(round(sender.value))
}
}
// MARK: - StoryboardLoadable
extension PageNumberSelectionViewController: StoryboardLoadable { }
|
mit
|
750aed05d7f2afdabf0cfda55db88c0a
| 32.592593 | 111 | 0.681735 | 5.598765 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/UITextField.swift
|
1
|
2227
|
//
// UITextField.swift
// CurrencyText
//
// Created by Felipe Lefèvre Marino on 12/26/18.
//
import Cocoa
public extension NSTextView {
// MARK: Public
var selectedTextRangeOffsetFromEnd: Int {
return self.string.length - selectedRange.min
}
/// Sets the selected text range when the text field is starting to be edited.
/// _Should_ be called when text field start to be the first responder.
func setInitialSelectedTextRange() {
// update selected text range if needed
adjustSelectedTextRange(lastOffsetFromEnd: 0) // at the end when first selected
}
/// Interface to update the selected text range as expected.
/// - Parameter lastOffsetFromEnd: The last stored selected text range offset from end. Used to keep it concise with pre-formatting.
func updateSelectedTextRange(lastOffsetFromEnd: Int) {
adjustSelectedTextRange(lastOffsetFromEnd: lastOffsetFromEnd)
}
// MARK: Private
/// Adjust the selected text range to match the best position.
private func adjustSelectedTextRange(lastOffsetFromEnd: Int) {
/// If text is empty the offset is set to zero, the selected text range does need to be changed.
let text = self.string
if text.isEmpty {
return
}
var offsetFromEnd = lastOffsetFromEnd
/// Adjust offset if needed. When the last number character offset from end is less than the current offset,
/// or in other words, is more distant to the end of the string, the offset is readjusted to it,
/// so the selected text range is correctly set to the last index with a number.
if let lastNumberOffsetFromEnd = text.lastNumberOffsetFromEnd,
case let shouldOffsetBeAdjusted = lastNumberOffsetFromEnd < offsetFromEnd,
shouldOffsetBeAdjusted {
offsetFromEnd = lastNumberOffsetFromEnd
}
updateSelectedTextRange(offsetFromEnd: offsetFromEnd)
}
/// Update the selected text range with given offset from end.
private func updateSelectedTextRange(offsetFromEnd: Int) {
self.setSelectedRange(NSMakeRange(string.length - offsetFromEnd, self.selectedRange.length))
}
}
|
gpl-2.0
|
bd8957ad75a8bf9c20d9bb3741ba0102
| 36.1 | 136 | 0.699012 | 4.849673 | false | false | false | false |
AdaptiveMe/adaptive-arp-darwin
|
adaptive-arp-rt/AdaptiveArpRtiOSTests/GeolocationTest.swift
|
1
|
2421
|
/*
* =| ADAPTIVE RUNTIME PLATFORM |=======================================================================================
*
* (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
*
* 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.
*
* Original author:
*
* * Carlos Lozano Diez
* <http://github.com/carloslozano>
* <http://twitter.com/adaptivecoder>
* <mailto:[email protected]>
*
* Contributors:
*
* * Ferran Vila Conesa
* <http://github.com/fnva>
* <http://twitter.com/ferran_vila>
* <mailto:[email protected]>
*
* =====================================================================================================================
*/
import XCTest
import AdaptiveArpApi
/**
* Geolocation delegate tests class
*/
class GeolocationTest: XCTestCase {
/// Listener for results
var listener:GeolocationListenerTest!
/**
Constructor.
*/
override func setUp() {
super.setUp()
AppRegistryBridge.sharedInstance.getLoggingBridge().setDelegate(LoggingDelegate())
AppRegistryBridge.sharedInstance.getPlatformContext().setDelegate(AppContextDelegate())
AppRegistryBridge.sharedInstance.getPlatformContextWeb().setDelegate(AppContextWebviewDelegate())
AppRegistryBridge.sharedInstance.getGeolocationBridge().setDelegate(GeolocationDelegate())
listener = GeolocationListenerTest(id: 0)
}
/**
Method for testing the geolocation operations
*/
func testGeolocation() {
AppRegistryBridge.sharedInstance.getGeolocationBridge().addGeolocationListener(listener)
AppRegistryBridge.sharedInstance.getGeolocationBridge().removeGeolocationListener(listener)
AppRegistryBridge.sharedInstance.getGeolocationBridge().removeGeolocationListeners()
}
}
|
apache-2.0
|
4d5ec1e9c076c412a7ad8b53f64a6016
| 35.69697 | 119 | 0.635275 | 4.981481 | false | true | false | false |
LeeShiYoung/LSYWeibo
|
LSYWeiBo/AppDelegate.swift
|
1
|
4061
|
//
// AppDelegate.swift
// LSYWeiBo
//
// Created by 李世洋 on 16/4/30.
// Copyright © 2016年 李世洋. All rights reserved.
//
import UIKit
let AppdelegateNotifiKey = "AppdelegateNotifiKey"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//注册通知 用于 切换 控制器
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.changeViewController(_:)), name: AppdelegateNotifiKey, object: nil)
UITabBar.appearance().tintColor = UIColor.orangeColor()
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = defultController()
window?.makeKeyAndVisible()
return true
}
// 接受通知 切换 控制器
func changeViewController(noti: NSNotification) {
if noti.object as! Bool {
window?.rootViewController = MainViewController()
} else {
window?.rootViewController = "NewfeatureCollectionViewController".storyBoard()
}
}
//获取 默认控制器
private func defultController() -> UIViewController {
if UserAccount.userLogin() {
return isNewUpdate() ? "NewfeatureCollectionViewController".storyBoard() : "WelcomeViewController".storyBoard()
}
return MainViewController()
}
//判断是否有新版本
private func isNewUpdate() -> Bool{
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
let sandboxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
if currentVersion.compare(sandboxVersion) == NSComparisonResult.OrderedDescending
{
NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString")
return true
}
return false
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
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:.
}
}
|
artistic-2.0
|
c4f9814e801f0c8a6425c65ea7d02dbb
| 39.161616 | 285 | 0.703471 | 5.762319 | false | false | false | false |
Jakobeha/lAzR4t
|
lAzR4t Shared/Code/Play/ProjectileElemController.swift
|
1
|
2774
|
//
// ProjectileElemController.swift
// lAzR4t
//
// Created by Jakob Hain on 9/30/17.
// Copyright © 2017 Jakob Hain. All rights reserved.
//
import Foundation
class ProjectileElemController: PlayElemController_impl<ProjectileElem> {
override var curModel: ProjectileElem {
didSet {
node_spe.reconfigure(
colors: curModel.colors,
direction: curModel.direction,
pos: curModel.pos,
offset: self.displayOffset
)
}
}
let node_spe: ProjectileElemNode
var pos: CellPos {
get { return curModel.pos }
set(newPos) { curModel = curModel.set(pos: newPos) }
}
var direction: CellDirection {
get { return curModel.direction }
}
var _displayOffset: CGFloat
///A display offset which shows this projectile;'s progress to the next cell
var displayOffset: CGFloat {
get { return _displayOffset }
set(newDisplayOffset) {
_displayOffset = newDisplayOffset
node_spe.reconfigureNoTexture(
colors: curModel.colors,
direction: curModel.direction,
pos: curModel.pos,
offset: self.displayOffset
)
}
}
init(curModel: ProjectileElem) {
_displayOffset = 0
node_spe = ProjectileElemNode(
colors: curModel.colors,
direction: curModel.direction,
pos: curModel.pos,
offset: _displayOffset
)
super.init(curModel: curModel, node: node_spe)
}
///Moves the projectile one in-game tick (time unit).
///*Does* update any collisions.
func moveOneTick(affecting collidables: [PlayElemController]) {
assert(isInPlay, "Projectile shouldn't be moved when it's out of play")
let newPos = pos + direction.unitOffset
let newFrame = curModel.frame.offset(by: direction.unitOffset)
let collideds = collidables.filter {
CellFrame.overlap($0.curModel_play.frame, newFrame)
}
var shouldRemove = false
for collided in collideds {
collided.absorb(projectile: curModel)
if let collidedProj = collided.curModel_play as? ProjectileElem {
//A projectile doesn't need to be removed when it collides with other projectiles,
//but it still could be removed in `absorb`
absorb(projectile: collidedProj)
} else {
//A projectile is removed when it collides with a non-projectile.
shouldRemove = true
}
}
if shouldRemove && isInPlay {
removeFromPlay()
}
pos = newPos
}
}
|
mit
|
4def38b07931bb44a687d1b143381323
| 32.409639 | 98 | 0.58709 | 4.422648 | false | false | false | false |
Oscareli98/Moya
|
Demo/Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/ObserveOnDispatchQueue.swift
|
2
|
1719
|
//
// ObserveOnDispatchQueue.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/31/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ObserveOnDispatchQueueSink<O: ObserverType> : ScheduledSerialSchedulerObserver<O> {
var disposeLock = Lock()
var cancel: Disposable
init(scheduler: DispatchQueueScheduler, observer: O, cancel: Disposable) {
self.cancel = cancel
super.init(scheduler: scheduler, observer: observer)
}
override func dispose() {
super.dispose()
let toDispose = disposeLock.calculateLocked { () -> Disposable in
let originalCancel = self.cancel
self.cancel = NopDisposable.instance
return originalCancel
}
toDispose.dispose()
}
}
#if TRACE_RESOURCES
public var numberOfDispatchQueueObservables: Int32 = 0
#endif
class ObserveOnDispatchQueue<E> : Producer<E> {
let scheduler: DispatchQueueScheduler
let source: Observable<E>
init(source: Observable<E>, scheduler: DispatchQueueScheduler) {
self.scheduler = scheduler
self.source = source
#if TRACE_RESOURCES
OSAtomicIncrement32(&numberOfDispatchQueueObservables)
#endif
}
override func run<O : ObserverType where O.Element == E>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = ObserveOnDispatchQueueSink(scheduler: scheduler, observer: observer, cancel: cancel)
setSink(sink)
return source.subscribeSafe(sink)
}
#if TRACE_RESOURCES
deinit {
OSAtomicDecrement32(&numberOfDispatchQueueObservables)
}
#endif
}
|
mit
|
ec883bcfa6e12f9e675c78f7164877fc
| 26.741935 | 140 | 0.668412 | 4.645946 | false | false | false | false |
czechboy0/BuildaUtils
|
Source/SimpleURLCache.swift
|
2
|
2122
|
//
// SimpleURLCache.swift
// Buildasaur
//
// Created by Honza Dvorsky on 1/19/16.
// Copyright © 2016 Honza Dvorsky. All rights reserved.
//
import Foundation
import SwiftSafe
open class ResponseInfo: AnyObject {
open let response: HTTPURLResponse
open let body: AnyObject?
public init(response: HTTPURLResponse, body: AnyObject?) {
self.response = response
self.body = body
}
}
public struct CachedInfo {
public let responseInfo: ResponseInfo?
public let update: (ResponseInfo) -> ()
public var etag: String? {
guard let responseInfo = self.responseInfo else { return nil }
return responseInfo.response.allHeaderFields["ETag"] as? String
}
}
public protocol URLCache {
func getCachedInfoForRequest(_ request: URLRequest) -> CachedInfo
}
/**
* Stores responses in memory only and only if resp code was in range 200...299
* This is optimized for APIs that return ETag for every response, thus
* a repeated request can send over ETag in a header, allowing for not
* downloading data again. In the case of GitHub, such request doesn't count
* towards the rate limit.
*/
open class InMemoryURLCache: URLCache {
fileprivate let storage = NSCache<NSString, AnyObject>()
fileprivate let safe: Safe = CREW()
public init(countLimit: Int = 1000) {
self.storage.countLimit = countLimit //just to not grow indefinitely
}
open func getCachedInfoForRequest(_ request: URLRequest) -> CachedInfo {
var responseInfo: ResponseInfo?
let key = request.cacheableKey() as NSString
self.safe.read {
responseInfo = self.storage.object(forKey: key) as? ResponseInfo
}
let info = CachedInfo(responseInfo: responseInfo) { (responseInfo) -> () in
self.safe.write {
self.storage.setObject(responseInfo, forKey: key)
}
}
return info
}
}
extension URLRequest {
public func cacheableKey() -> String {
return "\(self.httpMethod!)-\(self.url!.absoluteString)"
}
}
|
mit
|
1fabfff3e629c603e48eea1964931a7d
| 27.662162 | 83 | 0.656766 | 4.522388 | false | false | false | false |
colbylwilliams/bugtrap
|
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/JIRA/Domain/JiraProject.swift
|
1
|
1810
|
//
// JiraProject.swift
// bugTrap
//
// Created by Colby L Williams on 12/5/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
class JiraProject : JiraSimpleItem {
// var lead = JiraUser
var issueTypes = [JiraIssueType]()
var assigneeType = ""
var avatarUrls = JiraAvatarUrls()
override init() {
super.init()
}
init(id: Int?, name: String, key: String, selfUrl: String, iconUrl: String, details: String, expand: String, issueTypes: [JiraIssueType], assigneeType: String, avatarUrls: JiraAvatarUrls) {
super.init(id: id, name: name, key: key, selfUrl: selfUrl, iconUrl: iconUrl, details: details, expand: expand)
self.issueTypes = issueTypes
self.assigneeType = assigneeType
self.avatarUrls = avatarUrls
}
override class func deserialize (json: JSON) -> JiraProject? {
let id = json["id"].intValue
let name = json["name"].stringValue
let key = json["key"].stringValue
let selfUrl = json["self"].stringValue
let iconUrl = json["iconUrl"].stringValue
let details = json["description"].stringValue
let expand = json["expand"].stringValue
let issueTypes:[JiraIssueType] = JiraIssueType.deserializeAll(json["issuetypes"])
let assigneeType = json["assigneeType"].stringValue
let avatarUrls = JiraAvatarUrls.deserialize(json["avatarUrls"])
return JiraProject(id: id, name: name, key: key, selfUrl: selfUrl, iconUrl: iconUrl, details: details, expand: expand, issueTypes: issueTypes, assigneeType: assigneeType, avatarUrls: avatarUrls!)
}
class func deserializeAll(json: JSON) -> [JiraProject] {
var items = [JiraProject]()
if let jsonArray = json.array {
for item: JSON in jsonArray {
if let si = deserialize(item) {
items.append(si)
}
}
}
return items
}
}
|
mit
|
ee13c0c97c37c42f719d8143bde54e40
| 24.507042 | 197 | 0.69116 | 3.656566 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.