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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bingFly/weibo | weibo/weiboTests/AuthVCTests.swift | 1 | 3138 | //
// AtuhVCTests.swift
// weibo
//
// Created by hanbing on 15/3/2.
// Copyright (c) 2015年 fly. All rights reserved.
//
import UIKit
import XCTest
class AuthVCTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testContinueWithCode()
{
/// 登录
var url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=3951981946&redirect_uri=www.baidu.com")
var result = authVc!.continueWithCode(url!)
XCTAssertTrue(result.load, "应该加载")
XCTAssertNil(result.code, "不应该有code")
// 换账号
url = NSURL(string: "http://passport.weibo.cn/sso/crossdomain?action=logout&callback=sinaSSOController.doCrossDomainCallBack&scriptId=ssoscript6&client=ssologin.js(v1.4.18)&_=1425174996286")
result = authVc!.continueWithCode(url!)
XCTAssertFalse(result.load, "不应该加载")
XCTAssertNil(result.code, "不应该有code")
// 注册
url = NSURL(string: "http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=6n8jAS&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D3951981946%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dwww.baidu.com%26from%3D%26with_cookie%3D")
result = authVc!.continueWithCode(url!)
XCTAssertFalse(result.load, "不应该加载")
XCTAssertNil(result.code, "不应该有code")
// 取消授权
url = NSURL(string: "http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330")
result = authVc!.continueWithCode(url!)
XCTAssertFalse(result.load, "不应该加载")
XCTAssertNil(result.code, "不应该有code")
// 授权回掉
// code = 5aefff0d36f7b231554f43ccd4338abe
let code = "5aefff0d36f7b231554f43ccd4338abe"
url = NSURL(string: "http://www.baidu.com/?code=\(code)")
result = authVc!.continueWithCode(url!)
XCTAssertFalse(result.load, "不应该加载")
XCTAssertTrue(result.code == code, "应该相等")
}
/**
测试根view是否是UIWebView
*/
func testRootView(){
let view = authVc!.view
XCTAssert(view.isKindOfClass(UIWebView.self), "应该是webView")
}
/**
测试webView的代理
*/
func testWebViewDelegate(){
let view = authVc!.view as! UIWebView
XCTAssert(view.delegate === authVc, "webView的代理应该设置")
}
/// 主控制器懒加载
lazy var authVc:AuthVC? = {
let bundle = NSBundle(forClass: AuthVCTests.self)
/**
* 加载storyboard的所有方法总结
*/
let sb = UIStoryboard(name: "Auth", bundle: bundle)
let vc = sb.instantiateInitialViewController() as! AuthVC
return vc
}()
}
| mit | f88b9356bf0ca5c1b8c2ebd821b9062d | 28.148515 | 275 | 0.599185 | 3.61227 | false | true | false | false |
austinzheng/swift | validation-test/compiler_crashers_fixed/00199-swift-optional-swift-diagnostic-operator.swift | 65 | 909 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
func e<k>() -> (k, k -> k) -> k {
f j f.i = {
}
{
k) {
n }
}
m e {
class func i()
}
class f: e{ class f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f = 0) {
}
l -> Any) return $0
}
let succeeds: Int = 1, f1)
class A<T : A> {
}
class c {
func b((Any, c))(a: (Any, AnyObj c() -> Str rn
func e<T where Tj d. h }b
}
| apache-2.0 | 1706f40f75d748391c7ff9b19da6f1da | 19.2 | 79 | 0.573157 | 2.771341 | false | false | false | false |
alirsamar/BiOS | beginning-ios-alien-adventure-alien-adventure-2/Alien Adventure/AlienAdventure3.swift | 3 | 4460 | //
// AlienAdventure3.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/5/15.
// Copyright © 2015 Udacity. All rights reserved.
//
// MARK: - RequestTester (Alien Adventure 3 Tests)
extension UDRequestTester {
// MARK: BasicCheck
func testBasicCheck() -> Bool {
return delegate.handleBasicCheck()
}
// MARK: AdvancedCheck
func testAdvancedCheck() -> Bool {
return delegate.handleAdvancedCheck()
}
// MARK: ExpertCheck
func testExpertCheck() -> Bool {
return delegate.handleExpertCheck()
}
// MARK: CheckBadges
func testCheckBadges() -> Bool {
if let badgeManager = delegate.badgeManager {
// check 1
let typesToCheck1: [UDRequestType] = [.BasicCheck, .BasicCheck, .AdvancedCheck, .ExpertCheck]
var typesFulfilled1 = [UDRequestType]()
for badge in badgeManager.badges {
typesFulfilled1.append(badge.requestType)
}
if !delegate.handleCheckBadges(badgeManager.badges, requestTypes: typesToCheck1) {
print("CheckBadges FAILED: If badges for are present \(typesFulfilled1) when checking for \(typesToCheck1), then the check should pass.")
return false
}
// check 2
let typesToCheck2: [UDRequestType] = [.BasicCheck, .BasicCheck, .AdvancedCheck, .ExpertCheck]
let typesFulfilled2: [UDRequestType] = [.BasicCheck]
if delegate.handleCheckBadges([Badge(requestType: .BasicCheck)], requestTypes: typesToCheck2) {
print("CheckBadges FAILED: If badges for are present \(typesFulfilled2) when checking for \(typesToCheck2), then the check should not pass.")
return false
}
// check 3
let typesToCheck3: [UDRequestType] = [.BasicCheck, .ShuffleStrings]
let typesFulfilled3: [UDRequestType] = [.BasicCheck, .ShuffleStrings, .MostCommonCharacter]
if !delegate.handleCheckBadges([Badge(requestType: .BasicCheck), SpecialBadge(requestType: .ShuffleStrings), Badge(requestType: .MostCommonCharacter)], requestTypes: typesToCheck3) {
print("CheckBadges FAILED: If badges for are present \(typesFulfilled3) when checking for \(typesToCheck3), then the check should pass.")
return false
}
// check 4
let typesToCheck4 = [UDRequestType]()
let typesFulfilled4: [UDRequestType] = [.BasicCheck, .ShuffleStrings, .MostCommonCharacter]
if !delegate.handleCheckBadges([Badge(requestType: .BasicCheck), SpecialBadge(requestType: .ShuffleStrings), Badge(requestType: .MostCommonCharacter)], requestTypes: typesToCheck4) {
print("CheckBadges FAILED: If badges for are present \(typesFulfilled4) when checking for \(typesToCheck4), then the check should pass.")
return false
}
// check 5
let typesToCheck5: [UDRequestType] = [.BasicCheck, .ShuffleStrings]
let typesFulfilled5 = [UDRequestType]()
if delegate.handleCheckBadges([Badge](), requestTypes: typesToCheck5) {
print("CheckBadges FAILED: If badges for are present \(typesFulfilled5) when checking for \(typesToCheck5), then the check should not pass.")
return false
}
} else {
return false
}
return true
}
}
// MARK: - RequestTester (Alien Adventure 3 Process Requests)
extension UDRequestTester {
// MARK: BasicCheck
func processBasicCheck() -> String {
return "Hero: [Screen was tapped. Basic check complete!]"
}
// MARK: AdvancedCheck
func processAdvancedCheck() -> String {
return "Hero: [Screen was tapped. Advanced check complete!]"
}
// MARK: ExpertCheck
func processExpertCheck() -> String {
return "Hero: [Screen was tapped. Expert check complete!]"
}
// MARK: CheckBadges
func processCheckBadges(failed: Bool) -> String {
if failed {
return "Hero: Yeah... so it turns out I have some badges, but honestly I'm not going to tell you what I have..."
} else {
return "Hero: Yeah, I have those badges. See look here!"
}
}
} | mit | c34903e8b80a02cbafb56f54f5784fda | 37.119658 | 194 | 0.610899 | 4.758805 | false | true | false | false |
benlangmuir/swift | test/Constraints/keypath_swift_5.swift | 30 | 1111 | // RUN: %target-swift-frontend -typecheck -verify %S/Inputs/keypath.swift -primary-file %s -swift-version 5
struct S {
let i: Int
init() {
let _: WritableKeyPath<S, Int> = \.i // expected-error {{cannot convert value of type 'KeyPath<S, Int>' to specified type 'WritableKeyPath<S, Int>'}}
S()[keyPath: \.i] = 1
// expected-error@-1 {{cannot assign through subscript: key path is read-only}}
}
}
func test() {
let _: WritableKeyPath<C, Int> = \.i // expected-error {{cannot convert value of type 'KeyPath<C, Int>' to specified type 'WritableKeyPath<C, Int>'}}
C()[keyPath: \.i] = 1
// expected-error@-1 {{cannot assign through subscript: key path is read-only}}
let _ = C()[keyPath: \.i] // no warning for a read
}
struct T {
private(set) var a: Int
init(a: Int) {
self.a = a
}
}
func testReadOnlyKeyPathDiagnostics() {
let path = \T.a
var t = T(a: 3)
t[keyPath: path] = 4 // expected-error {{cannot assign through subscript: 'path' is a read-only key path}}
t[keyPath: \T.a] = 4 // expected-error {{cannot assign through subscript: key path is read-only}}
}
| apache-2.0 | 411e10e5e8877cfc252aa37b29f83a70 | 29.861111 | 153 | 0.645365 | 3.326347 | false | true | false | false |
riteshhgupta/RGListKit | RGListKit/CollectionViewController.swift | 1 | 1584 | //
// CollectionViewController.swift
// RGListKit
//
// Created by Ritesh Gupta on 01/01/17.
// Copyright © 2017 Ritesh Gupta. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
final class CollectionViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView! {
didSet {
listViewHolder = ReactiveDiffableListViewHolder(listView: collectionView, delegate: self)
}
}
var listViewHolder: ReactiveDiffableListViewHolder!
let items = MutableProperty<[SectionModel]?>(nil)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
listViewHolder.reactive.sections <~ items.producer.skipNil()
loadCacheData()
mockAPIData()
}
}
extension CollectionViewController {
func loadCacheData() {
let cells = (0..<50).map { "\($0)" }.map { CollectionCellModel(title: $0) }
let section = SectionModel(id: "section-one", cells: cells)
items.value = [section]
}
func mockAPIData() {
let delay = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: delay) {
let cells = (0..<50).filter { $0 % 2 == 0 }.map { "\($0)" }.map { CollectionCellModel(title: $0) }
let section = SectionModel(id: "section-one", cells: cells)
self.items.value = [section]
}
}
}
extension DiffableListViewHolder {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let vc = delegate as? CollectionViewController else { return }
print("CollectionViewController didSelectItemAt = \(indexPath.item)")
print(vc.view)
}
}
| mit | dc5b87f38c96cf42921acd40ea255944 | 26.77193 | 103 | 0.724574 | 3.851582 | false | false | false | false |
lucdion/aide-devoir | sources/AideDevoir/Classes/Domain/Observable.swift | 1 | 1983 | //
// Observable.swift
// PAP
//
// Created by Hugo Lefrancois on 2016-11-02.
//
// Copyright © 2016 BDC Mobility Development Practice. All rights reserved.
//
import Foundation
class ObservableToken<T> : Equatable {
fileprivate weak var observable: Observable<T>?
fileprivate let uuid = UUID().uuidString
init(observable: Observable<T>) {
self.observable = observable
}
func cancel() {
observable?.unRegister(self)
}
func ignore() {
// ignore token
}
public static func == (lhs: ObservableToken, rhs: ObservableToken) -> Bool {
return lhs.uuid == rhs.uuid
}
}
class Observable<T> {
typealias RegisterCallback = (_ token: ObservableToken<T>, _ value: T?) -> Void
typealias ObserverInfo = (token: ObservableToken<T>, callback: RegisterCallback, dispatchQueue: DispatchQueue)
fileprivate var observers: [ObserverInfo] = []
var value: T? {
didSet {
notify(value)
}
}
init(_ value: T? = nil) {
self.value = value
}
fileprivate func notify(_ newValue: T?) {
for observer in observers {
observer.dispatchQueue.async {
observer.callback(observer.token, newValue)
}
}
}
func register(_ dispatchQueue: DispatchQueue = DispatchQueue.main, callback: @escaping RegisterCallback) -> ObservableToken<T> {
let token = ObservableToken(observable: self)
observers.append(ObserverInfo(token: token, callback: callback, dispatchQueue: dispatchQueue))
if let lastNotifiedValue = value {
callback(token, lastNotifiedValue)
}
return token
}
fileprivate func unRegister(_ token: ObservableToken<T>) {
for (index, observer) in observers.enumerated() where observer.token == token {
observers.remove(at: index)
break
}
}
}
| apache-2.0 | e485a31c906be2a3545b604e0d6674b4 | 25.426667 | 132 | 0.602926 | 4.663529 | false | false | false | false |
nickdex/cosmos | code/search/src/binary_search/binary_search.swift | 8 | 1835 | // binary_search.swift
// Created by iraniya on 10/4/17.
// Part of Cosmos by OpenGenus Foundation
/**
Binary Search
Recursively splits the array in half until the value is found.
If there is more than one occurrence of the search key in the array, then
there is no guarantee which one it finds.
Note: The array must be sorted!
**/
import Foundation
// The recursive version of binary search.
public func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? {
if range.lowerBound >= range.upperBound {
return nil
} else {
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
if a[midIndex] > key {
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
} else if a[midIndex] < key {
return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
} else {
return midIndex
}
}
}
/**
The iterative version of binary search.
Notice how similar these functions are. The difference is that this one
uses a while loop, while the other calls itself recursively.
**/
public func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
var lowerBound = 0
var upperBound = a.count
while lowerBound < upperBound {
let midIndex = lowerBound + (upperBound - lowerBound) / 2
if a[midIndex] == key {
return midIndex
} else if a[midIndex] < key {
lowerBound = midIndex + 1
} else {
upperBound = midIndex
}
}
return nil
}
let numbers = [1,2,3,4,5]
let key = 5
var find = binarySearch(numbers, key: key, range: 0 ..< numbers.count) // gives 13
print("Position of \(key) is \(find)")
//printf("Position of %d is %d\n", find, binarySearch(arr, 0, size-1, find));
| gpl-3.0 | cbe5e4999fb0693867fb6e89c47e0805 | 27.671875 | 86 | 0.624523 | 3.929336 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | iOSDFULibrary/Classes/Utilities/Streams/DFUStream.swift | 1 | 3630 | /*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
internal let FIRMWARE_TYPE_SOFTDEVICE : UInt8 = 0x01
internal let FIRMWARE_TYPE_BOOTLOADER : UInt8 = 0x02
internal let FIRMWARE_TYPE_APPLICATION : UInt8 = 0x04
@objc open class DFUFirmwareSize : NSObject {
/// Size of the softdevice in bytes.
/// If not even, add it to the bootloader size to get size of
/// softdevice_bootloader.bin.
@objc open fileprivate(set) var softdevice : UInt32 = 0
/// Size of the bootloader in bytes.
/// If equal to 1 the ZIP contains SD+BL and size of SD or BL is not known exactly,
/// but their sum is known.
@objc open fileprivate(set) var bootloader : UInt32 = 0
/// Size of the application in bytes.
@objc open fileprivate(set) var application : UInt32 = 0
internal init(softdevice: UInt32, bootloader: UInt32, application: UInt32) {
self.softdevice = softdevice
self.bootloader = bootloader
self.application = application
}
}
/**
* The stream to read firmware from.
*/
internal protocol DFUStream {
/// Returns the 1-based number of the current part.
var currentPart: Int { get }
/// Number of parts to be sent.
var parts: Int { get }
/// The size of each component of the firmware.
var size: DFUFirmwareSize { get }
/// The size of each component of the firmware from the current part.
var currentPartSize: DFUFirmwareSize { get }
/// The type of the current part. See FIRMWARE_TYPE_* constants.
var currentPartType: UInt8 { get }
/// The firmware data to be sent to the DFU target.
var data: Data { get }
/// The whole init packet matching the current part.
/// Data may be longer than 20 bytes.
var initPacket: Data? { get }
/**
Returns `true` if there is another part to be send.
- returns: `True` if there is at least one byte of data not sent in the
current packet; `false` otherwise.
*/
func hasNextPart() -> Bool
/**
Switches the stream to the second part.
*/
func switchToNextPart()
}
| bsd-3-clause | 73e151ea8c619071207cdbf68d7b046b | 40.25 | 87 | 0.710193 | 4.410693 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/BitcoinChainKit/Domain/Models/Coincore/BitcoinChainTransactionFee.swift | 1 | 2115 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import FeatureTransactionDomain
import MoneyKit
import PlatformKit
import RxSwift
public struct BitcoinChainTransactionFee<Token: BitcoinChainToken>: TransactionFee, Decodable {
public static var cryptoType: HasPathComponent {
Token.coin.cryptoCurrency
}
public static var `default`: BitcoinChainTransactionFee<Token> {
switch Token.coin {
case .bitcoin:
return BitcoinChainTransactionFee<Token>(
regular: 5, priority: 11
)
case .bitcoinCash:
return BitcoinChainTransactionFee<Token>(
regular: 5,
priority: 11
)
}
}
public var regular: CryptoValue
public var priority: CryptoValue
enum CodingKeys: String, CodingKey {
case regular
case priority
case limits
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
let regularFee = try values.decode(Int.self, forKey: .regular)
let priorityFee = try values.decode(Int.self, forKey: .priority)
switch Token.coin {
case .bitcoin:
regular = CryptoValue(amount: BigInt(regularFee), currency: .bitcoin)
priority = CryptoValue(amount: BigInt(priorityFee), currency: .bitcoin)
case .bitcoinCash:
regular = CryptoValue(amount: BigInt(regularFee), currency: .bitcoinCash)
priority = CryptoValue(amount: BigInt(priorityFee), currency: .bitcoinCash)
}
}
init(regular: Int, priority: Int) {
switch Token.coin {
case .bitcoin:
self.regular = CryptoValue(amount: BigInt(regular), currency: .bitcoin)
self.priority = CryptoValue(amount: BigInt(priority), currency: .bitcoin)
case .bitcoinCash:
self.regular = CryptoValue(amount: BigInt(regular), currency: .bitcoinCash)
self.priority = CryptoValue(amount: BigInt(priority), currency: .bitcoinCash)
}
}
}
| lgpl-3.0 | 38ba414b13888908ffcfea714b3a0246 | 33.655738 | 95 | 0.642384 | 4.804545 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/Cells/LineItemTableViewCell/Pasteboard/PasteboardLabelContentPresenter.swift | 1 | 1426 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxRelay
import RxSwift
public final class PasteboardLabelContentPresenter: LabelContentPresenting {
public typealias PresentationState = LabelContent.State.Presentation
typealias PresentationDescriptors = LabelContent.Value.Presentation.Content.Descriptors
public let stateRelay = BehaviorRelay<PresentationState>(value: .loading)
public var state: Observable<PresentationState> {
stateRelay.asObservable()
}
// MARK: - Private Accessors
public let interactor: LabelContentInteracting
private let disposeBag = DisposeBag()
init(
interactor: PasteboardLabelContentInteracting,
descriptors: PresentationDescriptors
) {
self.interactor = interactor
let successDescriptors: PresentationDescriptors = .success(
fontSize: descriptors.fontSize,
accessibility: descriptors.accessibility
)
let descriptorObservable: Observable<PresentationDescriptors> = interactor.isPasteboarding
.map { $0 ? successDescriptors : descriptors }
.flatMap { Observable.just($0) }
Observable
.combineLatest(interactor.state, descriptorObservable)
.map { .init(with: $0.0, descriptors: $0.1) }
.bindAndCatch(to: stateRelay)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | 66052e9ed533a2fceb41cb6b509d8c7c | 33.756098 | 98 | 0.701754 | 5.501931 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/PasscodeSettingsViewController.swift | 1 | 11012 | //
// PasscodeSettingsViewController.swift
// TelegramMac
//
// Created by keepcoder on 10/01/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import InAppSettings
import SwiftSignalKit
import Postbox
import LocalAuthentication
private enum PasscodeEntry : Comparable, Identifiable {
case turnOn(sectionId:Int, viewType: GeneralViewType)
case turnOff(sectionId:Int, viewType: GeneralViewType)
case turnOnDescription(sectionId:Int, viewType: GeneralViewType)
case turnOffDescription(sectionId:Int, viewType: GeneralViewType)
case change(sectionId:Int, viewType: GeneralViewType)
case autoLock(sectionId:Int, time:Int32?, viewType: GeneralViewType)
case turnTouchId(sectionId:Int, enabled: Bool, viewType: GeneralViewType)
case section(sectionId:Int)
var stableId:Int {
switch self {
case .turnOn:
return 0
case .turnOff:
return 1
case .turnOnDescription:
return 2
case .turnOffDescription:
return 3
case .change:
return 4
case .autoLock:
return 5
case .turnTouchId:
return 6
case let .section(sectionId):
return (sectionId + 1) * 1000 - sectionId
}
}
var stableIndex:Int {
switch self {
case let .turnOn(sectionId, _):
return (sectionId * 1000) + stableId
case let .turnOff(sectionId, _):
return (sectionId * 1000) + stableId
case let .turnOnDescription(sectionId, _):
return (sectionId * 1000) + stableId
case let .turnOffDescription(sectionId, _):
return (sectionId * 1000) + stableId
case let .change(sectionId, _):
return (sectionId * 1000) + stableId
case let .autoLock(sectionId, _, _):
return (sectionId * 1000) + stableId
case let .turnTouchId(sectionId, _, _):
return (sectionId * 1000) + stableId
case let .section(sectionId):
return (sectionId + 1) * 1000 - sectionId
}
}
}
private func <(lhs:PasscodeEntry, rhs:PasscodeEntry) -> Bool {
return lhs.stableIndex < rhs.stableIndex
}
private func passcodeSettinsEntry(_ passcode: PostboxAccessChallengeData, passcodeSettings: PasscodeSettings, _ additional: AdditionalSettings) -> [PasscodeEntry] {
var entries:[PasscodeEntry] = []
var sectionId:Int = 1
entries.append(.section(sectionId: sectionId))
sectionId += 1
switch passcode {
case .none:
entries.append(.turnOn(sectionId: sectionId, viewType: .singleItem))
entries.append(.turnOnDescription(sectionId: sectionId, viewType: .textBottomItem))
case .plaintextPassword, let .numericalPassword:
entries.append(.turnOff(sectionId: sectionId, viewType: .firstItem))
entries.append(.change(sectionId: sectionId, viewType: .lastItem))
entries.append(.turnOffDescription(sectionId: sectionId, viewType: .textBottomItem))
entries.append(.section(sectionId: sectionId))
sectionId += 1
let context = LAContext()
entries.append(.autoLock(sectionId: sectionId, time: passcodeSettings.timeout, viewType: context.canUseBiometric ? .firstItem : .singleItem))
if context.canUseBiometric {
entries.append(.turnTouchId(sectionId: sectionId, enabled: additional.useTouchId, viewType: .lastItem))
}
}
entries.append(.section(sectionId: sectionId))
sectionId += 1
return entries
}
private let actionStyle:ControlStyle = blueActionButton
fileprivate func prepareTransition(left:[AppearanceWrapperEntry<PasscodeEntry>], right: [AppearanceWrapperEntry<PasscodeEntry>], initialSize:NSSize, arguments:PasscodeSettingsArguments) -> TableUpdateTransition {
let (removed, inserted, updated) = proccessEntriesWithoutReverse(left, right: right) { entry -> TableRowItem in
switch entry.entry {
case .section:
return GeneralRowItem(initialSize, height: 30, stableId: entry.stableId, viewType: .separator)
case let .turnOn(_, viewType):
return GeneralInteractedRowItem(initialSize, stableId: entry.stableId, name: strings().passcodeTurnOn, nameStyle: actionStyle, type: .none, viewType: viewType, action: {
arguments.turnOn()
})
case let .turnOff(_, viewType):
return GeneralInteractedRowItem(initialSize, stableId: entry.stableId, name: strings().passcodeTurnOff, nameStyle: actionStyle, type: .none, viewType: viewType, action: {
arguments.turnOff()
})
case let .change(_, viewType):
return GeneralInteractedRowItem(initialSize, stableId: entry.stableId, name: strings().passcodeChange, nameStyle: actionStyle, type: .none, viewType: viewType, action: {
arguments.change()
})
case let .turnOnDescription(_, viewType), let .turnOffDescription(_, viewType):
return GeneralTextRowItem(initialSize, stableId: entry.stableId, text: strings().passcodeControllerText, viewType: viewType)
case let .turnTouchId(_, enabled, viewType):
return GeneralInteractedRowItem(initialSize, stableId: entry.stableId, name: strings().passcodeUseTouchId, type: .switchable(enabled), viewType: viewType, action: {
arguments.toggleTouchId(!enabled)
})
case let .autoLock(sectionId: _, time, viewType):
var text:String
if let time = time {
if time < 60 {
text = strings().timerSecondsCountable(Int(time))
} else if time < 60 * 60 {
text = strings().timerMinutesCountable(Int(time / 60))
} else if time < 60 * 60 * 24 {
text = strings().timerHoursCountable(Int(time / 60) / 60)
} else {
text = strings().timerDaysCountable(Int(time / 60) / 60 / 24)
}
text = strings().passcodeAutoLockIfAway(text)
} else {
text = strings().passcodeAutoLockDisabled
}
return GeneralInteractedRowItem(initialSize, stableId: entry.stableId, name: strings().passcodeAutolock, type: .context(text), viewType: viewType, action: {
arguments.ifAway()
})
}
}
return TableUpdateTransition(deleted: removed, inserted: inserted, updated: updated, animated: true)
}
private final class PasscodeSettingsArguments {
let context: AccountContext
let turnOn:()->Void
let turnOff:()->Void
let change:()->Void
let ifAway:()->Void
let toggleTouchId:(Bool)->Void
init(_ context: AccountContext, turnOn: @escaping()->Void, turnOff: @escaping()->Void, change:@escaping()->Void, ifAway: @escaping()-> Void, toggleTouchId:@escaping(Bool)->Void) {
self.context = context
self.turnOn = turnOn
self.turnOff = turnOff
self.change = change
self.ifAway = ifAway
self.toggleTouchId = toggleTouchId
}
}
class PasscodeSettingsViewController: TableViewController {
private let disposable = MetaDisposable()
private func show(mode: PasscodeMode) {
self.navigationController?.push(PasscodeController(sharedContext: context.sharedContext, mode: mode))
}
deinit {
disposable.dispose()
}
func updateAwayTimeout(_ timeout:Int32?) {
disposable.set(updatePasscodeSettings(context.sharedContext.accountManager, {
$0.withUpdatedTimeout(timeout)
}).start())
}
func showIfAwayOptions() {
if let item = genericView.item(stableId: Int(5)), let view = (genericView.viewNecessary(at: item.index) as? GeneralInteractedRowView)?.textView {
var items:[ContextMenuItem] = []
items.append(ContextMenuItem(strings().passcodeAutoLockDisabled, handler: { [weak self] in
self?.updateAwayTimeout(nil)
}))
items.append(ContextMenuItem(strings().passcodeAutoLockIfAway(strings().timerMinutesCountable(1)), handler: { [weak self] in
self?.updateAwayTimeout(60)
}))
items.append(ContextMenuItem(strings().passcodeAutoLockIfAway(strings().timerMinutesCountable(5)), handler: { [weak self] in
self?.updateAwayTimeout(60 * 5)
}))
items.append(ContextMenuItem(strings().passcodeAutoLockIfAway(strings().timerHoursCountable(1)), handler: { [weak self] in
self?.updateAwayTimeout(60 * 60)
}))
items.append(ContextMenuItem(strings().passcodeAutoLockIfAway(strings().timerHoursCountable(5)), handler: { [weak self] in
self?.updateAwayTimeout(60 * 60 * 5)
}))
if let event = NSApp.currentEvent {
let menu = ContextMenu()
for item in items {
menu.addItem(item)
}
let value = AppMenu(menu: menu)
value.show(event: event, view: view)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let context = self.context
let arguments = PasscodeSettingsArguments(context, turnOn: { [weak self] in
self?.show(mode: .install)
}, turnOff: { [weak self] in
self?.show(mode: .disable)
}, change: { [weak self] in
self?.show(mode: .change)
}, ifAway: { [weak self] in
self?.showIfAwayOptions()
}, toggleTouchId: { enabled in
_ = updateAdditionalSettingsInteractively(accountManager: context.sharedContext.accountManager, { current -> AdditionalSettings in
return current.withUpdatedTouchId(enabled)
}).start()
})
let initialSize = self.atomicSize.modify({$0})
let previous:Atomic<[AppearanceWrapperEntry<PasscodeEntry>]> = Atomic(value: [])
genericView.merge(with: combineLatest(queue: prepareQueue, context.sharedContext.accountManager.accessChallengeData(), passcodeSettingsView(context.sharedContext.accountManager), appearanceSignal, additionalSettings(accountManager: context.sharedContext.accountManager)) |> map { passcode, passcodeSettings, appearance, additional in
let entries = passcodeSettinsEntry(passcode.data, passcodeSettings: passcodeSettings, additional).map{AppearanceWrapperEntry(entry: $0, appearance: appearance)}
return prepareTransition(left: previous.swap(entries), right: entries, initialSize: initialSize, arguments: arguments)
} |> deliverOnMainQueue)
readyOnce()
}
}
| gpl-2.0 | 12dfbccc8662b5cd688e9fd4a6d6e8b9 | 40.708333 | 341 | 0.629825 | 4.973351 | false | false | false | false |
abertelrud/swift-package-manager | Sources/PackageModel/Sanitizers.swift | 2 | 2328 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
/// Available runtime sanitizers.
public enum Sanitizer: String, Encodable, CaseIterable {
case address
case thread
case undefined
case scudo
/// Return an established short name for a sanitizer, e.g. "asan".
public var shortName: String {
switch self {
case .address: return "asan"
case .thread: return "tsan"
case .undefined: return "ubsan"
case .scudo: return "scudo"
}
}
}
/// A set of enabled runtime sanitizers.
public struct EnabledSanitizers: Encodable {
/// A set of enabled sanitizers.
public let sanitizers: Set<Sanitizer>
public init(_ sanitizers: Set<Sanitizer> = []) {
// FIXME: We need to throw from here if given sanitizers can't be
// enabled. For e.g., it is illegal to enable thread and address
// sanitizers together.
self.sanitizers = sanitizers
}
/// Sanitization flags for the C family compiler (C/C++).
public func compileCFlags() -> [String] {
return sanitizers.map({ "-fsanitize=\($0.rawValue)" })
}
/// Sanitization flags for the Swift compiler.
public func compileSwiftFlags() -> [String] {
return sanitizers.map({ "-sanitize=\($0.rawValue)" })
}
/// Sanitization flags for the Swift linker and compiler are the same so far.
public func linkSwiftFlags() -> [String] {
return compileSwiftFlags()
}
public var isEmpty: Bool {
return sanitizers.isEmpty
}
enum CodingKeys: String, CodingKey {
case sanitizers
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(sanitizers.sorted{ $0.rawValue < $1.rawValue }, forKey: .sanitizers)
}
}
| apache-2.0 | a4f38742e3cd26497251a9a172911a62 | 31.333333 | 97 | 0.605241 | 4.409091 | false | false | false | false |
peterfennema/AmazonSwiftStarter | AmazonSwiftStarter/AMZConstants.swift | 1 | 652 | //
// AMZConstants.swift
// AmazonSwiftStarter
//
// Created by Peter Fennema on 08/02/16.
// Copyright © 2016 Peter Fennema. All rights reserved.
//
import Foundation
import AWSCore
class AMZConstants {
static let COGNITO_REGIONTYPE = AWSRegionType.EUWest1 // Replace by your own
static let COGNITO_IDENTITY_POOL_ID = "YOUR_COGNITO_IDENTITY_POOL_ID" // Replace by your own
static let DEFAULT_SERVICE_REGION = AWSRegionType.EUWest1 // Replace by your own
static let S3BUCKET_USERS = "YOUR_S3BUCKET_USERS" // Replace by your own
static let DYNAMODB_USERS_TABLE = "YOUR_DYNAMODB_USERS_TABLE" // Replace by your own
}
| mit | 7ba514dd2f72be1cdc8a8010734598cc | 31.55 | 96 | 0.721966 | 3.255 | false | false | false | false |
urbanthings/urbanthings-sdk-apple | Demo/ViewControllers/StopsMapViewController.swift | 1 | 4658 | //
// StopsMapViewController.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 06/05/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import UIKit
import UTAPI
import MapKit
private let MarkerReuseIdentifier = "MarkerReuseIdentifier"
/// Adapter to make a TransitStop usabled as a map MKAnnotation
class TransitStopAdapter : NSObject, MKAnnotation {
let stop:UTAPI.TransitStop
init(stop:UTAPI.TransitStop) {
self.stop = stop
}
@objc var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: self.stop.location.latitude, longitude: self.stop.location.longitude)
}
@objc var title:String? {
return self.stop.name
}
@objc var subtitle:String? = "Fetching..."
}
class StopsMapViewController : UIViewController, MKMapViewDelegate {
var dataObserver:AnyObject?
var locationObserver:AnyObject?
var selectionObserver:AnyObject?
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.dataObserver = NotificationCenter.default.addObserver(name: StopDataUpdated, object: nil, queue: nil) { [weak self] _ in
let markers = StopsModel.sharedInstance.data.map { TransitStopAdapter(stop: $0) }
OperationQueue.main.addOperation {
self?.updateMap(markers: markers)
}
}
self.locationObserver = NotificationCenter.default.addObserver(name: LocationChanged, object: nil, queue: OperationQueue.main) { [weak self] _ in
self?.updateLocation(location: StopsModel.sharedInstance.location!)
}
self.selectionObserver = NotificationCenter.default.addObserver(name: TransitStopSelected, object: nil, queue: OperationQueue.main) { [weak self] note in
if (note.object as AnyObject) !== self {
if let annotation = self?.mapView.annotations.filter({ ($0 as? TransitStopAdapter)?.stop.primaryCode == (note.userInfo?[TransitStopPrimaryCode] as? String) }).first {
self?.mapView.selectAnnotation(annotation, animated: true)
}
}
}
OperationQueue.main.addOperation {
self.updateLocation(location: StopsModel.sharedInstance.location!)
}
}
func updateMap(markers:[TransitStopAdapter]) {
self.mapView.removeAnnotations(self.mapView.annotations)
self.mapView.addAnnotations(markers)
}
func updateLocation(location:Location) {
let coord = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
let camera = MKMapCamera(lookingAtCenter: coord,
fromDistance: 5000,
pitch: 0,
heading: 0)
self.mapView.setCamera(camera, animated: true)
}
var resourceRequest:UrbanThingsAPIRequest?
// MARK: MKMapViewDelegate
@objc func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotation = view.annotation as? TransitStopAdapter {
NotificationCenter.default.post(name: Notification.Name(TransitStopSelected),
object: self,
userInfo: [TransitStopPrimaryCode:annotation.stop.primaryCode])
self.resourceRequest?.cancel()
self.resourceRequest = StopsModel.sharedInstance.getStopResources(stop: annotation.stop) { msg in
OperationQueue.main.addOperation {
(view.annotation as? TransitStopAdapter)?.subtitle = msg
}
self.resourceRequest = nil
}
}
}
@objc func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let view = mapView.dequeueReusableAnnotationView(withIdentifier: MarkerReuseIdentifier) as? MKPinAnnotationView ?? MKPinAnnotationView(annotation: annotation, reuseIdentifier: MarkerReuseIdentifier)
view.annotation = annotation
view.canShowCallout = true
if (annotation as? TransitStopAdapter)?.stop.placePointType == PlacePointType.CycleHireDock {
view.pinTintColor = UIColor.red
} else {
view.pinTintColor = UIColor.orange
}
return view
}
@objc func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
resourceRequest?.cancel()
resourceRequest = nil
}
}
| apache-2.0 | fe878fe2b75dda77c2dd486575fd339a | 38.803419 | 206 | 0.635817 | 5.23847 | false | false | false | false |
jeroendesloovere/examples-swift | Swift-Playgrounds/Initialization.playground/section-1.swift | 1 | 9137 | // Initialization
struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
var f = Fahrenheit()
println("The default temperature is \(f.temperature)° Fahrenheit")
// Customizing Initialization
// Initialization Parameters
struct Celsius {
var temperatureInCelsius: Double = 0.0
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
struct Color {
let red = 0.0, green = 0.0, blue = 0.0
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
}
let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
//let verGreen = Color(0.0, 1.0, 0.0)
// Compile time error because external names for parameters were omitted
// Optinoal Property Types
class SurveyQuestion {
var text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
println(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
cheeseQuestion.response = "Yes, I do like cheese."
// Modifying Constant Properties during Initialization
class SurveyQuestion2 {
let text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
println(text)
}
}
let beetsQuestion = SurveyQuestion2(text: "How about beets?")
beetsQuestion.ask()
beetsQuestion.response = "I also like beets. (But not with cheese.)"
// Default Initializer
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
// Memberwise Initializers for Structure Types
// Because both stored properties have a default value, the Size structure automatically receives an init(width:height:) memberwise initializer, which you can use to initialize a new Size instance:
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
// Initializer Delegation for Value Types
struct Size2 {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size2()
init() {}
init(origin: Point, size: Size2) {
self.origin = origin
self.size = size
}
init(center: Point, size: Size2) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let basicRect = Rect()
let originRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size2(width: 5.0, height: 5.0))
let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size2(width: 3.0, height: 3.0))
// Class Inheritance and Initialization
// Rule 1
// Designated initializers must call a designated initializer from their immediate superclass
// Rule 2
// Convenience initializers must call another initializer available in the same class
// Rule 3
// Convenience initializers must ultimately end up calling a designated initializer
// Designated initializers must always delegate up. Convenience initializers must always delegate across
// Initialization is a 2 stage process. There are several safety checks that the compiler performs
// Safety Check 1
// A deignated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass
// Safety Check 2
// A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn't, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization
// Safety Check 3
// A convenience initializer must delegate to another initializer before assigning a value to any property (including properties defined by the same class). If it doesn't, the new value the convenience initializer assigns will be overwritten by its own class's designated initializer.
// Safety Check 4
// An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.
// Two-Phase initialization
// Phase 1
// - A designated or convenience initializer is called on a class
// - Memory for a new instance of that class is allocated. The memory is not yet initialized.
// - A designated initializer for that class confirms that all stored properties introduced by that class have a value. The memory for these stored properties is now initialized.
// - The designated initializer hands off to a superclass initializer to perform the same task for its own stored properties.
// - This continues up the class inheritance chain until the top of the chain is reached.
// - Once the top of the chain is reached, and the final class in the chain has ensured that all of its stored properties have a value, the instance's memory is considered to be fully initialized, and phase 1 is complete.
//
// Phase 2
// - Working back down from the top of the chain, each designated initializer in the chain has the option to customize the instance further. Initializers are now able to access self and can modify its properties, call its instance methods, and so on.
// - Finally, any convenience initializers in the chain have the option to customize the instance and to work with self.
// Automatic Initializers
// Rule 1
// If your subclass doesn't define any designated initializers, it automatically inherits all of its superclass designated initializers
// Rule 2
// If your subclass provides an implementaction of all of its superclass designated initializers- either by inheriting them as per rule 1, or by providing a custom implementation as part of its definitition- the it automatically inherits all of the superclass convenience initializers.
// Designated and Convenience Initializers in Action
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
let namedMeat = Food(name: "Bacon")
let mysteryMeat = Food()
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
convenience override init(name: String) {
self.init(name: name, quantity: 1)
}
}
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)
// In this example, the superclass for RecipeIngredient is Food, which has a single convenience initializer called init(). This initializer is therefore inherited by RecipeIngredient. The inherited version of init() functions in exactly the same way as the Food version, except that it delegates to the RecipeIngredient version of init(name: String) rather than the Food version.
let oneMysteryItem = RecipeIngredient()
class ShoppingListItem2: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) x \(name)"
output += purchased ? " √" : " ✘"
return output
}
}
// Because ShoppingListItem2 provides a default value for all of the properties it introduces and does not define any initializers itself, ShoppingListItem automatically inherits all of the designated and convenience initializers from its superclass. ShoppingListItem2(name: "Eggs, quantity: 6),
var breakfastList = [
ShoppingListItem2(),
ShoppingListItem2(name: "Bacon"),
ShoppingListItem2(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
println(item.description)
}
// Setting a default Property Value with a Closure or Function
/*
class SomeClass {
let someProperty: SomeType = {
// create a default value for someProperty inside this closure
// someValue must be of the same type as SomeType
return someValue
}()
}
*/
// Note that the closure’s end curly brace is followed by an empty pair of parentheses. This tells Swift to execute the closure immediately. If you omit these parentheses, you are trying to assign the closure itself to the property, and not the return value of the closure.
struct Checkerboard {
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...10 {
for j in 1...10 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}()
func squareIsBlackAtRow(row: Int, column: Int) -> Bool {
return boardColors[(row * 10) + column]
}
}
let board = Checkerboard()
println(board.squareIsBlackAtRow(0, column: 1))
println(board.squareIsBlackAtRow(9, column: 9))
| mit | a0dac7a12ad9ca6b6aac4a744bb626e5 | 37.200837 | 380 | 0.711939 | 4.304573 | false | false | false | false |
cwwise/CWWeChat | CWWeChat/MainClass/Contacts/ContactSetting/CWContactSettingController.swift | 2 | 1918 | //
// CWContactSettingController.swift
// CWWeChat
//
// Created by wei chen on 2017/9/5.
// Copyright © 2017年 cwwise. All rights reserved.
//
import UIKit
class CWContactSettingController: CWBaseTableViewController {
lazy var tableViewManager: CWTableViewManager = {
let tableViewManager = CWTableViewManager(tableView: self.tableView)
tableViewManager.delegate = self
tableViewManager.dataSource = self
return tableViewManager
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "资料设置"
setupData()
}
func setupData() {
let item1 = CWTableViewItem(title: "设置备注及标签")
tableViewManager.addSection(itemsOf: [item1])
let item2 = CWTableViewItem(title: "把她推荐给朋友")
tableViewManager.addSection(itemsOf: [item2])
let item3 = CWBoolItem(title: "设置为星标用户", value: true)
tableViewManager.addSection(itemsOf: [item3])
let item4 = CWBoolItem(title: "不让她看我的朋友圈", value: true)
let item5 = CWBoolItem(title: "不看她的朋友圈 ", value: true)
tableViewManager.addSection(itemsOf: [item4, item5])
let item6 = CWBoolItem(title: "加入黑名单", value: true)
let item7 = CWTableViewItem(title: "投诉")
tableViewManager.addSection(itemsOf: [item6, item7])
let frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 80)
let footerView = UIView(frame: frame)
self.tableView.tableFooterView = footerView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CWContactSettingController: CWTableViewManagerDelegate, CWTableViewManagerDataSource {
}
| mit | 9dd5616bb1e65820959daa70a2128187 | 27.873016 | 96 | 0.647609 | 4.230233 | false | false | false | false |
Aynelgul/finalproject | finalproject/LoginViewController.swift | 1 | 4819 | //
// LoginViewController.swift
// finalproject
//
// Created by Aynel Gül on 16-01-17.
// Copyright © 2017 Aynel Gül. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class LoginViewController: UIViewController {
// MARK: - Outlets.
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
// MARK: - viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
// Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
if let user = FIRAuth.auth()?.currentUser {
self.signedIn(user)
}
// Listener for state change of user.
FIRAuth.auth()!.addStateDidChangeListener() { auth, user in
if user != nil {
self.performSegue(withIdentifier: "gotoMenu", sender: nil)
}
}
}
// MARK: - Actions.
@IBAction func loginButtonDidTouch(_ sender: UIButton) {
guard let email = emailTextField.text, let password = passwordTextField.text else { return
}
FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
if let error = error {
print(error.localizedDescription)
self.presentAlert(title: "Oops!", message: "That e-mailadress and/or password is not correct! Try again or sign up.")
return
}
self.signedIn(user!)
}
}
@IBAction func signupButtonDidTouch(_ sender: UIButton) {
let alert = UIAlertController(title: "Sign Up",
message: "Sign Up",
preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { action in
let emailField = alert.textFields![0]
let passwordField = alert.textFields![1]
self.createNewUser(email: emailField.text!, password: passwordField.text!)
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .default)
alert.addTextField { textEmail in
textEmail.placeholder = "Enter your email"
}
alert.addTextField { textPassword in
textPassword.isSecureTextEntry = true
textPassword.placeholder = "Enter your password"
}
alert.addAction(cancelAction)
alert.addAction(saveAction)
present(alert, animated: true, completion: nil)
}
// MARK: - Functions.
private func signedIn(_ user: FIRUser?) {
emailTextField.text = ""
passwordTextField.text = ""
}
private func createNewUser(email: String, password: String) -> Void {
FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in
if let error = error {
print(error.localizedDescription)
if error.localizedDescription == "The email address is already in use by another account." {
self.presentAlert(title: "Oops!", message: "The email address is already in use by another account.")
}
if error.localizedDescription == "The password must be 6 characters long or more." {
self.presentAlert(title: "Oops!", message: "The password must be 6 characters long or more.")
}
self.presentAlert(title: "Oops!", message: "Sign up failed. Please fill in all fields or check your e-mailadress.")
return
}
let ref = FIRDatabase.database().reference(withPath: "Users")
let newUser = User(uid: (user?.uid)!, email: email)
let userRef = ref.child((user?.uid)!)
userRef.setValue(newUser.toAnyObject())
}
}
private func presentAlert(title: String, message: String) -> Void {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func dismissKeyboard() {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | b1f5340b2e91c0552ec5040430426db5 | 35.484848 | 134 | 0.575374 | 5.292308 | false | false | false | false |
per-dalsgaard/20-apps-in-20-weeks | App 09 - RainyShinyCloudy/RainyShinyCloudy/WeatherViewController.swift | 1 | 3672 | //
// WeatherViewController.swift
// RainyShinyCloudy
//
// Created by Per Kristensen on 13/04/2017.
// Copyright © 2017 Per Dalsgaard. All rights reserved.
//
import UIKit
import Alamofire
import CoreLocation
class WeatherViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var currentTempLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var currentWeatherImageView: UIImageView!
@IBOutlet weak var currentWeatherTypeLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
let locationManager = CLLocationManager()
var currentLocation: CLLocation!
var currentWeather = CurrentWeather()
var forecast: Forecast!
var forecasts = [Forecast]()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startMonitoringSignificantLocationChanges()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
locationAuthStatus()
}
func locationAuthStatus() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
let currentLocation = locationManager.location
Location.sharedInstance.longitude = currentLocation?.coordinate.longitude
Location.sharedInstance.latitude = currentLocation?.coordinate.latitude
print(CURRENT_WEATHER_URL)
print(FORECAST_URL)
currentWeather.downloadWeatherDetails {
self.downloadForecastData {
self.updateUI()
}
}
} else {
locationManager.requestWhenInUseAuthorization()
locationAuthStatus()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forecasts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherCell", for: indexPath) as? WeatherTableViewCell {
cell.configureCell(forecast: forecasts[indexPath.row])
return cell
}
return UITableViewCell()
}
func downloadForecastData(completed: @escaping DownloadComplete) {
let forecastUrl = URL(string: FORECAST_URL)!
Alamofire.request(forecastUrl).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let list = dict["list"] as? [Dictionary<String, AnyObject>] {
for forecastDict in list {
let forecast = Forecast(weatherDict: forecastDict)
self.forecasts.append(forecast)
}
self.forecasts.remove(at: 0)
}
}
completed()
}
}
func updateUI() {
dateLabel.text = currentWeather.formattedDate
currentTempLabel.text = "\(currentWeather.formattedTemp)°"
currentWeatherTypeLabel.text = currentWeather.weatherType
locationLabel.text = currentWeather.cityName
currentWeatherImageView.image = UIImage(named: currentWeather.weatherType)
tableView.reloadData()
}
}
| mit | d5fc9eac1321821ad08d08afdcfdd542 | 32.981481 | 125 | 0.640872 | 5.919355 | false | false | false | false |
yangboz/SwiftTutorials | CookieCrunch/CookieCrunch/GameViewController.swift | 1 | 5524 | //
// GameViewController.swift
// CookieCrunch
//
// Created by Matthijs on 19-06-14.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
import UIKit
import SpriteKit
import AVFoundation
class GameViewController: UIViewController {
// The scene draws the tiles and cookie sprites, and handles swipes.
var scene: GameScene!
// The level contains the tiles, the cookies, and most of the gameplay logic.
// Needs to be ! because it's not set in init() but in viewDidLoad().
var level: Level!
var movesLeft: Int = 0
var score: Int = 0
@IBOutlet var targetLabel: UILabel
@IBOutlet var movesLabel: UILabel
@IBOutlet var scoreLabel: UILabel
@IBOutlet var gameOverPanel: UIImageView
@IBOutlet var shuffleButton: UIButton
var tapGestureRecognizer: UITapGestureRecognizer!
var backgroundMusic: AVAudioPlayer!
override func prefersStatusBarHidden() -> Bool {
return true
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
}
override func viewDidLoad() {
super.viewDidLoad()
// Configure the view.
let skView = view as SKView
skView.multipleTouchEnabled = false
// Create and configure the scene.
scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .AspectFill
// Load the level.
level = Level(filename: "Level_1")
scene.level = level
scene.addTiles()
scene.swipeHandler = handleSwipe
// Hide the game over panel from the screen.
gameOverPanel.hidden = true
shuffleButton.hidden = true
// Present the scene.
skView.presentScene(scene)
// Load and start background music.
let url = NSBundle.mainBundle().URLForResource("Mining by Moonlight", withExtension: "mp3")
backgroundMusic = AVAudioPlayer(contentsOfURL: url, error: nil)
backgroundMusic.numberOfLoops = -1
backgroundMusic.play()
// Let's start the game!
beginGame()
}
func beginGame() {
movesLeft = level.maximumMoves
score = 0
updateLabels()
level.resetComboMultiplier()
scene.animateBeginGame() {
self.shuffleButton.hidden = false
}
shuffle()
}
func shuffle() {
// Delete the old cookie sprites, but not the tiles.
scene.removeAllCookieSprites()
// Fill up the level with new cookies, and create sprites for them.
let newCookies = level.shuffle()
scene.addSpritesForCookies(newCookies)
}
// This is the swipe handler. MyScene invokes this function whenever it
// detects that the player performs a swipe.
func handleSwipe(swap: Swap) {
// While cookies are being matched and new cookies fall down to fill up
// the holes, we don't want the player to tap on anything.
view.userInteractionEnabled = false
if level.isPossibleSwap(swap) {
level.performSwap(swap)
scene.animateSwap(swap, completion: handleMatches)
} else {
scene.animateInvalidSwap(swap) {
self.view.userInteractionEnabled = true
}
}
}
// This is the main loop that removes any matching cookies and fills up the
// holes with new cookies. While this happens, the user cannot interact with
// the app.
func handleMatches() {
// Detect if there are any matches left.
let chains = level.removeMatches()
// If there are no more matches, then the player gets to move again.
if chains.count == 0 {
beginNextTurn()
return
}
// First, remove any matches...
scene.animateMatchedCookies(chains) {
// Add the new scores to the total.
for chain in chains {
self.score += chain.score
}
self.updateLabels()
// ...then shift down any cookies that have a hole below them...
let columns = self.level.fillHoles()
self.scene.animateFallingCookies(columns) {
// ...and finally, add new cookies at the top.
let columns = self.level.topUpCookies()
self.scene.animateNewCookies(columns) {
// Keep repeating this cycle until there are no more matches.
self.handleMatches()
}
}
}
}
func beginNextTurn() {
level.resetComboMultiplier()
level.detectPossibleSwaps()
view.userInteractionEnabled = true
decrementMoves()
}
func updateLabels() {
targetLabel.text = NSString(format: "%ld", level.targetScore)
movesLabel.text = NSString(format: "%ld", movesLeft)
scoreLabel.text = NSString(format: "%ld", score)
}
func decrementMoves() {
--movesLeft
updateLabels()
if score >= level.targetScore {
gameOverPanel.image = UIImage(named: "LevelComplete")
showGameOver()
} else if movesLeft == 0 {
gameOverPanel.image = UIImage(named: "GameOver")
showGameOver()
}
}
func showGameOver() {
gameOverPanel.hidden = false
scene.userInteractionEnabled = false
shuffleButton.hidden = true
scene.animateGameOver() {
self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideGameOver")
self.view.addGestureRecognizer(self.tapGestureRecognizer)
}
}
func hideGameOver() {
view.removeGestureRecognizer(tapGestureRecognizer)
tapGestureRecognizer = nil
gameOverPanel.hidden = true
scene.userInteractionEnabled = true
beginGame()
}
@IBAction func shuffleButtonPressed(AnyObject) {
shuffle()
// Pressing the shuffle button costs a move.
decrementMoves()
}
}
| mit | 45cf6583e3da63401f3c00e65face66f | 25.430622 | 95 | 0.68139 | 4.535304 | false | false | false | false |
ios-studio/Typesetter | Typesetter/CSV.swift | 1 | 1726 | //
// CSV.swift
// Typesetter
//
// Created by Beat Richartz on 06/02/2016.
// Copyright © 2016 Beat Richartz. All rights reserved.
//
import Foundation
class CSV {
let headers: [String]
let columns: [String: [String]]
fileprivate static let delimiter = CharacterSet(charactersIn: ",")
fileprivate static func getColumns(_ headers: [String], lines: [String]) -> [String: [String]] {
return Array(lines)[1..<lines.count].reduce([String: [String]]()) { columns, line in
var newColumns = columns
let row = line.components(separatedBy: CharacterSet(charactersIn: ","))
for (index, header) in headers.enumerated() {
if columns[header] == nil {
newColumns[header] = [row[index]]
} else {
newColumns[header]?.append(row[index])
}
}
return newColumns
}
}
init?(contentsOfFile file: String) {
let contents: String
do {
contents = try String(contentsOfFile: file)
} catch {
self.headers = []
self.columns = [:]
return nil
}
let newline = CharacterSet.newlines
var lines: [String] = []
contents.trimmingCharacters(in: newline).enumerateLines { line, stop in lines.append(line)
}
guard lines.count > 1 else {
self.headers = []
self.columns = [:]
return nil
}
let headers = lines[0].components(separatedBy: CSV.delimiter)
self.headers = headers
self.columns = CSV.getColumns(headers, lines: lines)
}
}
| mit | 6bdbc91e8233b582c9315500d52c50d6 | 29.263158 | 100 | 0.536812 | 4.662162 | false | false | false | false |
rugheid/Swift-MathEagle | MathEagleTests/Statistics/RandomTests.swift | 1 | 58496 | //
// RandomTests.swift
// MathEagle
//
// Created by Rugen Heidbuchel on 01/04/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
import Cocoa
import XCTest
import MathEagle
class RandomTests: XCTestCase {
var N = 10000
var MAX = 100
func testRangeConstructors() {
print(String(describing:type(of:10.0..<20.0)))
print(String(describing:type(of:10.0...20.0)))
print(String(describing:type(of:10..<20)))
print(String(describing:type(of:10...20)))
XCTAssert((10.0..<20.0 as Any) is Range<Double>)
XCTAssert((10.0...20.0 as Any) is ClosedRange<Double>)
XCTAssert((10..<20 as Any) is CountableRange<Int>)
XCTAssert((10...20 as Any) is CountableClosedRange<Int>)
}
// MARK: random within upperBound
func testRandomInt() {
for _ in 1...N {
let x=Int.random()
XCTAssert((x as Any) is Int)
XCTAssert(0<=x && x<=1)
}
let m=Int.random(Int(MAX))
XCTAssert((m as Any) is Int)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=Int.random(m)
XCTAssert((x as Any) is Int)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=Int.random(-m)
XCTAssert((x as Any) is Int)
XCTAssert(-m<=x && x<=0)
}
}
func testRandomInt8() {
for _ in 1...N {
let x=Int8.random()
XCTAssert((x as Any) is Int8)
XCTAssert(0<=x && x<=1)
}
let m=Int8.random(Int8(MAX))
XCTAssert((m as Any) is Int8)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=Int8.random(m)
XCTAssert((x as Any) is Int8)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=Int8.random(-m)
XCTAssert((x as Any) is Int8)
XCTAssert(-m<=x && x<=0)
}
}
func testRandomInt16() {
for _ in 1...N {
let x=Int16.random()
XCTAssert((x as Any) is Int16)
XCTAssert(0<=x && x<=1)
}
let m=Int16.random(Int16(MAX))
XCTAssert((m as Any) is Int16)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=Int16.random(m)
XCTAssert((x as Any) is Int16)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=Int16.random(-m)
XCTAssert((x as Any) is Int16)
XCTAssert(-m<=x && x<=0)
}
}
func testRandomInt32() {
for _ in 1...N {
let x=Int32.random()
XCTAssert((x as Any) is Int32)
XCTAssert(0<=x && x<=1)
}
let m=Int32.random(Int32(MAX))
XCTAssert((m as Any) is Int32)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=Int32.random(m)
XCTAssert((x as Any) is Int32)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=Int32.random(-m)
XCTAssert((x as Any) is Int32)
XCTAssert(-m<=x && x<=0)
}
}
func testRandomInt64() {
for _ in 1...N {
let x=Int64.random()
XCTAssert((x as Any) is Int64)
XCTAssert(0<=x && x<=1)
}
let m=Int64.random(Int64(MAX))
XCTAssert((m as Any) is Int64)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=Int64.random(m)
XCTAssert((x as Any) is Int64)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=Int64.random(-m)
XCTAssert((x as Any) is Int64)
XCTAssert(-m<=x && x<=0)
}
}
func testRandomUInt() {
for _ in 1...N {
let x=UInt.random()
XCTAssert((x as Any) is UInt)
XCTAssert(0<=x && x<=1)
}
let m=UInt.random(UInt(MAX))
XCTAssert((m as Any) is UInt)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=UInt.random(m)
XCTAssert((x as Any) is UInt)
XCTAssert(0<=x && x<=m)
}
}
func testRandomUInt8() {
for _ in 1...N {
let x=UInt8.random()
XCTAssert((x as Any) is UInt8)
XCTAssert(0<=x && x<=1)
}
let m=UInt8.random(UInt8(MAX))
XCTAssert((m as Any) is UInt8)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=UInt8.random(m)
XCTAssert((x as Any) is UInt8)
XCTAssert(0<=x && x<=m)
}
}
func testRandomUInt16() {
for _ in 1...N {
let x=UInt16.random()
XCTAssert((x as Any) is UInt16)
XCTAssert(0<=x && x<=1)
}
let m=UInt16.random(UInt16(MAX))
XCTAssert((m as Any) is UInt16)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=UInt16.random(m)
XCTAssert((x as Any) is UInt16)
XCTAssert(0<=x && x<=m)
}
}
func testRandomUInt32() {
for _ in 1...N {
let x=UInt32.random()
XCTAssert((x as Any) is UInt32)
XCTAssert(0<=x && x<=1)
}
let m=UInt32.random(UInt32(MAX))
XCTAssert((m as Any) is UInt32)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=UInt32.random(m)
XCTAssert((x as Any) is UInt32)
XCTAssert(0<=x && x<=m)
}
}
func testRandomUInt64() {
for _ in 1...N {
let x=UInt64.random()
XCTAssert((x as Any) is UInt64)
XCTAssert(0<=x && x<=1)
}
let m=UInt64.random(UInt64(MAX))
XCTAssert((m as Any) is UInt64)
XCTAssert(0<=m && m<=MAX)
for _ in 1...N {
let x=UInt64.random(m)
XCTAssert((x as Any) is UInt64)
XCTAssert(0<=x && x<=m)
}
}
func testRandomFloat() {
for _ in 1...N {
let x=Float.random()
XCTAssert((x as Any) is Float)
XCTAssert(0<=x && x<=1)
}
let m=Float.random(Float(MAX))
XCTAssert((m as Any) is Float)
XCTAssert(0<=m && m<=Float(MAX))
for _ in 1...N {
let x=Float.random(m)
XCTAssert((x as Any) is Float)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=Float.random(-m)
XCTAssert((x as Any) is Float)
XCTAssert(-m<=x && x<=0)
}
}
func testRandomDouble() {
for _ in 1...N {
let x=Double.random()
XCTAssert((x as Any) is Double)
XCTAssert(0<=x && x<=1)
}
let m=Double.random(Double(MAX))
XCTAssert((m as Any) is Double)
XCTAssert(0<=m && m<=Double(MAX))
for _ in 1...N {
let x=Double.random(m)
XCTAssert((x as Any) is Double)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=Double.random(-m)
XCTAssert((x as Any) is Double)
XCTAssert(-m<=x && x<=0)
}
}
func testRandomCGFloat() {
for _ in 1...N {
let x=CGFloat.random()
XCTAssert((x as Any) is CGFloat)
XCTAssert(0<=x && x<=1)
}
let m=CGFloat.random(CGFloat(MAX))
XCTAssert((m as Any) is CGFloat)
XCTAssert(0<=m && m<=CGFloat(MAX))
for _ in 1...N {
let x=CGFloat.random(m)
XCTAssert((x as Any) is CGFloat)
XCTAssert(0<=x && x<=m)
}
for _ in 1...N {
let x=CGFloat.random(-m)
XCTAssert((x as Any) is CGFloat)
XCTAssert(-m<=x && x<=0)
}
}
// MARK: random in a Range
func testRandomInInt() {
let m=Int.random(Int(-MAX)..<Int(MAX))
XCTAssert((m as Any) is Int)
XCTAssert(-MAX<=m && m<MAX)
let n=Int.random((m+1)...Int(MAX))
XCTAssert((n as Any) is Int)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=Int.random(m..<n)
XCTAssert((x as Any) is Int)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=Int.random(m...n)
XCTAssert((x as Any) is Int)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInInt8() {
let m=Int8.random(Int8(-MAX)..<Int8(MAX))
XCTAssert((m as Any) is Int8)
XCTAssert(-MAX<=m && m<MAX)
let n=Int8.random((m+1)...Int8(MAX))
XCTAssert((n as Any) is Int8)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=Int8.random(m..<n)
XCTAssert((x as Any) is Int8)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=Int8.random(m...n)
XCTAssert((x as Any) is Int8)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInInt16() {
let m=Int16.random(Int16(-MAX)..<Int16(MAX))
XCTAssert((m as Any) is Int16)
XCTAssert(-MAX<=m && m<MAX)
let n=Int16.random((m+1)...Int16(MAX))
XCTAssert((n as Any) is Int16)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=Int16.random(m..<n)
XCTAssert((x as Any) is Int16)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=Int16.random(m...n)
XCTAssert((x as Any) is Int16)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInInt32() {
let m=Int32.random(Int32(-MAX)..<Int32(MAX))
XCTAssert((m as Any) is Int32)
XCTAssert(-MAX<=m && m<MAX)
let n=Int32.random((m+1)...Int32(MAX))
XCTAssert((n as Any) is Int32)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=Int32.random(m..<n)
XCTAssert((x as Any) is Int32)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=Int32.random(m...n)
XCTAssert((x as Any) is Int32)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInInt64() {
let m=Int64.random(Int64(-MAX)..<Int64(MAX))
XCTAssert((m as Any) is Int64)
XCTAssert(-MAX<=m && m<MAX)
let n=Int64.random((m+1)...Int64(MAX))
XCTAssert((n as Any) is Int64)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=Int64.random(m..<n)
XCTAssert((x as Any) is Int64)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=Int64.random(m...n)
XCTAssert((x as Any) is Int64)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInUInt() {
let m=UInt.random(0..<UInt(MAX))
XCTAssert((m as Any) is UInt)
XCTAssert(0<=m && m<MAX)
let n=UInt.random((m+1)...UInt(MAX))
XCTAssert((n as Any) is UInt)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=UInt.random(m..<n)
XCTAssert((x as Any) is UInt)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=UInt.random(m...n)
XCTAssert((x as Any) is UInt)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInUInt8() {
let m=UInt8.random(0..<UInt8(MAX))
XCTAssert((m as Any) is UInt8)
XCTAssert(0<=m && m<MAX)
let n=UInt8.random((m+1)...UInt8(MAX))
XCTAssert((n as Any) is UInt8)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=UInt8.random(m..<n)
XCTAssert((x as Any) is UInt8)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=UInt8.random(m...n)
XCTAssert((x as Any) is UInt8)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInUInt16() {
let m=UInt16.random(0..<UInt16(MAX))
XCTAssert((m as Any) is UInt16)
XCTAssert(0<=m && m<MAX)
let n=UInt16.random((m+1)...UInt16(MAX))
XCTAssert((n as Any) is UInt16)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=UInt16.random(m..<n)
XCTAssert((x as Any) is UInt16)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=UInt16.random(m...n)
XCTAssert((x as Any) is UInt16)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInUInt32() {
let m=UInt32.random(0..<UInt32(MAX))
XCTAssert((m as Any) is UInt32)
XCTAssert(0<=m && m<MAX)
let n=UInt32.random((m+1)...UInt32(MAX))
XCTAssert((n as Any) is UInt32)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=UInt32.random(m..<n)
XCTAssert((x as Any) is UInt32)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=UInt32.random(m...n)
XCTAssert((x as Any) is UInt32)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInUInt64() {
let m=UInt64.random(0..<UInt64(MAX))
XCTAssert((m as Any) is UInt64)
XCTAssert(0<=m && m<MAX)
let n=UInt64.random((m+1)...UInt64(MAX))
XCTAssert((n as Any) is UInt64)
XCTAssert(m<n && n<=MAX)
for _ in 1...N {
let x=UInt64.random(m..<n)
XCTAssert((x as Any) is UInt64)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=UInt64.random(m...n)
XCTAssert((x as Any) is UInt64)
if (!(m<=x && x<=n)) {
print([m,n,x])
print("Oh Oh")
}
XCTAssert(m<=x && x<=n)
}
}
func testRandomInFloat() {
let m=Float.random(Float(-MAX)..<Float(MAX))
XCTAssert((m as Any) is Float)
XCTAssert(-Float(MAX)<=m && m<Float(MAX))
let n=Float.random(m...Float(MAX))
XCTAssert((n as Any) is Float)
// Ignoring astronomically small chance m==n
XCTAssert(m<n && n<=Float(MAX))
for _ in 1...N {
let x=Float.random(m..<n)
XCTAssert((x as Any) is Float)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=Float.random(m...n)
XCTAssert((x as Any) is Float)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInDouble() {
let m=Double.random(Double(-MAX)..<Double(MAX))
XCTAssert((m as Any) is Double)
XCTAssert(-Double(MAX)<=m && m<Double(MAX))
let n=Double.random(m...Double(MAX))
XCTAssert((n as Any) is Double)
// Ignoring astronomically small chance m==n
XCTAssert(m<n && n<=Double(MAX))
for _ in 1...N {
let x=Double.random(m..<n)
XCTAssert((x as Any) is Double)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=Double.random(m...n)
XCTAssert((x as Any) is Double)
XCTAssert(m<=x && x<=n)
}
}
func testRandomInCGFloat() {
let m=CGFloat.random(CGFloat(-MAX)..<CGFloat(MAX))
XCTAssert((m as Any) is CGFloat)
XCTAssert(-CGFloat(MAX)<=m && m<CGFloat(MAX))
let n=CGFloat.random(m...CGFloat(MAX))
XCTAssert((n as Any) is CGFloat)
// Ignoring astronomically small chance m==n
XCTAssert(m<n && n<=CGFloat(MAX))
for _ in 1...N {
let x=CGFloat.random(m..<n)
XCTAssert((x as Any) is CGFloat)
XCTAssert(m<=x && x<n)
}
for _ in 1...N {
let x=CGFloat.random(m...n)
XCTAssert((x as Any) is CGFloat)
XCTAssert(m<=x && x<=n)
}
}
// MARK: randomArray to one
func testRandomArrayInt() {
do {
let range = Int(0)...Int(1)
let X = Int.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt8() {
do {
let range = Int8(0)...Int8(1)
let X = Int8.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt16() {
do {
let range = Int16(0)...Int16(1)
let X = Int16.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt32() {
do {
let range = Int32(0)...Int32(1)
let X = Int32.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt64() {
do {
let range = Int64(0)...Int64(1)
let X = Int64.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt() {
do {
let range = UInt(0)...UInt(1)
let X = UInt.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt8() {
do {
let range = UInt8(0)...UInt8(1)
let X = UInt8.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt16() {
do {
let range = UInt16(0)...UInt16(1)
let X = UInt16.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt32() {
do {
let range = UInt32(0)...UInt32(1)
let X = UInt32.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt64() {
do {
let range = UInt64(0)...UInt64(1)
let X = UInt64.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = 0.5
let s = 1.0/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayFloat() {
do {
let range = Float(0)...Float(1)
let X = Float.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Float(0.5)
let s = Float(1.0/sqrt(12.0))
XCTAssert(s>0)
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let z = (X.mean()-mu)/(s/sqrt(Float(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayDouble() {
do {
let range = Double(0)...Double(1)
let X = Double.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(0.5)
let s = Double(1.0/sqrt(12.0))
XCTAssert(s>0)
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let z = (X.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayCGFloat() {
do {
let range = CGFloat(0)...CGFloat(1)
let X = CGFloat.randomArray(N)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = CGFloat(0.5)
let s = CGFloat(1.0/sqrt(12.0))
XCTAssert(s>0)
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let z = (X.mean()-mu)/(s/sqrt(CGFloat(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayComplex() {
do {
let X = Complex.randomArray(N)
if (N>=100) {
let mu_X : Complex = X.mean()
do {
let mu_real = 0.5
let s_real = 1.0/sqrt(12.0)
let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N)))
XCTAssert(abs(z_real)<6.0)
}
do {
let mu_imaginary = 0.5
let s_imaginary = 1.0/sqrt(12.0)
let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N)))
XCTAssert(abs(z_imaginary)<6.0)
}
}
}
}
// MARK: randomArray to upperBound
func testRandomArrayIntUpperBound() {
let n=Int.random(1...Int(MAX))
XCTAssert((n as Any) is Int)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = Int.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt8UpperBound() {
let n=Int8.random(1...Int8(MAX))
XCTAssert((n as Any) is Int8)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = Int8.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt16UpperBound() {
let n=Int16.random(1...Int16(MAX))
XCTAssert((n as Any) is Int16)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = Int16.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt32UpperBound() {
let n=Int32.random(1...Int32(MAX))
XCTAssert((n as Any) is Int32)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = Int32.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt64UpperBound() {
let n=Int64.random(1...Int64(MAX))
XCTAssert((n as Any) is Int64)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = Int64.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUIntUpperBound() {
let n=UInt.random(1...UInt(MAX))
XCTAssert((n as Any) is UInt)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = UInt.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt8UpperBound() {
let n=UInt8.random(1...UInt8(MAX))
XCTAssert((n as Any) is UInt8)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = UInt8.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt16UpperBound() {
let n=UInt16.random(1...UInt16(MAX))
XCTAssert((n as Any) is UInt16)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = UInt16.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt32UpperBound() {
let n=UInt32.random(1...UInt32(MAX))
XCTAssert((n as Any) is UInt32)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = UInt32.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt64UpperBound() {
let n=UInt64.random(1...UInt64(MAX))
XCTAssert((n as Any) is UInt64)
XCTAssert(n<=MAX)
do {
let range = 0...n
let X = UInt64.randomArray(N,upperBound:n)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = Double(n)/2.0
let s = Double(n)/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayFloatUpperBound() {
let n=Float.random(Float(0.0)...Float(MAX))
XCTAssert((n as Any) is Float)
// Ignoring astronomically small chance 0.0==n
XCTAssert(n<=Float(MAX))
do {
let range = 0...n
let X = Float.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = n/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = n/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(Float(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayDoubleUpperBound() {
let n=Double.random(Double(0.0)...Double(MAX))
XCTAssert((n as Any) is Double)
// Ignoring astronomically small chance 0.0==n
XCTAssert(n<=Double(MAX))
do {
let range = 0...n
let X = Double.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = n/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = n/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayCGFloatUpperBound() {
let n=CGFloat.random(CGFloat(0.0)...CGFloat(MAX))
XCTAssert((n as Any) is CGFloat)
// Ignoring astronomically small chance 0.0==n
XCTAssert(n<=CGFloat(MAX))
do {
let range = 0...n
let X = CGFloat.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = n/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = n/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(CGFloat(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayComplexUpperBound() {
let n_real=Double.random(0.0...Double(MAX))
XCTAssert((n_real as Any) is Double)
// Ignoring astronomically small chance 0.0==n_real
XCTAssert(0.0<n_real && n_real<=Double(MAX))
let n_imaginary=Double.random(0.0...Double(MAX))
XCTAssert((n_imaginary as Any) is Double)
// Ignoring astronomically small chance 0.0==n_imaginary
XCTAssert(0.0<n_imaginary && n_imaginary<=Double(MAX))
// Complex n
let n=Complex(n_real,n_imaginary)
do {
let X = Complex.randomArray(N,upperBound:n)
if (N>=100) {
let mu_X : Complex = X.mean()
do {
let mu_real = n_real/2
let s_real = n_real/sqrt(12.0)
let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N)))
XCTAssert(abs(z_real)<6.0)
}
do {
let mu_imaginary = n_imaginary/2
let s_imaginary = n_imaginary/sqrt(12.0)
let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N)))
XCTAssert(abs(z_imaginary)<6.0)
}
}
}
}
// MARK: randomArray in a range
func testRandomArrayIntRange() {
let m=Int.random(Int(-MAX)..<Int(MAX))
XCTAssert((m as Any) is Int)
XCTAssert(-MAX<=m && m<MAX)
let n=Int.random((m+1)...Int(MAX))
XCTAssert((n as Any) is Int)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = Int.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = Int.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt8Range() {
let m=Int8.random(Int8(-MAX)..<Int8(MAX))
XCTAssert((m as Any) is Int8)
XCTAssert(-MAX<=m && m<MAX)
let n=Int8.random((m+1)...Int8(MAX))
XCTAssert((n as Any) is Int8)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = Int8.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = Int8.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt16Range() {
let m=Int16.random(Int16(-MAX)..<Int16(MAX))
XCTAssert((m as Any) is Int16)
XCTAssert(-MAX<=m && m<MAX)
let n=Int16.random((m+1)...Int16(MAX))
XCTAssert((n as Any) is Int16)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = Int16.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = Int16.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt32Range() {
let m=Int32.random(Int32(-MAX)..<Int32(MAX))
XCTAssert((m as Any) is Int32)
XCTAssert(-MAX<=m && m<MAX)
let n=Int32.random((m+1)...Int32(MAX))
XCTAssert((n as Any) is Int32)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = Int32.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = Int32.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayInt64Range() {
let m=Int64.random(Int64(-MAX)..<Int64(MAX))
XCTAssert((m as Any) is Int64)
XCTAssert(-MAX<=m && m<MAX)
let n=Int64.random((m+1)...Int64(MAX))
XCTAssert((n as Any) is Int64)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = Int64.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = Int64.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUIntRange() {
let m=UInt.random(0..<UInt(MAX))
XCTAssert((m as Any) is UInt)
XCTAssert(-MAX<=m && m<MAX)
let n=UInt.random((m+1)...UInt(MAX))
XCTAssert((n as Any) is UInt)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = UInt.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = UInt.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt8Range() {
let m=UInt8.random(0..<UInt8(MAX))
XCTAssert((m as Any) is UInt8)
XCTAssert(-MAX<=m && m<MAX)
let n=UInt8.random((m+1)...UInt8(MAX))
XCTAssert((n as Any) is UInt8)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = UInt8.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = UInt8.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt16Range() {
let m=UInt16.random(0..<UInt16(MAX))
XCTAssert((m as Any) is UInt16)
XCTAssert(-MAX<=m && m<MAX)
let n=UInt16.random((m+1)...UInt16(MAX))
XCTAssert((n as Any) is UInt16)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = UInt16.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = UInt16.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt32Range() {
let m=UInt32.random(0..<UInt32(MAX))
XCTAssert((m as Any) is UInt32)
XCTAssert(-MAX<=m && m<MAX)
let n=UInt32.random((m+1)...UInt32(MAX))
XCTAssert((n as Any) is UInt32)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = UInt32.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = UInt32.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayUInt64Range() {
let m=UInt64.random(0..<UInt64(MAX))
XCTAssert((m as Any) is UInt64)
XCTAssert(-MAX<=m && m<MAX)
let n=UInt64.random((m+1)...UInt64(MAX))
XCTAssert((n as Any) is UInt64)
XCTAssert(m<n && n<=MAX)
do {
let range = m..<n
let X = UInt64.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let b = n-1
let mu = (Double(m)+Double(b))/2.0
let s = (Double(b)-Double(m))/sqrt(12.0)
if (s>0) {
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
do {
let range = m...n
let X = UInt64.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (Double(m)+Double(n))/2.0
let s = (Double(n)-Double(m))/sqrt(12.0)
XCTAssert(s>0)
let D = X.asDoubleArray()
XCTAssert(D.min()!<mu)
XCTAssert(D.max()!>mu)
let z = (D.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayFloatRange() {
let m=Float.random(Float(-MAX)..<Float(MAX))
XCTAssert((m as Any) is Float)
XCTAssert(-Float(MAX)<=m && m<Float(MAX))
let n=Float.random(m...Float(MAX))
XCTAssert((n as Any) is Float)
// Ignoring astronomically small chance m==n
XCTAssert(m<n && n<=Float(MAX))
do {
let range = m..<n
let X = Float.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (m+n)/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = (n-m)/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(Float(N)))
XCTAssert(abs(z)<6.0)
}
}
do {
let range = m...n
let X = Float.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (m+n)/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = (n-m)/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(Float(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayDoubleRange() {
let m=Double.random(Double(-MAX)..<Double(MAX))
XCTAssert((m as Any) is Double)
XCTAssert(-Double(MAX)<=m && m<Double(MAX))
let n=Double.random(m...Double(MAX))
XCTAssert((n as Any) is Double)
// Ignoring astronomically small chance m==n
XCTAssert(m<n && n<=Double(MAX))
do {
let range = m..<n
let X = Double.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (m+n)/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = (n-m)/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
do {
let range = m...n
let X = Double.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (m+n)/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = (n-m)/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(Double(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayCGFloatRange() {
let m=CGFloat.random(CGFloat(-MAX)..<CGFloat(MAX))
XCTAssert((m as Any) is CGFloat)
XCTAssert(-CGFloat(MAX)<=m && m<CGFloat(MAX))
let n=CGFloat.random(m...CGFloat(MAX))
XCTAssert((n as Any) is CGFloat)
// Ignoring astronomically small chance m==n
XCTAssert(m<n && n<=CGFloat(MAX))
do {
let range = m..<n
let X = CGFloat.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (m+n)/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = (n-m)/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(CGFloat(N)))
XCTAssert(abs(z)<6.0)
}
}
do {
let range = m...n
let X = CGFloat.randomArray(N,range:range)
for x in X {
XCTAssert(range.contains(x))
}
if (N>=100) {
let mu = (m+n)/2
XCTAssert(X.min()!<mu)
XCTAssert(X.max()!>mu)
let s = (n-m)/sqrt(12.0)
let z = (X.mean()-mu)/(s/sqrt(CGFloat(N)))
XCTAssert(abs(z)<6.0)
}
}
}
func testRandomArrayComplexRange() {
let m_real=Double.random(Double(-MAX)..<Double(MAX))
XCTAssert((m_real as Any) is Double)
XCTAssert(-Double(MAX)<=m_real && m_real<Double(MAX))
let n_real=Double.random(m_real...Double(MAX))
XCTAssert((n_real as Any) is Double)
// Ignoring astronomically small chance m_real==n_real
XCTAssert(m_real<n_real && n_real<=Double(MAX))
let m_imaginary=Double.random(Double(-MAX)..<Double(MAX))
XCTAssert((m_imaginary as Any) is Double)
XCTAssert(-Double(MAX)<=m_imaginary && m_imaginary<Double(MAX))
let n_imaginary=Double.random(m_imaginary...Double(MAX))
XCTAssert((n_imaginary as Any) is Double)
// Ignoring astronomically small chance m_imaginary==n_imaginary
XCTAssert(m_imaginary<n_imaginary && n_imaginary<=Double(MAX))
// Complex m and n
let m=Complex(m_real,m_imaginary)
let n=Complex(n_real,n_imaginary)
do {
let range = m..<n
let X = Complex.randomArray(N,range:range)
if (N>=100) {
let mu_X : Complex = X.mean()
do {
let mu_real = (m_real+n_real)/2
let s_real = (n_real-m_real)/sqrt(12.0)
let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N)))
XCTAssert(abs(z_real)<6.0)
}
do {
let mu_imaginary = (m_imaginary+n_imaginary)/2
let s_imaginary = (n_imaginary-m_imaginary)/sqrt(12.0)
let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N)))
XCTAssert(abs(z_imaginary)<6.0)
}
}
}
do {
let range = m...n
let X = Complex.randomArray(N,range:range)
if (N>=100) {
let mu_X : Complex = X.mean()
do {
let mu_real = (m_real+n_real)/2
let s_real = (n_real-m_real)/sqrt(12.0)
let z_real = (mu_X.real-mu_real)/(s_real/sqrt(Double(N)))
XCTAssert(abs(z_real)<6.0)
}
do {
let mu_imaginary = (m_imaginary+n_imaginary)/2
let s_imaginary = (n_imaginary-m_imaginary)/sqrt(12.0)
let z_imaginary = (mu_X.imaginary-mu_imaginary)/(s_imaginary/sqrt(Double(N)))
XCTAssert(abs(z_imaginary)<6.0)
}
}
}
}
// MARK: randomArray Performance
func testRandomArrayUIntPerformance() {
compareBaseline(0.000478798151016235, title: "Random UInt Array of length 10000", n: 10) {
UInt.randomArray(10000)
}
}
func testRandomArrayIntPerformance() {
compareBaseline(0.000473904609680176, title: "Random Int Array of length 10000", n: 10) {
Int.randomArray(10000)
}
}
func testRandomArrayInt8Permormance() {
compareBaseline(0.000310802459716797, title: "Random Int8 Array of length 10000", n: 10) {
UInt8.randomArray(10000)
}
}
func testRandomArrayInt16Permormance() {
compareBaseline(0.000315195322036743, title: "Random Int16 Array of length 10000", n: 10) {
Int16.randomArray(10000)
}
}
func testRandomArrayInt32Permormance() {
compareBaseline(0.0002532958984375, title: "Random Int32 Array of length 10000", n: 10) {
Int32.randomArray(10000)
}
}
func testRandomArrayInt64Permormance() {
compareBaseline(0.000450801849365234, title: "Random Int64 Array of length 10000", n: 10) {
Int64.randomArray(10000)
}
}
func testRandomArrayFloatPerformance() {
compareBaseline(0.000304659207661947, title: "Random Float Array of length 10000", n: 10) {
Float.randomArray(10000)
}
}
func testRandomArrayDoublePerformance() {
compareBaseline(0.000660339991251628, title: "Random Double Array of length 10000", n: 10) {
Double.randomArray(10000)
}
}
}
| mit | ac49d25465265abae812c8232c4a5e8e | 31.087767 | 100 | 0.427858 | 3.674834 | false | false | false | false |
DanielAsher/Few.swift | Few-iOS/Image.swift | 4 | 1342 | //
// Image.swift
// Few
//
// Created by Coen Wessels on 13-03-15.
// Copyright (c) 2015 Josh Abernathy. All rights reserved.
//
import UIKit
public class Image: Element {
public var image: UIImage?
public var scaling: UIViewContentMode
public var clipsToBounds: Bool
public init(_ image: UIImage?, scaling: UIViewContentMode = .ScaleAspectFit, clipsToBounds: Bool = false) {
self.image = image
self.scaling = scaling
self.clipsToBounds = clipsToBounds
let size = image?.size ?? CGSize(width: Node.Undefined, height: Node.Undefined)
super.init(frame: CGRect(origin: CGPointZero, size: size))
}
// MARK: Element
public override func applyDiff(old: Element, realizedSelf: RealizedElement?) {
super.applyDiff(old, realizedSelf: realizedSelf)
if let view = realizedSelf?.view as? UIImageView {
if view.contentMode != scaling {
view.contentMode = scaling
}
if view.image != image {
view.image = image
realizedSelf?.markNeedsLayout()
}
if view.clipsToBounds != clipsToBounds {
view.clipsToBounds = clipsToBounds
}
}
}
public override func createView() -> ViewType {
let view = UIImageView(frame: CGRectZero)
view.alpha = alpha
view.hidden = hidden
view.image = image
view.contentMode = scaling
view.clipsToBounds = clipsToBounds
return view
}
}
| mit | 363a7e6293142b1ab6bca6d1faf9e3c6 | 23.4 | 108 | 0.701192 | 3.738162 | false | false | false | false |
Mayfleet/SimpleChat | Frontend/iOS/SimpleChat/SimpleChat/Screens/Chat/LogIn/LogInViewController.swift | 1 | 2952 | //
// Created by Maxim Pervushin on 10/03/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController {
// MARK: LogInViewController @IB
@IBOutlet weak var usernameTextField: UITextField?
@IBOutlet weak var passwordTextField: UITextField?
@IBOutlet weak var containerView: UIView?
@IBOutlet weak var containerToBottomLayoutConstraint: NSLayoutConstraint?
@IBAction func closeButtonAction(sender: AnyObject) {
didClose?()
}
@IBAction func logInButtonAction(sender: AnyObject) {
didLogIn?(username: usernameTextField?.text, password: passwordTextField?.text)
}
@IBAction func signUpButtonAction(sender: AnyObject) {
signUpButtonAction?()
}
@IBAction func forgotPasswordButtonAction(sender: AnyObject) {
}
@IBAction func tapGestureRecognizerAction(sender: AnyObject) {
if usernameTextField?.isFirstResponder() == true {
usernameTextField?.resignFirstResponder()
} else if passwordTextField?.isFirstResponder() == true {
passwordTextField?.resignFirstResponder()
}
}
// MARK: LogInViewController
var didClose: (Void -> Void)?
var didLogIn: ((username: String?, password: String?) -> Void)?
var signUpButtonAction: (Void -> Void)?
private func keyboardWillChangeFrameNotification(notification: NSNotification) {
guard let
viewHeight = view?.bounds.size.height,
frameEnd = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue(),
animationDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval else {
return
}
view.layoutIfNeeded()
UIView.animateWithDuration(animationDuration) {
() -> Void in
self.containerToBottomLayoutConstraint?.constant = viewHeight - frameEnd.origin.y
self.view.layoutIfNeeded()
}
}
private func subscribe() {
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil, usingBlock: keyboardWillChangeFrameNotification)
}
private func unsubscribe() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
subscribe()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
unsubscribe()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if traitCollection.horizontalSizeClass == .Compact {
return [.Portrait]
}
return [.All]
}
}
| mit | 4fc192af79407fcaa0e2d6b2f2f2f241 | 31.8 | 176 | 0.689363 | 5.857143 | false | false | false | false |
HTWDD/HTWDresden-iOS-Temp | HTWDresden_old/HTWDresden/Playground.playground/section-1.swift | 1 | 8449 | // Playground - noun: a place where people can play
import Cocoa
import Foundation
extension String {
func containsIgnoreCase(other: String) -> Bool{
var start = startIndex
do{
var subString = self[Range(start: start++, end: endIndex)].lowercaseString
if subString.hasPrefix(other.lowercaseString){
return true
}
}while start != endIndex
return false
}
func lengthAfterIndex(index: Int) -> Int {
return self.length - index
}
}
extension String
{
var length: Int {
get {
return countElements(self)
}
}
func contains(s: String) -> Bool
{
return (self.rangeOfString(s) != nil) ? true : false
}
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
subscript (i: Int) -> Character
{
get {
let index = advance(startIndex, i)
return self[index]
}
}
subscript (r: Range<Int>) -> String
{
get {
let startIndex = advance(self.startIndex, r.startIndex)
let endIndex = advance(self.startIndex, r.endIndex - 1)
return self[Range(start: startIndex, end: endIndex)]
}
}
func subString(startIndex: Int, length: Int) -> String
{
var start = advance(self.startIndex, startIndex)
var end = advance(self.startIndex, startIndex + length)
return self.substringWithRange(Range<String.Index>(start: start, end: end))
}
func indexOf(target: String) -> Int
{
var range = self.rangeOfString(target)
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func indexOf(target: String, startIndex: Int) -> Int
{
var startRange = advance(self.startIndex, startIndex)
var range = self.rangeOfString(target, options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: startRange, end: self.endIndex))
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func lastIndexOf(target: String) -> Int
{
var index = -1
var stepIndex = self.indexOf(target)
while stepIndex > -1
{
index = stepIndex
if stepIndex + target.length < self.length {
stepIndex = indexOf(target, startIndex: stepIndex + target.length)
} else {
stepIndex = -1
}
}
return index
}
func isMatch(regex: String, options: NSRegularExpressionOptions) -> Bool
{
var error: NSError?
var exp = NSRegularExpression(pattern: regex, options: options, error: &error)!
if let error = error {
println(error.description)
}
var matchCount = exp.numberOfMatchesInString(self, options: nil, range: NSMakeRange(0, self.length))
return matchCount > 0
}
func getMatches(regex: String, options: NSRegularExpressionOptions) -> [NSTextCheckingResult]
{
var error: NSError?
var exp = NSRegularExpression(pattern: regex, options: options, error: &error)!
if let error = error {
println(error.description)
}
var matches = exp.matchesInString(self, options: nil, range: NSMakeRange(0, self.length))
return matches as [NSTextCheckingResult]
}
private var vowels: [String]
{
get
{
return ["a", "e", "i", "o", "u"]
}
}
private var consonants: [String]
{
get
{
return ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"]
}
}
func pluralize(count: Int) -> String
{
if count == 1 {
return self
} else {
var lastChar = self.subString(self.length - 1, length: 1)
var secondToLastChar = self.subString(self.length - 2, length: 1)
var prefix = "", suffix = ""
if lastChar.lowercaseString == "y" && vowels.filter({x in x == secondToLastChar}).count == 0 {
prefix = self[0...self.length - 1]
suffix = "ies"
} else if lastChar.lowercaseString == "s" || (lastChar.lowercaseString == "o" && consonants.filter({x in x == secondToLastChar}).count > 0) {
prefix = self[0...self.length]
suffix = "es"
} else {
prefix = self[0...self.length]
suffix = "s"
}
return prefix + (lastChar != lastChar.uppercaseString ? suffix : suffix.uppercaseString)
}
}
}
extension NSDate {
class func dateFromString(string: String, format: String) -> NSDate {
let dateF = NSDateFormatter()
dateF.dateFormat = format
return dateF.dateFromString(string)!
}
func stringFromDate(format: String) -> String {
let dateF = NSDateFormatter()
dateF.dateFormat = format
return dateF.stringFromDate(self)
}
class func weekDay() -> Int {
var weekday = (NSCalendar.currentCalendar().components(.WeekdayCalendarUnit, fromDate: NSDate())).weekday - 2
if weekday == -1 {
weekday = 6
}
return weekday
}
func weekDay() -> Int {
var weekday = (NSCalendar.currentCalendar().components(.WeekdayCalendarUnit, fromDate: self)).weekday - 2
if weekday == -1 {
weekday = 6
}
return weekday
}
func weekdayString() -> String {
switch self.weekDay() {
case 0: return "Montag"
case 1: return "Dienstag"
case 2: return "Mittwoch"
case 3: return "Donnerstag"
case 4: return "Freitag"
case 5: return "Samstag"
case 6: return "Sonntag"
default: return ""
}
}
func getDayOnly() -> NSDate {
let dateF = NSDateFormatter()
dateF.dateFormat = "dd.MM.yyyy"
return dateF.dateFromString(dateF.stringFromDate(self))!
}
class func isSameDayWithDate1(date1: NSDate, andDate2 date2: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
let comp1 = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: date1)
let comp2 = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: date2)
return comp1.day == comp2.day && comp1.month == comp2.month && comp1.year == comp2.year
}
class func specificDate(day: Int, month: Int, year: Int) -> NSDate {
var comps = NSDateComponents()
comps.day = day
comps.month = month
comps.year = year
return NSCalendar.currentCalendar().dateFromComponents(comps)!
}
func inRange(date1: NSDate, date2: NSDate) -> Bool {
if NSCalendar.currentCalendar().compareDate(self, toDate: date1, toUnitGranularity: .HourCalendarUnit) == NSComparisonResult.OrderedAscending {
return false
}
if NSCalendar.currentCalendar().compareDate(self, toDate: date2, toUnitGranularity: .HourCalendarUnit) == NSComparisonResult.OrderedDescending {
return false
}
return true
}
func addDays(days: Int) -> NSDate {
var dayComponent = NSDateComponents()
dayComponent.day = days
var theCalendar = NSCalendar.currentCalendar()
return theCalendar.dateByAddingComponents(dayComponent, toDate: self, options: .allZeros)!
}
}
func ausformuliertesSemesterVon(semester: String) -> String {
let jahr = semester[0...4]
let typ = "\(semester[4])"
switch typ.toInt()! {
case 1:
return "Sommersemester \(jahr)"
case 2:
return "Wintersemester \(jahr)/\(jahr.toInt()! + 1)"
default:
break
}
return ""
}
ausformuliertesSemesterVon("20122")
| gpl-2.0 | b1190a8fd19baf6a38af9a4086ca288a | 29.501805 | 160 | 0.565156 | 4.586862 | false | false | false | false |
huankong/Weibo | Weibo/Weibo/Main/Home/QRCode/QRProduceViewController.swift | 1 | 3722 | //
// QRProduceViewController.swift
// Weibo
//
// Created by ldy on 16/7/4.
// Copyright © 2016年 ldy. All rights reserved.
//
import UIKit
class QRProduceViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "我的二维码"
view.backgroundColor = UIColor.lightGrayColor()
// 创建二维码
view.addSubview(myCodeImage)
myCodeImage.snp_makeConstraints { (make) in
make.center.equalTo(view)
make.size.equalTo(CGSize(width: 200, height: 200))
}
}
func createQRCodeImage(textStr: String) -> UIImage {
// 二维码滤镜
let filter = CIFilter(name: "CIQRCodeGenerator")
// 恢复滤镜的默认属性
filter?.setDefaults()
// 设置参数
filter?.setValue(textStr.dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
//获取滤镜输出的图像
let outputImage = filter?.outputImage
let bgImage = createNonInterpolatedUIImageFormCIImage(outputImage!, size: 200)
//获取头像
let iconImage = UIImage(named: "iconImage")
//设置图片
return createNewImageWithBg(bgImage, iconImage: iconImage!)
}
/**
生成二维码名片
:param: bgImage 背景图片
:param: iconImage 头像
:returns: 生成好的图片
*/
private func createNewImageWithBg(bgImage:UIImage, iconImage: UIImage) -> UIImage{
// 1.开启图片上下文
UIGraphicsBeginImageContext(bgImage.size)
// 2.绘制背景
bgImage.drawInRect(CGRect(origin: CGPointZero, size: bgImage.size))
// 3.绘制图标
let iconW:CGFloat = 50.0
let iconH:CGFloat = 50.0
let iconX = (bgImage.size.width - iconW) * 0.5
let iconY = (bgImage.size.height - iconH) * 0.5
iconImage.drawInRect(CGRect(x: iconX, y: iconY, width: iconW, height: iconH))
// 4.取出绘制好的图片
let newImage = UIGraphicsGetImageFromCurrentImageContext()
// 5.关闭上下文
UIGraphicsEndImageContext()
// 6.返回生成好得图片
return newImage
}
//MARK: - 懒加载
private lazy var myCodeImage: UIImageView = {
let image = self.createQRCodeImage("幻空缥缈")
let imgV = UIImageView(image: image)
return imgV
}()
/**
根据CIImage生成指定大小的高清UIImage
:param: image 指定CIImage
:param: size 指定大小
:returns: 生成好的图片
*/
private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
let extent: CGRect = CGRectIntegral(image.extent)
let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
// 1.创建bitmap;
let width = CGRectGetWidth(extent) * scale
let height = CGRectGetHeight(extent) * scale
let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
let context = CIContext(options: nil)
let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent)
CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None)
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2.保存bitmap到图片
let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
return UIImage(CGImage: scaledImage)
}
}
| apache-2.0 | 4bea139a607c316caaddb92248bdd512 | 30.898148 | 100 | 0.62119 | 4.520997 | false | false | false | false |
Ra1phM/RMTextViewPlaceholder | RMTextViewPlaceholder/RMTextViewPlaceholder.swift | 1 | 3798 | //
// RMPlaceholderTextView.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Ralph Marschall
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@IBDesignable class RMTextViewPlaceholder: UITextView {
var placeholderLabel: UILabel!
@IBInspectable var placeholder: String = "Placeholder" {
didSet {
placeholderLabel.text = placeholder
placeholderLabel.sizeToFit()
}
}
@IBInspectable var phColor: UIColor = UIColor.lightGrayColor() {
didSet {
placeholderLabel.textColor = phColor
}
}
@IBInspectable var phBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
placeholderLabel.backgroundColor = phBackgroundColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
registerToNotifications()
setupPlaceholderLabel()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
registerToNotifications()
setupPlaceholderLabel()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
registerToNotifications()
setupPlaceholderLabel()
}
deinit {
let ns = NSNotificationCenter.defaultCenter()
ns.removeObserver(self)
}
func setupPlaceholderLabel() {
if self.placeholderLabel == nil {
self.placeholderLabel = UILabel(frame: CGRectMake(8, 8, 0, 0))
self.placeholderLabel.sizeToFit()
//self.placeholderLabel.font = self.font
self.addSubview(self.placeholderLabel)
}
}
func updatePlaceholderLabel() {
self.placeholderLabel.hidden = !( countElements(self.text) == 0 )
}
func registerToNotifications() {
let ns = NSNotificationCenter.defaultCenter()
ns.removeObserver(self)
//ns.addObserver(self, selector: "didBeginEditing:", name: UITextViewTextDidBeginEditingNotification, object: nil)
ns.addObserver(self, selector: "didChange:", name: UITextViewTextDidChangeNotification, object: nil)
//ns.addObserver(self, selector: "didEndEditing:", name: UITextViewTextDidEndEditingNotification, object: nil)
}
func didBeginEditing(notification: NSNotification) {
println("UITEXTVIEW didBegin")
}
func didChange(notification: NSNotification) {
println("UITEXTVIEW didChange")
updatePlaceholderLabel()
}
func didEndEditing(notification: NSNotification) {
println("UITEXTVIEW didEnd")
}
}
| mit | 6ae1684bd494d4b26d70f47a65f90f67 | 32.026087 | 122 | 0.661927 | 5.097987 | false | false | false | false |
googleapis/google-api-swift-client | Sources/google-api-swift-generator/main.swift | 1 | 18266 | // Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Discovery
enum ParsingError: Error {
case topLevelSchemaUnknownType(schemaName: String, type: String)
case topLevelSchemaArrayDoesNotContainObjects(schemaName: String)
case arrayDidNotIncludeItems(schemaName: String?)
case arrayHadUnknownItems(schemaName: String)
case schemaDidNotIncludeTypeOrRef(schemaName: String)
case arrayContainedArray(schemaName: String)
case unknown
}
func createInitLines(baseIndent: Int, parentName: String?, parameters: [String: Schema]) -> String {
let inputs = parameters
.sorted(by: { $0.key < $1.key })
.map { (arg: (key: String, value: Schema)) -> (key: String, type: String) in
let (key, value) = arg
let typeName: String
if let parentName = parentName {
typeName = "\(parentName.upperCamelCased())_\(key.upperCamelCased())"
} else {
typeName = key.upperCamelCased()
}
var tmpKey = key.camelCased()
if tmpKey == "self" {
tmpKey = "selfRef"
}
return (key: "`\(tmpKey)`", type: "\(value.Type(objectName: typeName))?")
}
let inputSignature = inputs.map { "\($0.key): \($0.type)" }.joined(separator: ", ")
let assignments = inputs.reduce("") { (prev: String, curr: (key: String, type: String)) -> String in
let nextItem = String(repeating: " ", count: 12) + "self.\(curr.key) = \(curr.key)"
if prev.isEmpty { return "\n" + nextItem }
return """
\(prev)
\(nextItem)
"""
}
return """
public init (\(inputSignature)) {\(assignments)
}
"""
}
func createCodingKeys(baseIndent: Int, parentName: String?, parameters: [String: Schema]) -> String {
let someKeyHasHyphen = parameters.keys.reduce(false) { (prev: Bool, curr: String) -> Bool in
if prev { return prev }
return curr.contains("-") || curr.contains(".") || curr.starts(with: "$") || curr.starts(with: "@") || curr == "self"
}
guard someKeyHasHyphen else { return "" }
let cases = parameters
.sorted(by: { $0.key < $1.key })
.reduce("") { (prev: String, curr: (key: String, value: Schema)) -> String in
let explicitValue = curr.key.contains("-") || curr.key.contains(".") || curr.key.starts(with: "$") || curr.key.starts(with: "@") || curr.key == "self"
? " = \"\(curr.key)\""
: ""
var key = curr.key.camelCased()
if key == "self" {
key = "selfRef"
}
let nextLine = "case `\(key)`\(explicitValue)"
if prev.isEmpty { return String(repeating: " ", count: 12) + nextLine }
return """
\(prev)
\(nextLine)
"""
}
return """
enum CodingKeys : String, CodingKey {
\(cases)
}
"""
}
func createArrayType(nextName: String, schema: (key: String, value: Schema), stringUnderConstruction: inout String) throws -> String {
guard let arrayItems = schema.value.items else {
throw ParsingError.arrayDidNotIncludeItems(schemaName: schema.key)
}
let type: String
if var ref = arrayItems.ref {
let escapingNames = ["Type", "Error"]
if escapingNames.contains(ref) {
ref = "Custom_" + ref
}
type = "[\(ref)]"
} else if let _ = arrayItems.properties {
try createNestedObject(parentName: nextName, name: nextName, schema: arrayItems, stringUnderConstruction: &stringUnderConstruction)
type = "\(schema.value.Type(objectName: nextName))"
} else if let additionalProperties = arrayItems.additionalProperties {
try createDynamicNestedObject(parentName: nextName, name: nextName, schema: additionalProperties, stringUnderConstruction: &stringUnderConstruction)
type = "\(schema.value.Type(objectName: nextName))"
}
else if let arrayItemType = arrayItems.type {
var arrayItemTypeName = ""
switch arrayItemType {
case "string": arrayItemTypeName = "String" // todo: perform check for enums.
case "integer": arrayItemTypeName = "Int"
case "number": arrayItemTypeName = "Double"
case "boolean": arrayItemTypeName = "Bool"
case "array":
arrayItemTypeName = try createArrayType(nextName: nextName, schema: (key: "\(schema.key)ArrayItem", value: arrayItems), stringUnderConstruction: &stringUnderConstruction)
default: arrayItemTypeName = "JSONAny"
}
type = "[\(arrayItemTypeName)]"
} else {
throw ParsingError.arrayHadUnknownItems(schemaName: schema.key)
}
return type
}
func createSchemaAssignment(parentName: String?, name: String, schema: (key: String, value: Schema), stringUnderConstruction: inout String) throws -> (key: String, type: String) {
var key = schema.key.camelCased()
if key == "self" { key = "selfRef" }
let type: String
let nextName = "\(name.upperCamelCased())_\(schema.key.upperCamelCased())"
if let t = schema.value.type {
switch t {
case "object":
// replace branchs with single route?
if let additionalProperties = schema.value.additionalProperties {
let dynamicNextName = schema.value.Type(objectName: nextName)
try createDynamicNestedObject(parentName: nextName, name: dynamicNextName, schema: additionalProperties, stringUnderConstruction: &stringUnderConstruction)
type = schema.value.Type(objectName: nextName)
} else {
try createNestedObject(parentName: nextName, name: nextName, schema: schema.value, stringUnderConstruction: &stringUnderConstruction)
type = "\(schema.value.Type(objectName: nextName))"
}
case "array":
type = try createArrayType(nextName: nextName, schema: schema, stringUnderConstruction: &stringUnderConstruction)
default:
type = schema.value.Type()
}
} else if let ref = schema.value.ref {
let escapingNames = ["Type", "Error"]
if escapingNames.contains(ref) {
type = "Custom_" + ref
} else {
type = ref
}
} else {
throw ParsingError.schemaDidNotIncludeTypeOrRef(schemaName: schema.key)
}
return (key: key, type: type)
}
func createDynamicNestedObject(parentName: String?, name: String, schema: Schema, stringUnderConstruction: inout String) throws {
let aliasType: String
if let type = schema.type, type == "object" {
try createNestedObject(parentName: (parentName ?? "") + "Item", name: name + "Item", schema: schema, stringUnderConstruction: &stringUnderConstruction)
aliasType = "[String: \(schema.Type(objectName: name + "Item"))]"
} else if let type = schema.type, type == "array", let arrayItems = schema.items, arrayItems.type == "object" {
try createNestedObject(parentName: (parentName ?? "") + "Item", name: name + "Item", schema: schema, stringUnderConstruction: &stringUnderConstruction)
aliasType = "[String: \(schema.Type(objectName: name + "Item"))]"
} else {
aliasType = "[String: \(schema.Type(objectName: name))]"
}
// todo: check for string being an enum
stringUnderConstruction.addLine(indent: 4, "public typealias \(name) = \(aliasType)\n")
}
func createStaticNestedObject(parentName: String?, name: String, schema: Schema, stringUnderConstruction: inout String) throws {
let currentIndent = 2
let initializer = createInitLines(baseIndent: currentIndent, parentName: parentName, parameters: schema.properties!)
let codingKeys = createCodingKeys(baseIndent: currentIndent, parentName: parentName, parameters: schema.properties!)
var assignments = ""
for p in schema.properties!.sorted(by: { $0.key.camelCased() < $1.key.camelCased() }) {
let assignment = try createSchemaAssignment(parentName: parentName, name: name, schema: p, stringUnderConstruction: &stringUnderConstruction)
assignments.addLine(indent: 8, "public var `\(assignment.key)`: \(assignment.type)?")
}
//todo: add comments for class
let escapingNames = ["Type", "Error"]
let className = escapingNames.contains(name) ? "Custom_" + name : name
let def = """
public class \(className): Codable {
\(initializer)\(!codingKeys.isEmpty ? "\n\(codingKeys)" : "")
\(assignments) }
"""
stringUnderConstruction.addLine(indent: currentIndent, def)
}
func createNestedObject(parentName: String?, name: String, schema: Schema, stringUnderConstruction: inout String) throws {
if let additionalProperties = schema.additionalProperties {
try createDynamicNestedObject(parentName: parentName, name: name, schema: additionalProperties, stringUnderConstruction: &stringUnderConstruction)
} else if let _ = schema.properties {
try createStaticNestedObject(parentName: parentName, name: name, schema: schema, stringUnderConstruction: &stringUnderConstruction)
} else {
// object has no dynamic properties, and no static properties. Can't infer what it is. Typealias to JSONAny
let aliasDef = "public typealias \(name) = JSONAny\n"
stringUnderConstruction.addLine(indent: 4, aliasDef)
}
}
func createCodingKeys(baseIndent: Int, parameters: [String: Schema]) -> String {
let someKeyHasHyphen = parameters.keys.reduce(false) { (prev: Bool, curr: String) -> Bool in
if prev { return prev }
return curr.contains("-")
}
guard someKeyHasHyphen else { return "" }
var currentIndent = baseIndent
var enumDeclaration = ""
enumDeclaration.addLine(indent: currentIndent, "enum CodingKeys : String, CodingKey {")
currentIndent += 2
for p in parameters.sorted(by: { $0.key < $1.key }) {
let explicitValue = p.key.contains("-") ? " = \"\(p.key)\"" : ""
enumDeclaration.addLine(indent: currentIndent, "case `\(p.key.camelCased())`\(explicitValue)")
}
currentIndent -= 2
enumDeclaration.addLine(indent: currentIndent, "}")
return enumDeclaration
}
extension Discovery.Method {
func ParametersTypeDeclaration(resource : String, method : String) -> String {
var s = ""
s.addLine()
guard let parameters = parameters else { return "" } // todo: check: should this throw an error or return func with no args?
let initializer = createInitLines(baseIndent: 4, parentName: nil, parameters: parameters)
let codingKeys = createCodingKeys(baseIndent: 4, parentName: nil, parameters: parameters)
var classProperties = ""
for p in parameters.sorted(by: { $0.key < $1.key }) {
classProperties.addLine(indent:8, "public var `\(p.key.camelCased())`: \(p.value.Type())?")
}
let queryParameterItems = parameters
.sorted(by: { $0.key < $1.key })
.filter { if let location = $0.value.location { return location == "query" } else { return false } }
.map { return "\"\($0.key.camelCased())\"" }
.joined(separator: ",")
let queryParametersDef = """
public func queryParameters() -> [String] {
[\(queryParameterItems)]
}
"""
let pathParameterItems = parameters
.sorted(by: { $0.key < $1.key })
.filter { if let location = $0.value.location { return location == "path" } else { return false } }
.map { return "\"\($0.key.camelCased())\"" }
.joined(separator: ",")
let pathParametersDef = """
public func pathParameters() -> [String] {
[\(pathParameterItems)]
}
"""
return """
public class \(ParametersTypeName(resource:resource, method:method)): Parameterizable {
\(initializer)
\(codingKeys)
\(classProperties)
\(queryParametersDef)
\(pathParametersDef)
}
"""
}
}
extension Discovery.Resource {
func generate(name: String) -> String {
var s = ""
if let methods = self.methods {
for m in methods.sorted(by: { $0.key < $1.key }) {
s.addLine()
if m.value.HasParameters() {
s += m.value.ParametersTypeDeclaration(resource:name, method:m.key)
}
let methodName = name.camelCased() + "_" + m.key.upperCamelCased()
s.addLine()
s.addLine(indent:4, "public func \(methodName) (")
if m.value.HasRequest() {
s.addLine(indent:8, "request: \(m.value.RequestTypeName()),")
}
if m.value.HasParameters() {
s.addLine(indent:8, "parameters: \(m.value.ParametersTypeName(resource:name, method:m.key)),")
}
if m.value.HasResponse() {
s.addLine(indent:8, "completion: @escaping (\(m.value.ResponseTypeName())?, Error?) -> ()) throws {")
} else {
s.addLine(indent:8, "completion: @escaping (Error?) -> ()) throws {")
}
s.addLine(indent:12, "try perform(")
s.addLine(indent:16, "method: \"\(m.value.httpMethod!)\",")
var path = ""
if m.value.path != nil {
path = m.value.path!
}
s.addLine(indent:16, "path: \"\(path)\",")
if m.value.HasRequest() {
s.addLine(indent:16, "request: request,")
}
if m.value.HasParameters() {
s.addLine(indent:16, "parameters: parameters,")
}
s.addLine(indent:16, "completion: completion)")
s.addLine(indent:4, "}")
s.addLine()
}
}
if let resources = self.resources {
for r in resources.sorted(by: { $0.key < $1.key }) {
s += r.value.generate(name: name + "_" + r.key)
}
}
return s
}
}
extension Discovery.Service {
func generate() throws -> String {
guard let schemas = schemas else {
return ""
}
var generatedSchemas = ""
for schema in schemas.sorted(by: { $0.key < $1.key }) {
switch schema.value.type {
case "object":
try createNestedObject(parentName: schema.key,
name: schema.key.camelCased(),
schema: schema.value,
stringUnderConstruction: &generatedSchemas)
case "array":
guard let itemsSchema = schema.value.items else {
throw ParsingError.topLevelSchemaArrayDoesNotContainObjects(schemaName: schema.key)
}
if let ref = itemsSchema.ref {
generatedSchemas.addLine(indent: 4, "public typealias \(schema.key) = [\(ref)]")
} else {
generatedSchemas.addLine(indent:2, "public typealias \(schema.key) = [\(schema.key)Item]")
generatedSchemas.addLine()
generatedSchemas.addLine(indent:2, "public class \(schema.key)Item : Codable {")
if let properties = itemsSchema.properties {
let initializer = createInitLines(baseIndent: 4, parentName: nil, parameters: properties)
generatedSchemas.addTextWithoutLinebreak(initializer)
let codingKeys = createCodingKeys(baseIndent: 4, parentName: nil, parameters: properties)
generatedSchemas.addLine(codingKeys)
for p in properties.sorted(by: { $0.key < $1.key }) {
generatedSchemas.addLine(indent:4, "public var `\(p.key.camelCased())` : \(p.value.Type())?")
}
}
generatedSchemas.addLine("}")
}
case "any":
generatedSchemas.addLine(indent: 2, "public typealias `\(schema.key)` = JSONAny")
default:
throw ParsingError.topLevelSchemaUnknownType(schemaName: schema.key, type: schema.value.type ?? "nil - unknown type")
}
}
var generatesResources = ""
if let resources = resources {
for r in resources.sorted(by: { $0.key < $1.key }) {
generatesResources += r.value.generate(name: r.key)
}
}
return """
\(Discovery.License)
import Foundation
import OAuth2
import GoogleAPIRuntime
public class \(self.name.capitalized()) : Service {
public init(tokenProvider: TokenProvider) throws {
try super.init(tokenProvider, "\(self.baseUrl)")
}
\(generatedSchemas)
\(generatesResources)
}
"""
}
}
func main() throws {
let arguments = CommandLine.arguments
if (arguments.count > 1) {
let discoveryFileURL = URL(fileURLWithPath: arguments[1])
try processDiscoveryDocument(url: discoveryFileURL, name: discoveryFileURL.deletingPathExtension().lastPathComponent)
} else {
try interactiveServiceGeneration()
}
}
func processDiscoveryDocument(url: URL, name: String) throws {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
do {
let service = try decoder.decode(Service.self, from: data)
let code = try service.generate()
let fileURL = URL(fileURLWithPath: name).appendingPathExtension("swift")
try code.write(to: fileURL, atomically: true, encoding: .utf8)
print("wrote \(fileURL.path)")
} catch {
print("error \(error)\n")
}
}
func interactiveServiceGeneration() throws {
let data = try Data(contentsOf: URL(string: "https://www.googleapis.com/discovery/v1/apis")!)
let decoder = JSONDecoder()
let directoryList = try decoder.decode(DirectoryList.self, from: data)
var map : [Int:DirectoryItem] = [:]
var i = 1
for item in directoryList.items.filter({ $0.preferred }) {
map[i] = item
let istr = String.init(describing: i)
let padding = String(repeatElement(" ", count: 3 - istr.count))
print("\(padding + istr)) \(item.title)")
i += 1
}
var directoryItem: DirectoryItem?
repeat {
print("Please enter the number corresponding to the service or 0 to exit")
print("> ", terminator: "")
let input = readLine()
if input == "0" {
return
}
if let i = Int(input!), input != nil {
directoryItem = map[i]
}
} while directoryItem == nil
try processDiscoveryDocument(url: directoryItem!.discoveryRestUrl, name: directoryItem!.id.replacingOccurrences(of: ":", with: ""))
}
do {
try main()
} catch (let error) {
print("ERROR: \(error)\n")
}
| apache-2.0 | 8ea2a8b0af511a43d13b5d2592cf2134 | 39.501109 | 179 | 0.642779 | 4.04473 | false | false | false | false |
dvaughn1712/perfect-routing | PerfectLib/LibEvent.swift | 2 | 4084 | //
// LibEvent.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/5/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import LibEvent
#if os(Linux)
import SwiftGlibc
#endif
// I'm unsure why these aren't coming through
/** Indicates that a timeout has occurred. It's not necessary to pass
this flag to event_for new()/event_assign() to get a timeout. */
let EV_TIMEOUT: Int32 = 0x01
/** Wait for a socket or FD to become readable */
let EV_READ: Int32 = 0x02
/** Wait for a socket or FD to become writeable */
let EV_WRITE: Int32 = 0x04
typealias EventCallBack = (Int32, Int16, AnyObject?) -> ()
private typealias PrimEventCallBack = @convention(c) (Int32, Int16, UnsafeMutablePointer<Void>) -> ()
class LibEvent {
internal static let eventBase: LibEventBase = LibEventBase()
private var event: COpaquePointer? = nil
private var userData: AnyObject?
private var cb: EventCallBack?
private var base: LibEventBase?
private static var eventCallBack: PrimEventCallBack {
let c: PrimEventCallBack = {
(a,b,c) in
let evt = Unmanaged<LibEvent>.fromOpaque(COpaquePointer(c)).takeRetainedValue()
let queue = evt.base!.eventDispatchQueue
let userData: AnyObject? = evt.userData
let callBack: EventCallBack = evt.cb!
evt.base = nil
evt.cb = nil
evt.userData = nil
evt.del()
Threading.dispatchBlock(queue) {
callBack(a, b, userData)
}
}
return c
}
init(base: LibEventBase, fd: Int32, what: Int32, userData: AnyObject?, callBack: EventCallBack) {
self.userData = userData
self.cb = callBack
self.base = base
self.event = event_new(base.eventBase, fd, Int16(what), LibEvent.eventCallBack, UnsafeMutablePointer(Unmanaged.passRetained(self).toOpaque()))
}
deinit {
del()
}
func add(inout tv: timeval) {
event_add(event!, &tv)
}
func add(timeout: Double) {
if timeout == -1 {
event_add(event!, nil)
} else {
var tv: timeval = timeval()
let i = floor(timeout)
let f = timeout - i
tv.tv_sec = Int(i)
#if os(Linux)
tv.tv_usec = Int(f * 100000)
#else
tv.tv_usec = Int32(f * 100000)
#endif
event_add(event!, &tv)
}
}
func add() {
event_add(event!, nil)
}
func del() {
if let e = event {
event_free(e)
self.event = nil
}
}
}
let EVLOOP_NO_EXIT_ON_EMPTY = Int32(0/*0x04*/) // not supported until libevent 2.1
class LibEventBase {
var eventBase: COpaquePointer
private var baseDispatchQueue: Threading.ThreadQueue
var eventDispatchQueue: Threading.ThreadQueue
init() {
evthread_use_pthreads()
// !FIX! this is not ideal, but since we are the only ones dispatching to this queue,
// and it only happens from within the singular libevent loop, we can ensure is it not called concurrently.
baseDispatchQueue = Threading.createConcurrentQueue("LibEvent Base") //Threading.createSerialQueue("LibEvent Base")
eventDispatchQueue = Threading.createConcurrentQueue("LibEvent Event")
eventBase = event_base_new()
addDummyEvent()
triggerEventBaseLoop()
}
private func addDummyEvent() {
let event = LibEvent(base: self, fd: -1, what: EV_TIMEOUT, userData: nil) {
[weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in
self?.addDummyEvent()
}
event.add(1_000_000)
}
private func triggerEventBaseLoop() {
Threading.dispatchBlock(baseDispatchQueue) { [weak self] in
self?.eventBaseLoop()
}
}
private func eventBaseLoop() {
let r = event_base_dispatch(self.eventBase) //event_base_loop(self.eventBase, EVLOOP_NO_EXIT_ON_EMPTY)
if r == 1 {
triggerEventBaseLoop()
} else if r == -1 {
print("eventBaseLoop exited because of error")
}
}
}
| unlicense | 97ced5a81b16c7f8a5eaad0803fe646e | 23.902439 | 144 | 0.659158 | 3.331158 | false | false | false | false |
kallahir/MarvelFinder | MarvelFinder/CharacterListViewController.swift | 1 | 5270 | //
// ViewController.swift
// MarvelFinder
//
// Created by Itallo Rossi Lucas on 28/12/16.
// Copyright © 2016 Kallahir Labs. All rights reserved.
//
import UIKit
import AlamofireImage
class CharacterListViewController: UITableViewController {
let requests = MarvelRequests()
var offset = 0
var result: SearchResult!
var loadMoreFlag = false
var loadErrorFlag = false
var selectedCharacter: Character!
override func viewDidLoad() {
super.viewDidLoad()
self.loadCharacterList(offset: self.offset)
}
// MARK: TableView
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if self.result == nil || indexPath.row == self.result?.characters?.count {
if self.loadErrorFlag {
let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterListRetryCell", for: indexPath) as! CharacterListRetryCell
cell.tryAgainLabel.text = NSLocalizedString("Cell.tryAgain", comment: "")
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterListLoadingCell", for: indexPath) as! CharacterListLoadingCell
cell.loadingIndicator.startAnimating()
return cell
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterListCell", for: indexPath) as! CharacterListCell
let urlString = "\(self.result.characters![indexPath.row].thumbnail!)/landscape_incredible.\(self.result.characters![indexPath.row].thumbFormat!)"
cell.characterImage.af_setImage(withURL: URL(string: urlString)!, placeholderImage: UIImage(named: "placeholder_list"), imageTransition: UIImageView.ImageTransition.crossDissolve(0.3))
cell.characterName.text = self.result.characters![indexPath.row].name
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if self.result == nil || indexPath.row == self.result?.characters?.count {
return 88
}
return 185
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.result != nil {
return (self.result.characters?.count)! + 1
}
return 1
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if self.result == nil || indexPath.row == self.result?.characters?.count {
if self.loadErrorFlag {
self.loadErrorFlag = false
self.tableView.reloadData()
self.loadCharacterList(offset: self.offset)
return
}
return
}
self.selectedCharacter = self.result.characters![indexPath.row]
self.performSegue(withIdentifier: "DetailFromList", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailFromList" {
let characterDetailVC = segue.destination as! CharacterDetailViewController
characterDetailVC.character = self.selectedCharacter
}
let backItem = UIBarButtonItem()
backItem.title = NSLocalizedString("Navigation.back", comment: "")
navigationItem.backBarButtonItem = backItem
}
// MARK: Load more
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
let maxOffset = scrollView.contentSize.height - scrollView.frame.size.height
if (maxOffset - offset) <= 55 {
self.loadMore()
}
}
func loadMore(){
if self.loadMoreFlag == true {
self.loadMoreFlag = false
let offset = self.offset + 20
if self.result != nil {
if offset > self.result.total! {
return
}
}
self.loadCharacterList(offset: offset)
}
}
// MARK: Util
func loadCharacterList(offset: Int) {
self.requests.getCharacterList(offset: offset) { (result) in
guard let result = result else {
self.refreshTable(loadMore: false, loadError: true, offset: offset)
return
}
if self.result == nil {
self.result = result
} else {
for character in (result.characters)! {
self.result.characters?.append(character)
}
}
self.refreshTable(loadMore: true, loadError: false, offset: offset)
}
}
func refreshTable(loadMore: Bool, loadError: Bool, offset: Int) {
DispatchQueue.main.sync {
self.offset = offset
self.loadMoreFlag = loadMore
self.loadErrorFlag = loadError
self.tableView.reloadData()
}
}
}
| mit | dedc1fedd73b6ed393fa1c8d6bc2acff | 33.214286 | 192 | 0.587018 | 5.290161 | false | false | false | false |
mtransitapps/mtransit-for-ios | MonTransit/Source/Utils/DateUtils.swift | 1 | 4199 | //
// DateUtils.swift
// MonTransit
//
// Created by Thibault on 16-01-25.
// Copyright © 2016 Thibault. All rights reserved.
//
import UIKit
extension NSDate {
static func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
return components.day
}
func getDate() -> String{
let formatter = NSDateFormatter()
formatter.timeStyle = NSDateFormatterStyle.NoStyle
formatter.dateStyle = NSDateFormatterStyle.MediumStyle
return formatter.stringFromDate(self)
}
func getTime() -> String{
let formatter = NSDateFormatter()
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
formatter.dateStyle = NSDateFormatterStyle.NoStyle
return formatter.stringFromDate(self)
}
func getHour() -> Int{
let calendar = NSCalendar.currentCalendar()
let hour = calendar.component(NSCalendarUnit.Hour, fromDate: self)
return hour
}
func getYear() -> Int{
let calendar = NSCalendar.currentCalendar()
let year = calendar.component(NSCalendarUnit.Year, fromDate: self)
return year
}
func getMonth() -> Int{
let calendar = NSCalendar.currentCalendar()
let month = calendar.component(NSCalendarUnit.Month, fromDate: self)
return month
}
func getDay() -> Int{
let calendar = NSCalendar.currentCalendar()
let day = calendar.component(NSCalendarUnit.Day, fromDate: self)
return day
}
func getGtfsFormatTime() -> String{
// get the user's calendar
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Year,
NSCalendarUnit.Month,
NSCalendarUnit.Day,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Second
]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate:self)
return String(format: "%02d", dateTimeComponents.hour)
+ String(format: "%02d", dateTimeComponents.minute)
+ String(format: "%02d", dateTimeComponents.second)
}
func getDateToInt() -> Int{
// get the user's calendar
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Year,
NSCalendarUnit.Month,
NSCalendarUnit.Day,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Second
]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: self)
let wDateString = String(format: "%04d", dateTimeComponents.year) + String(format: "%02d", dateTimeComponents.month) + String(format: "%02d", dateTimeComponents.day)
return Int(wDateString)!
}
func substractDays(iDays:Int) -> NSDate{
let wNewDate = NSCalendar.currentCalendar().dateByAddingUnit(
.Day,
value: -iDays,
toDate: self,
options: NSCalendarOptions(rawValue: 0))
return wNewDate!
}
func getTimeWithFormat(iFormatter:NSDateFormatter) -> String{
return iFormatter.stringFromDate(self)
}
func getMinutesDiference(iCompareDate:NSDate) -> Int {
let calendar = NSCalendar.currentCalendar()
let datecomponenets = calendar.components(.Minute, fromDate: iCompareDate, toDate: self, options: [])
let wDiffMin = datecomponenets.minute
return wDiffMin
}
}
| apache-2.0 | c2807cab2d443680b0ca704132dca108 | 28.356643 | 173 | 0.601477 | 5.437824 | false | false | false | false |
ttlock/iOS_TTLock_Demo | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/SecureDFU/Characteristics/ButtonlessDFU.swift | 2 | 11442 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal enum ButtonlessDFUOpCode : UInt8 {
case enterBootloader = 0x01
case setName = 0x02
case responseCode = 0x20
var code: UInt8 {
return rawValue
}
}
internal enum ButtonlessDFUResultCode : UInt8 {
case success = 0x01
case opCodeNotSupported = 0x02
case operationFailed = 0x04
var description: String {
switch self {
case .success: return "Success"
case .opCodeNotSupported: return "Operation not supported"
case .operationFailed: return "Operation failed"
}
}
var code: UInt8 {
return rawValue
}
}
internal enum ButtonlessDFURequest {
case enterBootloader
case set(name : String)
var data : Data {
switch self {
case .enterBootloader:
return Data(bytes: [ButtonlessDFUOpCode.enterBootloader.code])
case .set(let name):
var data = Data(bytes: [ButtonlessDFUOpCode.setName.code])
data += UInt8(name.lengthOfBytes(using: String.Encoding.utf8))
data += name.utf8
return data
}
}
}
internal struct ButtonlessDFUResponse {
let opCode : ButtonlessDFUOpCode?
let requestOpCode : ButtonlessDFUOpCode?
let status : ButtonlessDFUResultCode?
init?(_ data: Data) {
// The correct response is always 3 bytes long: Response Op Code, Request Op Code and Status
let opCode : UInt8 = data[0]
let requestOpCode : UInt8 = data[1]
let status : UInt8 = data[2]
self.opCode = ButtonlessDFUOpCode(rawValue: opCode)
self.requestOpCode = ButtonlessDFUOpCode(rawValue: requestOpCode)
self.status = ButtonlessDFUResultCode(rawValue: status)
if self.opCode != .responseCode || self.requestOpCode == nil || self.status == nil {
return nil
}
}
var description: String {
return "Response (Op Code = \(requestOpCode!.rawValue), Status = \(status!.rawValue))"
}
}
internal class ButtonlessDFU : NSObject, CBPeripheralDelegate, DFUCharacteristic {
internal var characteristic: CBCharacteristic
internal var logger: LoggerHelper
internal var uuidHelper: DFUUuidHelper!
private var success: Callback?
private var report: ErrorCallback?
internal var valid: Bool {
return (characteristic.properties.isSuperset(of: [.write, .notify])
&& characteristic.uuid.isEqual(uuidHelper.buttonlessExperimentalCharacteristic))
|| characteristic.properties.isSuperset(of: [.write, .indicate])
}
/**
Returns true if the device address is expected to change. In that case,
the service should scan for another device using DFUPeripheralSelectorDelegate.
*/
internal var newAddressExpected: Bool {
return characteristic.uuid.isEqual(uuidHelper.buttonlessExperimentalCharacteristic)
|| characteristic.uuid.isEqual(uuidHelper.buttonlessWithoutBonds)
}
/**
Returns true for a buttonless DFU characteristic that may support setting
bootloader's name. This feature has been added in SDK 14.0 to Buttonless
service without bond sharing (the one with bond sharing does not change
device address so this feature is not needed).
The same characteristic from SDK 13.0 does not support it. Sending this
command to that characteristic will end with ButtonlessDFUResultCode.opCodeNotSupported.
*/
internal var maySupportSettingName: Bool {
return characteristic.uuid.isEqual(uuidHelper.buttonlessWithoutBonds)
}
// MARK: - Initialization
required init(_ characteristic: CBCharacteristic, _ logger: LoggerHelper) {
self.characteristic = characteristic
self.logger = logger
}
// MARK: - Characteristic API methods
/**
Enables notifications or indications for the DFU Control Point characteristics, depending on the characteristic property.
Reports success or an error using callbacks.
- parameter success: Method called when notifications were successfully enabled.
- parameter report: Method called in case of an error.
*/
func enable(onSuccess success: Callback?, onError report: ErrorCallback?) {
// Save callbacks
self.success = success
self.report = report
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
if characteristic.properties.contains(.indicate) {
logger.v("Enabling indications for \(characteristic.uuid.uuidString)...")
} else {
logger.v("Enabling notifications for \(characteristic.uuid.uuidString)...")
}
logger.d("peripheral.setNotifyValue(true, for: \(characteristic.uuid.uuidString))")
peripheral.setNotifyValue(true, for: characteristic)
}
/**
Sends given request to the Buttonless DFU characteristic. Reports success or an error
using callbacks.
- parameter request: Request to be sent.
- parameter success: Method called when peripheral reported with status success.
- parameter report: Method called in case of an error.
*/
func send(_ request: ButtonlessDFURequest, onSuccess success: Callback?, onError report: ErrorCallback?) {
// Save callbacks and parameter
self.success = success
self.report = report
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
let buttonlessUUID = characteristic.uuid.uuidString
logger.v("Writing to characteristic \(buttonlessUUID)...")
logger.d("peripheral.writeValue(0x\(request.data.hexString), for: \(buttonlessUUID), type: .withResponse)")
peripheral.writeValue(request.data, for: characteristic, type: .withResponse)
}
// MARK: - Peripheral Delegate callbacks
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
if error != nil {
if characteristic.properties.contains(.indicate) {
logger.e("Enabling indications failed")
logger.e(error!)
report?(.enablingControlPointFailed, "Enabling indications failed")
} else {
logger.e("Enabling notifications failed")
logger.e(error!)
report?(.enablingControlPointFailed, "Enabling notifications failed")
}
} else {
if characteristic.properties.contains(.indicate) {
logger.v("Indications enabled for \(characteristic.uuid.uuidString)")
logger.a("Buttonless DFU indications enabled")
} else {
logger.v("Notifications enabled for \(characteristic.uuid.uuidString)")
logger.a("Buttonless DFU notifications enabled")
}
success?()
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if error != nil {
logger.e("Writing to characteristic failed")
logger.e(error!)
report?(.writingCharacteristicFailed, "Writing to characteristic failed")
} else {
logger.i("Data written to \(characteristic.uuid.uuidString)")
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
// Ignore updates received for other characteristics
guard self.characteristic.isEqual(characteristic) else {
return
}
if error != nil {
// This characteristic is never read, the error may only pop up when notification/indication is received
logger.e("Receiving response failed")
logger.e(error!)
report?(.receivingNotificationFailed, "Receiving response failed")
} else {
if characteristic.properties.contains(.indicate) {
logger.i("Indication received from \(characteristic.uuid.uuidString), value (0x):\(characteristic.value!.hexString)")
} else {
logger.i("Notification received from \(characteristic.uuid.uuidString), value (0x):\(characteristic.value!.hexString)")
}
// Parse response received
let dfuResponse = ButtonlessDFUResponse(characteristic.value!)
if let dfuResponse = dfuResponse {
if dfuResponse.status == .success {
logger.a("\(dfuResponse.description) received")
success?()
} else {
logger.e("Error \(dfuResponse.status!.code): \(dfuResponse.status!.description)")
// The returned errod code is incremented by 90 or 9000 to match Buttonless DFU or Experimental Buttonless DFU remote codes
// See DFUServiceDelegate.swift -> DFUError
let offset = characteristic.uuid.isEqual(uuidHelper.buttonlessExperimentalCharacteristic) ? 9000 : 90
report?(DFUError(rawValue: Int(dfuResponse.status!.code) + offset)!, dfuResponse.status!.description)
}
} else {
logger.e("Unknown response received: 0x\(characteristic.value!.hexString)")
report?(.unsupportedResponse, "Unsupported response received: 0x\(characteristic.value!.hexString)")
}
}
}
}
| mit | 41088312be6a0325d87675b1cf12a155 | 42.177358 | 145 | 0.656092 | 5.272811 | false | false | false | false |
AvdLee/Moya | Tests/MoyaProviderIntegrationTests.swift | 3 | 11634 | import Quick
import Nimble
import OHHTTPStubs
import Alamofire
@testable import Moya
@testable import ReactiveMoya
func beIdenticalToResponse(_ expectedValue: Moya.Response) -> MatcherFunc<Moya.Response> {
return MatcherFunc { actualExpression, failureMessage in
do {
let instance = try actualExpression.evaluate()
return instance === expectedValue
} catch {
return false
}
}
}
class MoyaProviderIntegrationTests: QuickSpec {
override func spec() {
let userMessage = String(data: GitHub.userProfile("ashfurrow").sampleData, encoding: .utf8)
let zenMessage = String(data: GitHub.zen.sampleData, encoding: .utf8)
beforeEach {
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}) { _ in
return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil)
}
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/users/ashfurrow"}) { _ in
return OHHTTPStubsResponse(data: GitHub.userProfile("ashfurrow").sampleData, statusCode: 200, headers: nil)
}
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/basic-auth/user/passwd"}) { _ in
return OHHTTPStubsResponse(data: HTTPBin.basicAuth.sampleData, statusCode: 200, headers: nil)
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
describe("valid endpoints") {
describe("with live data") {
describe("a provider") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>()
}
it("returns real data for zen request") {
var message: String?
waitUntil { done in
provider.request(.zen) { result in
if case let .success(response) = result {
message = String(data: response.data, encoding: .utf8)
}
done()
}
}
expect(message) == zenMessage
}
it("returns real data for user profile request") {
var message: String?
waitUntil { done in
let target: GitHub = .userProfile("ashfurrow")
provider.request(target) { result in
if case let .success(response) = result {
message = String(data: response.data, encoding: .utf8)
}
done()
}
}
expect(message) == userMessage
}
it("uses a custom Alamofire.Manager request generation") {
let manager = StubManager()
let provider = MoyaProvider<GitHub>(manager: manager)
waitUntil { done in
provider.request(.zen) { _ in done() }
}
expect(manager.called) == true
}
it("uses other background queue") {
var isMainThread: Bool?
let queue = DispatchQueue(label: "background_queue", attributes: .concurrent)
let target: GitHub = .zen
waitUntil { done in
provider.request(target, queue:queue) { _ in
isMainThread = Thread.isMainThread
done()
}
}
expect(isMainThread) == false
}
it("uses main queue") {
var isMainThread: Bool?
let target: GitHub = .zen
waitUntil { done in
provider.request(target) { _ in
isMainThread = Thread.isMainThread
done()
}
}
expect(isMainThread) == true
}
}
describe("a provider with credential plugin") {
it("credential closure returns nil") {
var called = false
let plugin = CredentialsPlugin { _ in
called = true
return nil
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
expect(provider.plugins.count).to(equal(1))
waitUntil { done in
provider.request(.basicAuth) { _ in done() }
}
expect(called) == true
}
it("credential closure returns valid username and password") {
var called = false
var returnedData: Data?
let plugin = CredentialsPlugin { _ in
called = true
return URLCredential(user: "user", password: "passwd", persistence: .none)
}
let provider = MoyaProvider<HTTPBin>(plugins: [plugin])
let target = HTTPBin.basicAuth
waitUntil { done in
provider.request(target) { result in
if case let .success(response) = result {
returnedData = response.data
}
done()
}
}
expect(called) == true
expect(returnedData) == target.sampleData
}
}
describe("a provider with network activity plugin") {
it("notifies at the beginning of network requests") {
var called = false
let plugin = NetworkActivityPlugin { change in
if change == .began {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
provider.request(.zen) { _ in done() }
}
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
let plugin = NetworkActivityPlugin { change in
if change == .ended {
called = true
}
}
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
provider.request(.zen) { _ in done() }
}
expect(called) == true
}
}
describe("a provider with network logger plugin") {
var log = ""
var plugin: NetworkLoggerPlugin!
beforeEach {
log = ""
plugin = NetworkLoggerPlugin(verbose: true, output: { printing in
//mapping the Any... from items to a string that can be compared
let stringArray: [String] = printing.2.map { $0 as? String }.flatMap { $0 }
let string: String = stringArray.reduce("") { $0 + $1 + " " }
log += string
})
}
it("logs the request") {
let provider = MoyaProvider<GitHub>(plugins: [plugin])
waitUntil { done in
provider.request(.zen) { _ in done() }
}
expect(log).to( contain("Request:") )
expect(log).to( contain("{ URL: https://api.github.com/zen }") )
expect(log).to( contain("Request Headers: [:]") )
expect(log).to( contain("HTTP Request Method: GET") )
expect(log).to( contain("Response:") )
expect(log).to( contain("{ URL: https://api.github.com/zen } { status code: 200, headers") )
expect(log).to( contain("\"Content-Length\" = 43;") )
}
}
}
describe("a reactive provider with SignalProducer") {
var provider: ReactiveSwiftMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveSwiftMoyaProvider<GitHub>()
}
it("returns some data for zen request") {
var message: String?
waitUntil { done in
provider.request(.zen).startWithResult { result in
if case .success(let response) = result {
message = String(data: response.data, encoding: String.Encoding.utf8)
done()
}
}
}
expect(message) == zenMessage
}
it("returns some data for user profile request") {
var message: String?
waitUntil { done in
let target: GitHub = .userProfile("ashfurrow")
provider.request(target).startWithResult { result in
if case .success(let response) = result {
message = String(data: response.data, encoding: String.Encoding.utf8)
done()
}
}
}
expect(message) == userMessage
}
}
}
}
}
class StubManager: Manager {
var called = false
override func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
called = true
return super.request(urlRequest)
}
}
| mit | f1493b84c75377fcce309ba1dbb43b20 | 40.402135 | 123 | 0.389032 | 6.945672 | false | false | false | false |
janniklorenz/MyPlan | MyPlan/MPTableViewCellSubject.swift | 1 | 1606 | //
// MPTableViewCellSubject.swift
// MyPlan
//
// Created by Jannik Lorenz on 01.05.15.
// Copyright (c) 2015 Jannik Lorenz. All rights reserved.
//
import Foundation
class MPTableViewCellSubject: UITableViewCell {
var colorView: UILabel
var subject: Subject? {
didSet {
self.colorView.text = subject!.titleShort
self.colorView.backgroundColor = subject?.color
self.colorView.textColor = subject?.color.getReadableTextColor()
self.textLabel?.text = subject?.title
}
}
// MARK: - Init
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
colorView = UILabel()
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.separatorInset = UIEdgeInsets(top: 0, left: self.frame.size.height+5, bottom: 0, right: 15)
colorView.frame = CGRectMake(0, 0, self.frame.size.height, self.frame.size.height)
// colorView.layer.cornerRadius = self.frame.size.height*0.4
colorView.clipsToBounds = true
colorView.textAlignment = .Center
colorView.autoresizingMask = .FlexibleRightMargin | .FlexibleHeight
// colorView.layer.borderColor = UIColor.blackColor().CGColor
// colorView.layer.borderWidth = 1
colorView.alpha = 0.8
self.addSubview(colorView)
self.selectionStyle = .None
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | gpl-2.0 | 7b5fd2d8270bde5e5d5806ba16b56090 | 27.696429 | 104 | 0.620174 | 4.695906 | false | false | false | false |
OscarSwanros/swift | stdlib/public/core/RandomAccessCollection.swift | 2 | 12282 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection that supports efficient random-access index traversal.
///
/// In most cases, it's best to ignore this protocol and use the
/// `RandomAccessCollection` protocol instead, because it has a more complete
/// interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'RandomAccessCollection' instead")
public typealias RandomAccessIndexable = RandomAccessCollection
/// A collection that supports efficient random-access index traversal.
///
/// Random-access collections can move indices any distance and
/// measure the distance between indices in O(1) time. Therefore, the
/// fundamental difference between random-access and bidirectional collections
/// is that operations that depend on index movement or distance measurement
/// offer significantly improved efficiency. For example, a random-access
/// collection's `count` property is calculated in O(1) instead of requiring
/// iteration of an entire collection.
///
/// Conforming to the RandomAccessCollection Protocol
/// =================================================
///
/// The `RandomAccessCollection` protocol adds further constraints on the
/// associated `Indices` and `SubSequence` types, but otherwise imposes no
/// additional requirements over the `BidirectionalCollection` protocol.
/// However, in order to meet the complexity guarantees of a random-access
/// collection, either the index for your custom type must conform to the
/// `Strideable` protocol or you must implement the `index(_:offsetBy:)` and
/// `distance(from:to:)` methods with O(1) efficiency.
public protocol RandomAccessCollection : BidirectionalCollection
{
// FIXME(ABI): Associated type inference requires this.
associatedtype Element
// FIXME(ABI): Associated type inference requires this.
associatedtype Index
/// A collection that represents a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence : RandomAccessCollection
= RandomAccessSlice<Self>
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : RandomAccessCollection
= DefaultRandomAccessIndices<Self>
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence { get }
// FIXME(ABI): Associated type inference requires this.
subscript(position: Index) -> Element { get }
// FIXME(ABI): Associated type inference requires this.
var startIndex: Index { get }
// FIXME(ABI): Associated type inference requires this.
var endIndex: Index { get }
}
/// Supply the default "slicing" `subscript` for `RandomAccessCollection`
/// models that accept the default associated `SubSequence`,
/// `RandomAccessSlice<Self>`.
extension RandomAccessCollection where SubSequence == RandomAccessSlice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
@_inlineable
public subscript(bounds: Range<Index>) -> RandomAccessSlice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return RandomAccessSlice(base: self, bounds: bounds)
}
}
// TODO: swift-3-indexing-model - Make sure RandomAccessCollection has
// documented complexity guarantees, e.g. for index(_:offsetBy:).
// TODO: swift-3-indexing-model - (By creating an ambiguity?), try to
// make sure RandomAccessCollection models implement
// index(_:offsetBy:) and distance(from:to:), or they will get the
// wrong complexity.
/// Default implementation for random access collections.
extension RandomAccessCollection {
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position. The
/// operation doesn't require going beyond the limiting `numbers.endIndex`
/// value, so it succeeds.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The next example attempts to retrieve an index ten positions from
/// `numbers.startIndex`, but fails, because that distance is beyond the
/// index passed as `limit`.
///
/// let j = numbers.index(numbers.startIndex,
/// offsetBy: 10,
/// limitedBy: numbers.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - n: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// `limit` should be greater than `i` to have any effect. Likewise, if
/// `n < 0`, `limit` should be less than `i` to have any effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1)
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: tests.
let l = distance(from: i, to: limit)
if n > 0 ? l >= 0 && l < n : l <= 0 && n < l {
return nil
}
return index(i, offsetBy: n)
}
}
extension RandomAccessCollection
where Index : Strideable,
Index.Stride == IndexDistance,
Indices == CountableRange<Index> {
/// The indices that are valid for subscripting the collection, in ascending
/// order.
@_inlineable
public var indices: CountableRange<Index> {
return startIndex..<endIndex
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
@_inlineable
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: tests for the trap.
_failEarlyRangeCheck(
i, bounds: Range(uncheckedBounds: (startIndex, endIndex)))
return i.advanced(by: 1)
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
let result = i.advanced(by: -1)
// FIXME: swift-3-indexing-model: tests for the trap.
_failEarlyRangeCheck(
result, bounds: Range(uncheckedBounds: (startIndex, endIndex)))
return result
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1)
@_inlineable
public func index(_ i: Index, offsetBy n: Index.Stride) -> Index {
let result = i.advanced(by: n)
// This range check is not precise, tighter bounds exist based on `n`.
// Unfortunately, we would need to perform index manipulation to
// compute those bounds, which is probably too slow in the general
// case.
// FIXME: swift-3-indexing-model: tests for the trap.
_failEarlyRangeCheck(
result, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))
return result
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
///
/// - Complexity: O(1)
@_inlineable
public func distance(from start: Index, to end: Index) -> Index.Stride {
// FIXME: swift-3-indexing-model: tests for traps.
_failEarlyRangeCheck(
start, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))
_failEarlyRangeCheck(
end, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))
return start.distance(to: end)
}
}
| apache-2.0 | e524899d2365d4d7e41422c1fd19d24f | 40.214765 | 115 | 0.660479 | 4.377049 | false | false | false | false |
OscarSwanros/swift | test/decl/protocol/req/unsatisfiable.swift | 11 | 1790 | // RUN: %target-typecheck-verify-swift -swift-version 4
protocol P {
associatedtype A
associatedtype B
func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A == Self.B' on 'Self'}}
}
extension P {
func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B { }
}
struct X : P {
typealias A = X
typealias B = Int
}
protocol P2 {
associatedtype A
func f<T: P2>(_: T) where T.A == Self.A, T.A: P2 // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A: P2' on 'Self'}}
}
class C { }
protocol P3 {
associatedtype A
func f<T: P3>(_: T) where T.A == Self.A, T.A: C // expected-error{{instance method requirement 'f' cannot add constraint 'Self.A: C' on 'Self'}}
func g<T: P3>(_: T) where T.A: C, T.A == Self.A // expected-error{{instance method requirement 'g' cannot add constraint 'Self.A: C' on 'Self'}}
}
protocol Base {
associatedtype Assoc
}
// FIXME: The first error is redundant, isn't correct in what it states, and
// also should be emitted on the inheritance clause.
// FIXME: This used to /not/ error in Swift 3. It didn't impose any statically-
// enforced requirements, but the compiler crashed if you used anything but the
// same type.
protocol Sub1: Base { // expected-error {{type 'Self.SubAssoc' constrained to non-protocol, non-class type 'Self.Assoc'}}
associatedtype SubAssoc: Assoc // expected-error {{inheritance from non-protocol, non-class type 'Self.Assoc'}}
}
// FIXME: This error is incorrect in what it states and should be emitted on
// the where-clause.
protocol Sub2: Base { // expected-error {{type 'Self.SubAssoc' constrained to non-protocol, non-class type 'Self.Assoc'}}
associatedtype SubAssoc where SubAssoc: Assoc
}
| apache-2.0 | 4f072b3f319fb973e7a728cf66b3901f | 34.8 | 159 | 0.686592 | 3.358349 | false | false | false | false |
epiphanyapps/ProductivitySuite | Example/Pods/Kingfisher/Sources/AnimatedImageView.swift | 1 | 13118 | //
// AnimatableImageView.swift
// Kingfisher
//
// Created by bl4ckra1sond3tre on 4/22/16.
//
// The AnimatableImageView, AnimatedFrame and Animator is a modified version of
// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Reda Lemeden.
//
// 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.
//
// The name and characters used in the demo of this software are property of their
// respective owners.
import UIKit
import ImageIO
/// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image.
open class AnimatedImageView: UIImageView {
/// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView.
class TargetProxy {
private weak var target: AnimatedImageView?
init(target: AnimatedImageView) {
self.target = target
}
@objc func onScreenUpdate() {
target?.updateFrame()
}
}
// MARK: - Public property
/// Whether automatically play the animation when the view become visible. Default is true.
public var autoPlayAnimatedImage = true
/// The size of the frame cache.
public var framePreloadCount = 10
/// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true.
public var needsPrescaling = true
/// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling.
public var runLoopMode = RunLoopMode.commonModes {
willSet {
if runLoopMode == newValue {
return
} else {
stopAnimating()
displayLink.remove(from: .main, forMode: runLoopMode)
displayLink.add(to: .main, forMode: newValue)
startAnimating()
}
}
}
// MARK: - Private property
/// `Animator` instance that holds the frames of a specific image in memory.
private var animator: Animator?
/// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D
private var isDisplayLinkInitialized: Bool = false
/// A display link that keeps calling the `updateFrame` method on every screen refresh.
private lazy var displayLink: CADisplayLink = {
self.isDisplayLinkInitialized = true
let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
displayLink.add(to: .main, forMode: self.runLoopMode)
displayLink.isPaused = true
return displayLink
}()
// MARK: - Override
override open var image: Image? {
didSet {
if image != oldValue {
reset()
}
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
deinit {
if isDisplayLinkInitialized {
displayLink.invalidate()
}
}
override open var isAnimating: Bool {
if isDisplayLinkInitialized {
return !displayLink.isPaused
} else {
return super.isAnimating
}
}
/// Starts the animation.
override open func startAnimating() {
if self.isAnimating {
return
} else {
displayLink.isPaused = false
}
}
/// Stops the animation.
override open func stopAnimating() {
super.stopAnimating()
if isDisplayLinkInitialized {
displayLink.isPaused = true
}
}
override open func display(_ layer: CALayer) {
if let currentFrame = animator?.currentFrame {
layer.contents = currentFrame.cgImage
} else {
layer.contents = image?.cgImage
}
}
override open func didMoveToWindow() {
super.didMoveToWindow()
didMove()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
didMove()
}
// MARK: - Private method
/// Reset the animator.
private func reset() {
animator = nil
if let imageSource = image?.kf.imageSource?.imageRef {
animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount)
animator?.needsPrescaling = needsPrescaling
animator?.prepareFramesAsynchronously()
}
didMove()
}
private func didMove() {
if autoPlayAnimatedImage && animator != nil {
if let _ = superview, let _ = window {
startAnimating()
} else {
stopAnimating()
}
}
}
/// Update the current frame with the displayLink duration.
private func updateFrame() {
let duration: CFTimeInterval
// CA based display link is opt-out from ProMotion by default.
// So the duration and its FPS might not match.
// See [#718](https://github.com/onevcat/Kingfisher/issues/718)
if #available(iOS 10.0, tvOS 10.0, *) {
// By setting CADisableMinimumFrameDuration to YES in Info.plist may
// cause the preferredFramesPerSecond being 0
if displayLink.preferredFramesPerSecond == 0 {
duration = displayLink.duration
} else {
// Some devices (like iPad Pro 10.5) will have a different FPS.
duration = 1.0 / Double(displayLink.preferredFramesPerSecond)
}
} else {
duration = displayLink.duration
}
if animator?.updateCurrentFrame(duration: duration) ?? false {
layer.setNeedsDisplay()
}
}
}
/// Keeps a reference to an `Image` instance and its duration as a GIF frame.
struct AnimatedFrame {
var image: Image?
let duration: TimeInterval
static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0)
}
// MARK: - Animator
class Animator {
// MARK: Private property
fileprivate let size: CGSize
fileprivate let maxFrameCount: Int
fileprivate let imageSource: CGImageSource
fileprivate var animatedFrames = [AnimatedFrame]()
fileprivate let maxTimeStep: TimeInterval = 1.0
fileprivate var frameCount = 0
fileprivate var currentFrameIndex = 0
fileprivate var currentPreloadIndex = 0
fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0
fileprivate var needsPrescaling = true
/// Loop count of animated image.
private var loopCount = 0
var currentFrame: UIImage? {
return frame(at: currentFrameIndex)
}
var contentMode = UIViewContentMode.scaleToFill
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
/**
Init an animator with image source reference.
- parameter imageSource: The reference of animated image.
- parameter contentMode: Content mode of AnimatedImageView.
- parameter size: Size of AnimatedImageView.
- parameter framePreloadCount: Frame cache size.
- returns: The animator object.
*/
init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) {
self.imageSource = source
self.contentMode = mode
self.size = size
self.maxFrameCount = count
}
func frame(at index: Int) -> Image? {
return animatedFrames[safe: index]?.image
}
func prepareFramesAsynchronously() {
preloadQueue.async { [weak self] in
self?.prepareFrames()
}
}
private func prepareFrames() {
frameCount = CGImageSourceGetCount(imageSource)
if let properties = CGImageSourceCopyProperties(imageSource, nil),
let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int
{
self.loopCount = loopCount
}
let frameToProcess = min(frameCount, maxFrameCount)
animatedFrames.reserveCapacity(frameToProcess)
animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))}
currentPreloadIndex = (frameToProcess + 1) % frameCount
}
private func prepareFrame(at index: Int) -> AnimatedFrame {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
return AnimatedFrame.null
}
let defaultGIFFrameDuration = 0.100
let frameDuration = imageSource.kf.gifProperties(at: index).map {
gifInfo -> Double in
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
let duration = unclampedDelayTime ?? delayTime ?? 0.0
/**
http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
Many annoying ads specify a 0 duration to make an image flash as quickly as
possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
for any frames that specify a duration of <= 10 ms.
See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
*/
return duration > 0.011 ? duration : defaultGIFFrameDuration
} ?? defaultGIFFrameDuration
let image = Image(cgImage: imageRef)
let scaledImage: Image?
if needsPrescaling {
scaledImage = image.kf.resize(to: size, for: contentMode)
} else {
scaledImage = image
}
return AnimatedFrame(image: scaledImage, duration: frameDuration)
}
/**
Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
*/
func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
timeSinceLastFrameChange += min(maxTimeStep, duration)
guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else {
return false
}
timeSinceLastFrameChange -= frameDuration
let lastFrameIndex = currentFrameIndex
currentFrameIndex += 1
currentFrameIndex = currentFrameIndex % animatedFrames.count
if animatedFrames.count < frameCount {
preloadFrameAsynchronously(at: lastFrameIndex)
}
return true
}
private func preloadFrameAsynchronously(at index: Int) {
preloadQueue.async { [weak self] in
self?.preloadFrame(at: index)
}
}
private func preloadFrame(at index: Int) {
animatedFrames[index] = prepareFrame(at: currentPreloadIndex)
currentPreloadIndex += 1
currentPreloadIndex = currentPreloadIndex % frameCount
}
}
extension CGImageSource: KingfisherCompatible { }
extension Kingfisher where Base: CGImageSource {
func gifProperties(at index: Int) -> [String: Double]? {
let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary?
return properties?[kCGImagePropertyGIFDictionary] as? [String: Double]
}
}
extension Array {
subscript(safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
private func pure<T>(_ value: T) -> [T] {
return [value]
}
| mit | 134a340b4c1f56592fd986f5e35f522e | 34.550136 | 184 | 0.639427 | 5.354286 | false | false | false | false |
dsxNiubility/SXSwiftWeibo | 103 - swiftWeibo/103 - swiftWeibo/Classes/BusinessModel/AccessToken.swift | 1 | 2274 | //
// AccessToken.swift
// 103 - swiftWeibo
//
// Created by 董 尚先 on 15/3/3.
// Copyright (c) 2015年 shangxianDante. All rights reserved.
//
import UIKit
class AccessToken:NSObject,NSCoding{
var access_token:String?
/// token过期日期
var expiresDate: NSDate?
var remind_in: NSNumber?
var expires_in :NSNumber?{
didSet{
expiresDate = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
print("过期时间为--:\(expiresDate)")
}
}
var isExpired:Bool{
// 判断过期时间和系统时间,如果后面比较结果是升序,那就是当前日期比过期时间大。就是过期
return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
}
var uid : Int = 0
/// 传入字典的构造方法
init(dict:NSDictionary){
super.init()
self.setValuesForKeysWithDictionary(dict as [NSObject : AnyObject] as [NSObject:AnyObject])
}
/// 将数据保存到沙盒
func saveAccessToken(){
NSKeyedArchiver.archiveRootObject(self, toFile: AccessToken.tokenPath())
print("accesstoken地址是" + AccessToken.tokenPath())
}
/// 从沙盒读取 token 数据
class func loadAccessToken() -> AccessToken? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(tokenPath()) as? AccessToken
}
/// 返回保存的沙盒路径
class func tokenPath() -> String {
var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as!String
path = (path as NSString).stringByAppendingPathComponent("SXWeiboToken.plist")
return path
}
/// 普通的构造方法
override init() {}
func encodeWithCoder(encode: NSCoder) {
encode.encodeObject(access_token)
encode.encodeObject(expiresDate)
encode.encodeInteger(uid, forKey: "uid")
}
required init?(coder decoder:NSCoder){
access_token = decoder.decodeObject() as?String
expiresDate = decoder.decodeObject() as?NSDate
uid = decoder.decodeIntegerForKey("uid")
}
} | mit | 3864aba19e1d674eae113a5cab9fd71a | 24.9625 | 155 | 0.632466 | 4.633929 | false | false | false | false |
bradhilton/Allegro | Sources/SetValue.swift | 1 | 1539 | //
// ValueSetters.swift
// Allegro
//
// Created by Bradley Hilton on 3/17/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
/// Set value for key of an instance
public func setValue(value: Any, forKey key: String, inout ofInstance instance: Any) throws {
let field = try fieldForType(instance.dynamicType, withName: key)
try setValue(value, forKey: key, field: field, storage: mutableStorageForInstance(&instance))
}
/// Set value for key of an instance
public func setValue(value: Any, forKey key: String, ofInstance instance: AnyObject) throws {
var copy: Any = instance
try setValue(value, forKey: key, ofInstance: ©)
}
/// Set value for key of an instance
public func setValue<T>(value: Any, forKey key: String, inout ofInstance instance: T) throws {
let field = try fieldForType(T.self, withName: key)
try setValue(value, forKey: key, field: field, storage: mutableStorageForInstance(&instance))
}
private func fieldForType(type: Any.Type, withName name: String) throws -> Field {
guard let field = try fieldsForType(type).filter({ $0.name == name }).first else { throw Error.InstanceHasNoKey(type: type, key: name) }
return field
}
private func setValue(value: Any, forKey key: String, field: Field, storage: UnsafeMutablePointer<UInt8>) throws {
guard instanceValue(value, isOfType: field.type) else { throw Error.ValueIsNotOfType(value: value, type: field.type) }
var copy: Any = value
storage.advancedBy(field.offset).consumeBuffer(bytesForInstance(©))
}
| mit | 8d37b42a5a5bf8c349646ccb12ce816e | 41.722222 | 140 | 0.728218 | 3.788177 | false | false | false | false |
madoffox/Stretching | Stretching/Stretching/CellView.swift | 1 | 3291 | import JTAppleCalendar
private let preDateSelectable: Bool = true
private let todayColor: UIColor = UIColor.black
private let selectableDateColor: UIColor = .white
private let selectedRoundColor: UIColor = UIColor.red
class CellView: JTAppleDayCellView {
@IBOutlet weak var stableBackView: AnimationView!
@IBOutlet var selectedView: AnimationView!
@IBOutlet var dayLabel: UILabel!
override func awakeFromNib() {
//self.stableBackView.layer.cornerRadius = self.frame.height * 0.13
//self.stableBackView.layer.borderColor = UIColor.white.cgColor
//self.stableBackView.layer.borderWidth = 0.3
}
func handleCellSelection(cellState: CellState, date: Date, selectedDate: Date) {
//InDate, OutDate
if cellState.dateBelongsTo != .thisMonth {
self.dayLabel.text = ""
self.isUserInteractionEnabled = false
self.stableBackView.isHidden = true
} else if date.isSmaller(to: Date()) && !preDateSelectable {
self.dayLabel.text = "-"
self.dayLabel.textColor = UIColor.white
self.isUserInteractionEnabled = false
self.stableBackView.isHidden = true
}else{
self.stableBackView.isHidden = false
self.isUserInteractionEnabled = true
dayLabel.text = cellState.text
dayLabel.textColor = selectableDateColor
}
configueViewIntoBubbleView(cellState, date: date)
if date.isEqual(to: Date()) {
if !cellState.isSelected {
self.dayLabel.textColor = todayColor
}
}
}
func cellSelectionChanged(_ cellState: CellState, date: Date) {
if cellState.isSelected == true {
if self.selectedView.isHidden == true {
configueViewIntoBubbleView(cellState, date: date)
self.selectedView.animateWithBounceEffect(withCompletionHandler: {
})
}
} else {
configueViewIntoBubbleView(cellState, date: date, animateDeselection: true)
}
}
fileprivate func configueViewIntoBubbleView(_ cellState: CellState, date: Date, animateDeselection: Bool = false) {
if cellState.isSelected && self.isUserInteractionEnabled {
self.selectedView.isHidden = false
self.selectedView.layer.cornerRadius = self.frame.height * 0.37
self.selectedView.layer.backgroundColor = selectedRoundColor.cgColor
self.dayLabel.textColor = .white
} else {
if animateDeselection {
if date.isEqual(to: Date())
{
self.dayLabel.textColor = todayColor
}else{
self.dayLabel.textColor = selectableDateColor
}
if self.selectedView.isHidden == false {
self.selectedView.animateWithFadeEffect(withCompletionHandler: { () -> Void in
self.selectedView.isHidden = true
self.selectedView.alpha = 1
})
}
} else {
self.selectedView.isHidden = true
}
}
}
}
| mit | 47ec0b962d454f8507464741fdb920e5 | 36.827586 | 119 | 0.592525 | 5.174528 | false | false | false | false |
kitasuke/SwiftProtobufSample | Client/Client/ViewController.swift | 1 | 1623 | //
// ViewController.swift
// Client
//
// Created by Yusuke Kita on 12/18/16.
// Copyright © 2016 Yusuke Kita. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet private weak var tableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else {
return UITableViewCell()
}
if indexPath.row == 0 {
cell.textLabel?.text = "protobuf"
} else {
cell.textLabel?.text = "JSON"
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let viewController = storyboard?.instantiateViewController(withIdentifier: String(describing: TalkViewController.self)) as? TalkViewController else {
return
}
if indexPath.row == 0 {
viewController.contentType = .protobuf
} else {
viewController.contentType = .json
}
navigationController?.pushViewController(viewController, animated: true)
}
}
| mit | b77130f93bf54be175eb2d0a03d15093 | 30.192308 | 163 | 0.636868 | 5.47973 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Core/Intersections2D.swift | 1 | 9112 | //
// Intersections2D.swift
// CesiumKit
//
// Created by Ryan Walklin on 2/04/2016.
// Copyright © 2016 Test Toast. All rights reserved.
//
import Foundation
/**
* Contains functions for operating on 2D triangles.
*
* @namespace
* @alias Intersections2D
*/
class Intersections2D {
/**
* Splits a 2D triangle at given axis-aligned threshold value and returns the resulting
* polygon on a given side of the threshold. The resulting polygon may have 0, 1, 2,
* 3, or 4 vertices.
*
* @param {Number} threshold The threshold coordinate value at which to clip the triangle.
* @param {Boolean} keepAbove true to keep the portion of the triangle above the threshold, or false
* to keep the portion below.
* @param {Number} u0 The coordinate of the first vertex in the triangle, in counter-clockwise order.
* @param {Number} u1 The coordinate of the second vertex in the triangle, in counter-clockwise order.
* @param {Number} u2 The coordinate of the third vertex in the triangle, in counter-clockwise order.
* @param {Number[]} [result] The array into which to copy the result. If this parameter is not supplied,
* a new array is constructed and returned.
* @returns {Number[]} The polygon that results after the clip, specified as a list of
* vertices. The vertices are specified in counter-clockwise order.
* Each vertex is either an index from the existing list (identified as
* a 0, 1, or 2) or -1 indicating a new vertex not in the original triangle.
* For new vertices, the -1 is followed by three additional numbers: the
* index of each of the two original vertices forming the line segment that
* the new vertex lies on, and the fraction of the distance from the first
* vertex to the second one.
*
* @example
* var result = Cesium.Intersections2D.clipTriangleAtAxisAlignedThreshold(0.5, false, 0.2, 0.6, 0.4);
* // result === [2, 0, -1, 1, 0, 0.25, -1, 1, 2, 0.5]
*/
class func clipTriangleAtAxisAlignedThreshold (threshold thresholdInt: Int, keepAbove: Bool, u0 u0Int: Int, u1 u1Int: Int, u2 u2Int: Int) -> [Double] {
var result = [Double]()
let threshold = Double(thresholdInt)
let u0 = Double(u0Int)
let u1 = Double(u1Int)
let u2 = Double(u2Int)
let u0Behind: Bool
let u1Behind: Bool
let u2Behind: Bool
if keepAbove {
u0Behind = u0 < threshold
u1Behind = u1 < threshold
u2Behind = u2 < threshold
} else {
u0Behind = u0 > threshold
u1Behind = u1 > threshold
u2Behind = u2 > threshold
}
let numBehind = Int(u0Behind) + Int(u1Behind) + Int(u2Behind)
var u01Ratio: Double
var u02Ratio: Double
var u12Ratio: Double
var u10Ratio: Double
var u20Ratio: Double
var u21Ratio: Double
if numBehind == 1 {
if u0Behind {
u01Ratio = (threshold - u0) / (u1 - u0)
u02Ratio = (threshold - u0) / (u2 - u0)
result.append(1)
result.append(2)
if u02Ratio != 1.0 {
result.append(-1)
result.append(0)
result.append(2)
result.append(u02Ratio)
}
if u01Ratio != 1.0 {
result.append(-1)
result.append(0)
result.append(1)
result.append(u01Ratio)
}
} else if u1Behind {
u12Ratio = (threshold - u1) / (u2 - u1)
u10Ratio = (threshold - u1) / (u0 - u1)
result.append(2);
result.append(0);
if u10Ratio != 1.0 {
result.append(-1)
result.append(1)
result.append(0)
result.append(u10Ratio)
}
if u12Ratio != 1.0 {
result.append(-1)
result.append(1)
result.append(2)
result.append(u12Ratio)
}
} else if (u2Behind) {
u20Ratio = (threshold - u2) / (u0 - u2);
u21Ratio = (threshold - u2) / (u1 - u2);
result.append(0)
result.append(1)
if u21Ratio != 1.0 {
result.append(-1)
result.append(2)
result.append(1)
result.append(u21Ratio)
}
if u20Ratio != 1.0 {
result.append(-1)
result.append(2)
result.append(0)
result.append(u20Ratio)
}
}
} else if numBehind == 2 {
if !u0Behind && u0 != threshold {
u10Ratio = (threshold - u1) / (u0 - u1)
u20Ratio = (threshold - u2) / (u0 - u2)
result.append(0)
result.append(-1)
result.append(1)
result.append(0)
result.append(u10Ratio)
result.append(-1)
result.append(2)
result.append(0)
result.append(u20Ratio)
} else if !u1Behind && u1 != threshold {
u21Ratio = (threshold - u2) / (u1 - u2)
u01Ratio = (threshold - u0) / (u1 - u0)
result.append(1)
result.append(-1)
result.append(2)
result.append(1)
result.append(u21Ratio)
result.append(-1)
result.append(0)
result.append(1)
result.append(u01Ratio)
} else if !u2Behind && u2 != threshold {
u02Ratio = (threshold - u0) / (u2 - u0)
u12Ratio = (threshold - u1) / (u2 - u1)
result.append(2);
result.append(-1)
result.append(0)
result.append(2)
result.append(u02Ratio)
result.append(-1)
result.append(1)
result.append(2)
result.append(u12Ratio)
}
} else if numBehind != 3 {
// Completely in front of threshold
result.append(0)
result.append(1)
result.append(2)
}
// else Completely behind threshold
return result
}
/**
* Compute the barycentric coordinates of a 2D position within a 2D triangle.
*
* @param {Number} x The x coordinate of the position for which to find the barycentric coordinates.
* @param {Number} y The y coordinate of the position for which to find the barycentric coordinates.
* @param {Number} x1 The x coordinate of the triangle's first vertex.
* @param {Number} y1 The y coordinate of the triangle's first vertex.
* @param {Number} x2 The x coordinate of the triangle's second vertex.
* @param {Number} y2 The y coordinate of the triangle's second vertex.
* @param {Number} x3 The x coordinate of the triangle's third vertex.
* @param {Number} y3 The y coordinate of the triangle's third vertex.
* @param {Cartesian3} [result] The instance into to which to copy the result. If this parameter
* is undefined, a new instance is created and returned.
* @returns {Cartesian3} The barycentric coordinates of the position within the triangle.
*
* @example
* var result = Cesium.Intersections2D.computeBarycentricCoordinates(0.0, 0.0, 0.0, 1.0, -1, -0.5, 1, -0.5);
* // result === new Cesium.Cartesian3(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0);
*/
static func computeBarycentricCoordinates (x: Double, y: Double, x1: Double, y1: Double, x2: Double, y2: Double, x3: Double, y3: Double) -> Cartesian3 {
let x1mx3 = x1 - x3
let x3mx2 = x3 - x2
let y2my3 = y2 - y3
let y1my3 = y1 - y3
let inverseDeterminant = 1.0 / (y2my3 * x1mx3 + x3mx2 * y1my3)
let ymy3 = y - y3
let xmx3 = x - x3
let l1 = (y2my3 * xmx3 + x3mx2 * ymy3) * inverseDeterminant
let l2 = (-y1my3 * xmx3 + x1mx3 * ymy3) * inverseDeterminant
let l3 = 1.0 - l1 - l2
return Cartesian3(x: l1, y: l2, z: l3)
}
}
| apache-2.0 | c1a540ccf0bf14326394c1797533a70e | 38.103004 | 156 | 0.496872 | 4.122624 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Reddit/OAuth/AuthorizeRequest.swift | 1 | 2494 | //
// AuthorizeRequest.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import ModestProposal
public enum TokenDuration : String {
case Temporary = "temporary"
case Permanent = "permanent"
}
public class AuthorizeRequest {
let clientID: String // The client ID generated during app registration
let state: String // A string of your choosing
let redirectURI: NSURL // The redirect URI you have specified during registration
let duration: TokenDuration // Either temporary or permanent
let scope: [OAuthScope] // A comma separated list of scope strings
public init(clientID: String, state: String, redirectURI: NSURL, duration: TokenDuration, scope: [OAuthScope]) {
self.clientID = clientID
self.state = state
self.redirectURI = redirectURI
self.duration = duration
self.scope = scope
}
public func buildURL(prototype: NSURL) -> NSURL? {
return prototype.relativeToPath(
"/api/v1/authorize.compact",
parameters: [
"client_id": clientID,
"response_type": "code",
"state": state,
"redirect_uri": redirectURI.absoluteString,
"duration": duration.rawValue,
"scope": rawValues(scope).joinWithSeparator(","),
]
)
}
}
| mit | a2d5c47503e3e6a1c643e5ff27a5aa41 | 39.225806 | 116 | 0.689655 | 4.768642 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | UberGoCore/UberGoCore/UberOauth.swift | 1 | 5336 | //
// UberAuth.swift
// UberGoCore
//
// Created by Nghia Tran on 6/3/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Foundation
import OAuthSwift
import RxSwift
public class UberAuth {
// MARK: - Variable
public var callbackObserverPublish = PublishSubject<NSAppleEventDescriptor>()
public var loginPublisher = PublishSubject<Void>()
fileprivate lazy var _oauthUber: OAuth2Swift = self.lazyOauthUber()
fileprivate let disposeBag = DisposeBag()
// MARK: - Share
public static let share = UberAuth()
// MARK: - Persistant Store
fileprivate let persistantStore = UserDefaults.standard
fileprivate static let PersistantStoreKey = "Uber.CurrentUser"
// MARK: - Current User
public fileprivate(set) var currentUserVariable = Variable<UserObj?>(nil)
public var currentUser: UserObj? { return currentUserVariable.value }
public var authenStateObj: Observable<AuthenticationState>
// Lock
fileprivate let lock = NSLock()
fileprivate let storeLock = NSLock()
// MARK: - Init
public init() {
authenStateObj = currentUserVariable.asObservable()
.map { $0 == nil ? .unAuthenticated : .authenticated }
.distinctUntilChanged()
// Load disk
loadPersistantUser()
currentUserVariable.asObservable()
.subscribe(onNext: {[unowned self] (userObj) in
self.savePersistantUser(userObj)
})
.addDisposableTo(disposeBag)
loginPublisher.asObservable()
.flatMapLatest { [unowned self] _ -> Observable<OAuthSwiftCredential?> in
return self.requestOauthWithUber()
}
.subscribe(onNext: {[unowned self] credential in
guard let credential = credential else { return }
self.convertToCurrentUser(credential)
})
.addDisposableTo(disposeBag)
callbackObserverPublish
.subscribe(onNext: { (event) in
if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue,
let url = URL(string: urlString) {
UberAuth.applicationHandle(url: url)
}
})
.addDisposableTo(disposeBag)
}
// MARK: - Public
public func logout() {
// Lock
lock.lock()
defer {
self.lock.unlock()
}
currentUserVariable.value = nil
}
fileprivate class func applicationHandle(url: URL) {
OAuthSwift.handle(url: url)
}
}
// MARK: - Private
extension UberAuth {
fileprivate func lazyOauthUber() -> OAuth2Swift {
return OAuth2Swift(
consumerKey: Constants.UberApp.ClientID,
consumerSecret: Constants.UberApp.SecretID,
authorizeUrl: Constants.UberApp.AuthorizeUrl,
accessTokenUrl: Constants.UberApp.AccessTokenUrl,
responseType: Constants.UberApp.ResponseType
)
}
fileprivate func requestOauthWithUber() -> Observable<OAuthSwiftCredential?> {
return Observable<OAuthSwiftCredential?>.create {[unowned self] (observer) -> Disposable in
_ = self._oauthUber.authorize (
withCallbackURL: URL(string: Constants.UberApp.CallBackUrl)!,
scope: "",
state: "UBER",
success: { credential, _, _ in
print(credential.oauthToken)
observer.onNext(credential)
observer.onCompleted()
},
failure: { error in
print(error.localizedDescription)
observer.onNext(nil)
observer.onCompleted()
})
return Disposables.create()
}
}
}
// MARK: - Authentication
extension UberAuth {
fileprivate func loadPersistantUser() {
// Lock
lock.lock()
defer {
self.lock.unlock()
}
guard let data = UserDefaults.standard.data(forKey: UberAuth.PersistantStoreKey) else { return }
guard let userObj = NSKeyedUnarchiver.unarchiveObject(with: data) as? UserObj else { return }
currentUserVariable.value = userObj
}
fileprivate func savePersistantUser(_ userObj: UserObj?) {
if let userObj = userObj {
// Lock
storeLock.lock()
defer {
self.storeLock.unlock()
}
let data = NSKeyedArchiver.archivedData(withRootObject: userObj)
persistantStore.set(data, forKey: UberAuth.PersistantStoreKey)
persistantStore.synchronize()
} else {
// Lock
storeLock.lock()
defer {
self.storeLock.unlock()
}
// Remove
persistantStore.removeObject(forKey: UberAuth.PersistantStoreKey)
persistantStore.synchronize()
}
}
public func convertToCurrentUser(_ credential: OAuthSwiftCredential) {
// Lock
lock.lock()
defer {
self.lock.unlock()
}
let token = AuthToken(credential: credential)
let user = UserObj(authToken: token)
currentUserVariable.value = user
}
}
| mit | 42dcea67784377309ebfe954aa309de4 | 28.804469 | 110 | 0.592877 | 5.085796 | false | false | false | false |
cjcaufield/SecretKit | SecretKit/ios/SGDynamicTableViewController.swift | 1 | 32476 | //
// SGDynamicTableViewController.swift
// SecretKit
//
// Created by Colin Caufield on 4/17/15.
// Copyright (c) 2015 Secret Geometry, Inc. All rights reserved.
//
import UIKit
open class SGDynamicTableViewController: UITableViewController,
UITextFieldDelegate,
UITextViewDelegate,
UIPickerViewDelegate
{
// MARK: Properties
open var tableData = SGTableData()
open var revealedCellIndexPath: IndexPath?
open var hasRegisteredObservers = false
open var showDoneButton = false
open var autosave = false
// MARK: Title
open var titleString: String {
return self.title ?? "Untitled"
}
open func refreshTitle() {
let title = self.titleString
if title == "" {
self.title = "Untitled"
} else {
self.title = title
}
}
// MARK: Object
open var object: AnyObject? {
willSet {
self.unregisterObservers()
}
didSet {
if self.object != nil {
self.registerObservers()
}
if self.tableView != nil {
self.configureView()
}
}
}
// MARK: Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
self.refreshTitle()
let bundle = Bundle(for: SGDynamicTableViewController.self)
self.registerCellNib(name: DATE_PICKER_CELL_ID, bundle: bundle)
self.registerCellNib(name: PICKER_CELL_ID, bundle: bundle)
self.registerCellNib(name: LABEL_CELL_ID, bundle: bundle)
self.registerCellNib(name: SWITCH_CELL_ID, bundle: bundle)
self.registerCellNib(name: SLIDER_CELL_ID, bundle: bundle)
self.registerCellNib(name: TEXT_FIELD_CELL_ID, bundle: bundle)
self.registerCellNib(name: TEXT_VIEW_CELL_ID, bundle: bundle)
self.registerCellNib(name: TIME_PICKER_CELL_ID, bundle: bundle)
self.registerCellNib(name: SEGMENTED_CELL_ID, bundle: bundle)
self.registerCellNib(name: COLOR_CELL_ID, bundle: bundle)
self.tableData = self.makeTableData()
assert(self.dataMatchesTable)
self.registerObservers()
self.configureView()
self.tableView.alwaysBounceVertical = false
}
open func registerCellNib(name: String, bundle: Bundle? = nil) {
let nib = UINib(nibName: name, bundle: bundle)
self.tableView.register(nib, forCellReuseIdentifier: name)
}
open func makeTableData() -> SGTableData {
return SGTableData()
}
open func refreshData() {
self.refreshTitle()
self.tableView.reloadData()
}
open func configureView() {
if self.showDoneButton {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
}
if self.title == nil || self.title == "" {
if let name = self.object?.value(forKey: "name") as? String {
self.title = name
} else {
self.title = "Untitled"
}
}
}
open func done(sender: AnyObject) {
let _ = self.navigationController?.popViewController(animated: true)
}
deinit {
self.unregisterObservers()
}
// MARK: Key-Value Coding
open func registerObservers() {
if self.hasRegisteredObservers {
return
}
if self.object == nil || self.tableData.sections.count == 0 {
return
}
for section in self.tableData.sections {
for data in section.rows {
if let path = data.modelPath {
self.object?.addObserver(
self,
forKeyPath: path,
options: NSKeyValueObservingOptions([.new, .old]),
context: nil
)
}
}
}
self.hasRegisteredObservers = true
}
open func unregisterObservers() {
if !self.hasRegisteredObservers {
return
}
if self.object == nil || self.tableData.sections.count == 0 {
return
}
for section in self.tableData.sections {
for data in section.rows {
if let path = data.modelPath {
self.object?.removeObserver(
self,
forKeyPath: path,
context: nil
)
}
}
}
self.hasRegisteredObservers = false
}
open func path(_ path1: String?, isAncestorOf path2: String?) -> Bool {
if path1 == nil || path2 == nil {
return false
}
let comps1 = path1!.components(separatedBy: ".")
let comps2 = path2!.components(separatedBy: ".")
for i in 0 ..< comps1.count {
if comps1[i] != comps2[i] {
return false
}
}
return true
}
open override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
for section in self.tableData.sections {
for data in section.rows {
if self.path(keyPath, isAncestorOf: data.modelPath) {
self.dataModelWillChange(data)
self.dataModelDidChange(data)
if let indexPath = self.indexPathForData(data) {
self.configureCellAtIndexPath(indexPath)
}
}
}
}
}
open func dataModelWillChange(_ data: SGRowData) {
// empty
}
open func dataModelDidChange(_ data: SGRowData) {
// empty
}
// MARK: TextFields
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
open func textFieldDidEndEditing(_ textField: UITextField) {
if let data = self.dataForControl(textField) {
if let path = data.modelPath {
if let target = self.targetForData(data) {
self.dataModelWillChange(data)
target.setValue(textField.text, forKeyPath: path)
self.dataModelDidChange(data)
}
if autosave {
SGData.shared.save()
}
}
}
}
// MARK: TextViews
open func textViewDidEndEditing(_ textView: UITextView) {
if let data = self.dataForControl(textView) {
if let path = data.modelPath {
if let target = self.targetForData(data) {
self.dataModelWillChange(data)
target.setValue(textView.text, forKeyPath: path)
self.dataModelDidChange(data)
}
if autosave {
SGData.shared.save()
}
}
}
}
// MARK: Switches
open func switchDidChange(_ toggle: UISwitch) {
if let data = self.dataForControl(toggle) {
if let path = data.modelPath {
if let target = self.targetForData(data) {
self.dataModelWillChange(data)
target.setValue(toggle.isOn, forKeyPath: path)
self.dataModelDidChange(data)
}
if autosave {
SGData.shared.save()
}
}
}
}
// MARK: Sliders
open func sliderDidChange(_ slider: UISlider) {
if let data = self.dataForControl(slider) {
if let path = data.modelPath {
if let target = self.targetForData(data) {
self.dataModelWillChange(data)
target.setValue(slider.value, forKeyPath: path)
self.dataModelDidChange(data)
}
if autosave {
SGData.shared.save()
}
}
}
}
// MARK: PickerViews
open func configurePickerView(_ picker: UIPickerView, forModelPath path: String?) {
//
}
open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return ""
}
open func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//
}
open func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 0
}
open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 0
}
// MARK: DatePickers
open func datePickerDidChange(_ picker: UIDatePicker) {
// Update the model.
if let data = self.dataForControl(picker) {
if let path = data.modelPath {
if let target = self.targetForData(data) {
let countdown = (picker.datePickerMode == .countDownTimer)
let value = (countdown) ? picker.countDownDuration as AnyObject : picker.date as AnyObject
self.dataModelWillChange(data)
target.setValue(value, forKeyPath: path)
self.dataModelDidChange(data)
}
if autosave {
SGData.shared.save()
}
}
}
// Update the cell above.
if let path = self.revealedCellIndexPath?.previous() {
if let cell = self.tableView.cellForRow(at: path as IndexPath) {
self.configureCell(cell, atIndexPath: path)
}
}
}
// MARK: SegmentedControls
open func configureSegmentedControl(_ control: UISegmentedControl, forModelPath path: String?) {
//
}
open func segmentedControlDidChange(control: UISegmentedControl) {
if let data = self.dataForControl(control) {
if let path = data.modelPath {
if let target = self.targetForData(data) {
self.dataModelWillChange(data)
target.setValue(control.selectedSegmentIndex, forKeyPath: path)
self.dataModelDidChange(data)
}
if autosave {
SGData.shared.save()
}
}
}
}
// MARK: TableViewController
open override func numberOfSections(in tableView: UITableView) -> Int {
return self.tableData.sections.count
}
open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// CJC todo: don't hardcode these.
switch self.cellIdentifierForIndexPath(indexPath) {
case TIME_PICKER_CELL_ID:
return 216.0
case DATE_PICKER_CELL_ID:
return 216.0
case TEXT_VIEW_CELL_ID:
return 178.0
case PICKER_CELL_ID:
return 162.0
default:
return self.tableView.rowHeight
}
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: NSInteger) -> NSInteger {
var numRows = self.tableData.sections[section].rows.count
if section == self.revealedCellIndexPath?.section {
numRows += 1
}
return numRows
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = self.cellIdentifierForIndexPath(indexPath)
var cell = self.tableView.dequeueReusableCell(withIdentifier: cellID)
if cell == nil {
if cellID == BASIC_CELL_ID {
cell = UITableViewCell(style: .default, reuseIdentifier: cellID)
cell?.textLabel?.font = cell?.textLabel?.font.withSize(16.0)
} else {
cell = UITableViewCell(style: .value1, reuseIdentifier: cellID)
cell?.textLabel?.font = cell?.textLabel?.font.withSize(16.0)
cell?.detailTextLabel?.font = cell?.detailTextLabel?.font.withSize(16.0)
}
}
self.configureCell(cell!, atIndexPath: indexPath)
return cell!
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = self.tableView.cellForRow(at: indexPath as IndexPath) {
if let data = self.dataForIndexPath(indexPath) {
if let segueName = data.segueName {
self.performSegue(withIdentifier: segueName, sender: cell)
return
}
}
}
}
open override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
if let cell = self.tableView.cellForRow(at: indexPath as IndexPath) {
self.tableView.deselectRow(at: indexPath as IndexPath, animated: true)
if self.canExpandCell(cell, atIndexPath: indexPath) {
self.displayRevealedCellForRowAtIndexPath(indexPath)
}
else if let data = self.dataForIndexPath(indexPath) {
if let action = data.action {
if self.responds(to: action) {
self.perform(action, with: cell)
}
}
self.didSelectData(data)
if let segueName = data.segueName {
self.performSegue(withIdentifier: segueName, sender: cell)
}
}
}
}
// MARK: Data
open var dataMatchesTable: Bool {
// TODO: Add logic to handle hidden rows.
// Check for mismatched section count.
if self.tableView.numberOfSections != self.tableData.sections.count {
return false
}
// Check for mismatched row counts.
var index = 0
for section in self.tableData.sections {
if self.tableView.numberOfRows(inSection: index) != section.rows.count {
return false
}
index += 1
}
return true
}
open func didSelectData(_ data: SGRowData) {
// nothing
}
// MARK: Mapping
open func targetForData(_ data: SGRowData) -> AnyObject? {
return (data.targetType == .Object) ? self.object : self
}
open func cellForControl(_ control: UIView) -> UITableViewCell? {
return control.superview?.superview as? UITableViewCell
}
open func dataForControl(_ control: UIView) -> SGRowData? {
if let cell = self.cellForControl(control) {
return self.dataForCell(cell);
}
return nil
}
open func dataForCell(_ cell: UITableViewCell) -> SGRowData? {
if let path = self.tableView.indexPath(for: cell) {
return self.dataForIndexPath(path)
}
return nil
}
open func cellForData(_ data: SGRowData) -> UITableViewCell? {
if let indexPath = self.indexPathForData(data) {
return self.tableView.cellForRow(at: indexPath)
}
return nil
}
open func cellForModelPath(_ modelPath: String) -> UITableViewCell? {
var s = 0
var r = 0
for section in self.tableData.sections {
for data in section.rows {
if modelPath == data.modelPath {
let indexPath = IndexPath(row: r, section: s)
return self.tableView.cellForRow(at: indexPath)
}
r += 1
}
r = 0
s += 1
}
return nil
}
open func dataForIndexPath(_ indexPath: IndexPath) -> SGRowData? {
let modelPath = self.dynamicIndexPath(for: indexPath)
if modelPath.section < self.tableData.sections.count {
let section = self.tableData.sections[modelPath.section]
if modelPath.row < section.rows.count {
return section.rows[modelPath.row]
}
}
return nil
}
open func indexPathForData(_ dataToFind: SGRowData) -> IndexPath? {
var s = 0
var r = 0
for section in self.tableData.sections {
for data in section.rows {
if data == dataToFind {
return IndexPath(row: r, section: s)
}
r += 1
}
r = 0
s += 1
}
return nil
}
open func enabledStateForModelPath(_ modelPath: String?) -> Bool {
return true
}
open func cellIdentifierForIndexPath(_ indexPath: IndexPath) -> String {
let id = self.dataForIndexPath(indexPath)!.cellIdentifier
if indexPath == self.revealedCellIndexPath {
switch id {
case PICKER_LABEL_CELL_ID:
return PICKER_CELL_ID
case DATE_LABEL_CELL_ID:
return DATE_PICKER_CELL_ID
case TIME_LABEL_CELL_ID:
return TIME_PICKER_CELL_ID
default:
break
}
}
return id
}
// MARK: Configuration
open func configureCell(_ cell: UITableViewCell) {
if let path = self.tableView.indexPath(for: cell) {
self.configureCell(cell, atIndexPath: path)
}
}
open func configureCellAtIndexPath(_ path: IndexPath) {
if let cell = self.tableView.cellForRow(at: path as IndexPath) {
self.configureCell(cell, atIndexPath: path)
}
}
open func configureCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) {
let data = self.dataForIndexPath(indexPath)!
switch (cell.reuseIdentifier ?? "") {
case BASIC_CELL_ID:
var text = ""
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value: Any = target.value(forKeyPath: path) {
text = "\(value)"
}
}
}
if text == "" {
text = data.title
}
cell.textLabel?.text = text
if data.segueName != nil {
cell.accessoryType = .disclosureIndicator
}
else if data.checked == true {
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
case OTHER_CELL_ID:
cell.textLabel?.text = data.title
//cell.selectionStyle = .None
if data.segueName != nil {
cell.accessoryType = .disclosureIndicator
}
else if data.checked == true {
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
case PICKER_LABEL_CELL_ID:
cell.textLabel?.text = data.title
var text = "Untitled"
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let name = target.value(forKeyPath: path) as? String {
text = name
}
}
}
cell.detailTextLabel?.text = text
case DATE_LABEL_CELL_ID:
cell.textLabel?.text = data.title
var date = NSDate()
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? NSDate {
date = value
}
}
}
cell.detailTextLabel?.text = SGFormatter.dateStringFromDate(date as Date)
case TIME_LABEL_CELL_ID:
cell.textLabel?.text = data.title
var length = 0.0
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? TimeInterval {
length = value
}
}
}
let timeString = SGFormatter.stringFromLength(length)
cell.detailTextLabel?.text = timeString
case LABEL_CELL_ID:
var text = ""
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value: Any = target.value(forKeyPath: path) {
text = "\(value)"
}
}
}
let textLabel = cell.viewWithTag(1) as? UILabel
let detailTextLabel = cell.viewWithTag(2) as? UILabel
textLabel?.text = data.title
detailTextLabel?.text = text
if data.segueName != nil {
cell.accessoryType = .disclosureIndicator
}
else if data.checked == true {
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
case COLOR_CELL_ID:
let colorView = cell.viewWithTag(2) as! SGColorView
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? UIColor {
colorView.color = value
}
}
}
let label = cell.viewWithTag(1) as! UILabel
label.text = data.title
cell.accessoryType = .disclosureIndicator
case TEXT_FIELD_CELL_ID:
let label = cell.viewWithTag(1) as! UILabel
label.text = data.title
var text = "Untitled"
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? String {
text = value
}
}
}
let textField = cell.viewWithTag(2) as! UITextField
textField.text = text
textField.delegate = self
case TEXT_VIEW_CELL_ID:
var text = ""
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? String {
text = value
}
}
}
let textView = cell.viewWithTag(2) as! UITextView
textView.text = text
textView.delegate = self
case SWITCH_CELL_ID:
let label = cell.viewWithTag(1) as! UILabel
label.text = data.title
var on = false
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? Bool {
on = value
}
}
}
let toggle = cell.viewWithTag(2) as! UISwitch
toggle.isOn = on
toggle.addTarget(self, action: #selector(switchDidChange(_:)), for: .valueChanged)
case SLIDER_CELL_ID:
let label = cell.viewWithTag(1) as! UILabel
label.text = data.title
var number: Float = 0.0
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? Float {
number = value
}
}
}
let slider = cell.viewWithTag(2) as! UISlider
slider.minimumValue = Float(data.range.location)
slider.maximumValue = Float(data.range.location + data.range.length)
slider.value = number
slider.addTarget(self, action: #selector(sliderDidChange(_:)), for: .valueChanged)
case PICKER_CELL_ID:
let picker = cell.viewWithTag(2) as! UIPickerView
picker.delegate = self
self.configurePickerView(picker, forModelPath: data.modelPath)
case DATE_PICKER_CELL_ID:
var date = NSDate()
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? NSDate {
date = value
}
}
}
let picker = cell.viewWithTag(2) as! UIDatePicker
picker.setDate(date as Date, animated: false)
picker.addTarget(self, action: #selector(datePickerDidChange(_:)), for: .valueChanged)
case TIME_PICKER_CELL_ID:
var length = 0.0
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? TimeInterval {
length = value
}
}
}
let picker = cell.viewWithTag(2) as! UIDatePicker
picker.countDownDuration = length
picker.addTarget(self, action: #selector(datePickerDidChange(_:)), for: .valueChanged)
case SEGMENTED_CELL_ID:
let control = cell.viewWithTag(2) as! UISegmentedControl
var index = 0
if let path = data.modelPath {
if let target = self.targetForData(data) {
if let value = target.value(forKeyPath: path) as? Int {
index = Int(value)
}
}
}
self.configureSegmentedControl(control, forModelPath: data.modelPath)
control.selectedSegmentIndex = index
control.addTarget(self, action: #selector(segmentedControlDidChange), for: .valueChanged)
default:
break
}
let enabled = self.enabledStateForModelPath(data.modelPath)
self.enable(cell, enabled)
}
open func enable(_ cell: UITableViewCell, _ enabled: Bool) {
cell.isUserInteractionEnabled = enabled
cell.textLabel?.isEnabled = enabled
cell.detailTextLabel?.isEnabled = enabled
}
open func refresh(section: Int) {
for i in 0 ..< self.tableView.numberOfRows(inSection: section) {
let path = IndexPath(row: i, section: 0)
if let cell = self.tableView.cellForRow(at: path) {
self.configureCell(cell)
}
}
}
// MARK: Hide/Show
open func dynamicIndexPath(for indexPath: IndexPath) -> IndexPath {
if let path = self.revealedCellIndexPath {
if (path.section == indexPath.section && path.row <= indexPath.row) {
return indexPath.previous()
}
}
return indexPath
}
open func targetedCell() -> IndexPath? {
if let path = self.revealedCellIndexPath {
return path.previous()
} else {
return self.tableView.indexPathForSelectedRow
}
}
open func hasRevealedCell() -> Bool {
return self.revealedCellIndexPath != nil
}
open func canExpandCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) -> Bool {
let hasRevealableCellBelow = (cell.reuseIdentifier == TIME_LABEL_CELL_ID) // CJC: revisit
let canModify = true // CJC: revisit
return hasRevealableCellBelow && canModify
}
open func hasRevealedCellFor(_ indexPath: IndexPath) -> Bool {
if let thisCell = self.tableView.cellForRow(at: indexPath as IndexPath) {
if let nextCell = self.tableView.cellForRow(at: indexPath.next() as IndexPath) {
let thisID = thisCell.reuseIdentifier
let nextID = nextCell.reuseIdentifier
if thisID == TIME_LABEL_CELL_ID {
return nextID == TIME_PICKER_CELL_ID
}
if thisID == DATE_LABEL_CELL_ID {
return nextID == DATE_PICKER_CELL_ID
}
if thisID == PICKER_LABEL_CELL_ID {
return nextID == PICKER_CELL_ID
}
}
}
return false
}
open func updateRevealedControl() {
if let path = self.revealedCellIndexPath {
if let cell = self.tableView.cellForRow(at: path as IndexPath) {
self.configureCell(cell, atIndexPath: path)
}
}
}
open func toggleRevealedCellFor(_ indexPath: IndexPath) {
self.tableView.beginUpdates()
let indexPaths = [indexPath.next()]
if self.hasRevealedCellFor(indexPath) {
self.tableView.deleteRows(at: indexPaths as [IndexPath], with: .fade)
} else {
self.tableView.insertRows(at: indexPaths as [IndexPath], with: .fade)
}
self.tableView.endUpdates()
}
open func displayRevealedCellForRowAtIndexPath(_ indexPath: IndexPath) {
self.tableView.beginUpdates()
var before = false
var sameCellClicked = false
if let path = self.revealedCellIndexPath {
before = path.row < indexPath.row
sameCellClicked = (path.previous() == indexPath)
self.tableView.deleteRows(at: [path as IndexPath], with: .fade)
self.revealedCellIndexPath = nil
}
if !sameCellClicked {
let path = (before) ? indexPath.previous() : indexPath
self.toggleRevealedCellFor(path)
self.revealedCellIndexPath = path.next()
}
self.tableView.deselectRow(at: indexPath as IndexPath, animated: true)
self.tableView.endUpdates()
self.updateRevealedControl()
}
}
| mit | c6de48b6155785c1cf1a0f3c315901cd | 30.622201 | 135 | 0.498399 | 5.418989 | false | false | false | false |
rgravina/tddtris | TddTetris/Components/Game/MoveTetrominoRightOneColumnAction.swift | 1 | 1178 | class MoveTetrominoRightOneColumnAction: Action {
let view: GameView
let state: GameState
let collisionDetector: CollisionDetector
init(
view: GameView,
state: GameState,
collisionDetector: CollisionDetector
) {
self.view = view
self.state = state
self.collisionDetector = collisionDetector
}
func perform() {
if (state.tetromino == nil) {
return
}
let tetromino = state.tetromino!
if (collisionDetector.wouldCollide(.right)) {
return
}
let movedTetromino = tetromino.move(.right)
state.tetromino = movedTetromino
for position in tetromino.blocks {
state.free(
position: Position(
column: position.column,
row: position.row
)
)
}
for position in movedTetromino.blocks {
state.occupy(
position: Position(
column: position.column,
row: position.row
)
)
}
view.move(movedTetromino)
}
}
| mit | b2ac59c306b0b2f4774c6016ae00e689 | 25.177778 | 53 | 0.518676 | 5.40367 | false | false | false | false |
BlackSourceLabs/BlackNectar-iOS | BlackNectar/BlackNectar/WelcomeScreens/WelcomeScreenFour.swift | 1 | 11003 | //
// WelcomeScreenFour.swift
// BlackNectar
//
// Created by Wellington Moreno on 3/3/17.
// Copyright © 2017 BlackSource. All rights reserved.
//
import Archeota
import AromaSwiftClient
import CoreLocation
import Foundation
import UIKit
class WelcomeScreenFour: UIViewController {
@IBOutlet weak var myLocationButton: CustomButtonView!
@IBOutlet weak var zipCodeButton: CustomButtonView!
@IBOutlet weak var nextButton: CustomButtonView!
fileprivate var originalZipCodeText: NSAttributedString!
@IBOutlet weak var locationPin: UIImageView!
@IBOutlet weak var locationPinCenterXMyLocation: NSLayoutConstraint!
@IBOutlet weak var locationPinCenterYMyLocation: NSLayoutConstraint!
@IBOutlet weak var locationPinCenterYZipCode: NSLayoutConstraint!
@IBOutlet weak var locationPinCenterXZipCode: NSLayoutConstraint!
fileprivate var eitherOneSelected: Bool {
return UserPreferences.instance.useMyLocation ||
UserPreferences.instance.useZipCode
}
fileprivate var neitherSelected: Bool {
return !eitherOneSelected
}
var delegate: WelcomeScreenDelegate?
override func viewDidLoad() {
super.viewDidLoad()
makeNoteThatScreenLaunched()
}
override func viewDidAppear(_ animated: Bool) {
if let title = self.zipCodeButton.attributedTitle(for: .normal) {
self.originalZipCodeText = title
}
updateButtons(animated: false)
}
fileprivate func dismiss() {
self.delegate?.didDismissWelcomeScreens()
self.dismiss(animated: true, completion: nil)
}
}
//MARK: IB Actions
extension WelcomeScreenFour {
@IBAction func didSelectMyLocation(_ sender: Any) {
let alert = createAlertToRequestGPS()
presentAlert(alert)
makeNoteThatUserTappedGPS()
}
@IBAction func didSelectZipCode(_ sender: Any) {
let alert = createAlertToRequestZipCode()
presentAlert(alert)
makeNoteThatUserTappedZipCode()
}
@IBAction func didSelectNext(_ sender: Any) {
self.dismiss()
}
}
//MARK: Location Code
extension WelcomeScreenFour {
var useGPS: Bool {
get {
return UserPreferences.instance.useMyLocation
}
set (newValue) {
UserPreferences.instance.useMyLocation = newValue
UserPreferences.instance.useZipCode = !newValue
if newValue == true {
makeNoteThatUserSelectedGPS()
}
}
}
var gpsAuthorized: Bool {
if let status = UserLocation.instance.currentStatus, status == .authorizedWhenInUse || status == .authorizedAlways {
return true
}
else {
return false
}
}
var useZipCode: Bool {
get {
return UserPreferences.instance.useZipCode
}
set (newValue) {
UserPreferences.instance.useZipCode = newValue
UserPreferences.instance.useMyLocation = !newValue
if newValue == true {
makeNoteThatUserSelectedZipCode()
}
}
}
var zipCode: String {
get {
return UserPreferences.instance.zipCode ?? ""
}
set (newValue) {
UserPreferences.instance.zipCode = newValue
}
}
func requestGPS() {
if let status = UserLocation.instance.currentStatus, status == .denied {
let alert = self.createAlertToSendUserToLocationSettings()
self.present(alert, animated: true, completion: nil)
return
}
UserLocation.instance.requestLocation() { location in
LOG.info("GPS successfully enabled")
self.useGPS = true
self.updateButtons()
}
}
func isValidZipCode(_ zipCode: String) -> (isValid: Bool, errorMessage: String) {
if zipCode.isEmpty {
return (false, "Zip Code is Empty")
}
if zipCode.characters.count != 5 {
return (false, "Zip Code must be 5 digits")
}
guard let _ = Int(zipCode) else {
return (false, "Zip Code must be numerical")
}
return (true, "")
}
}
//MARK: UI Setup
extension WelcomeScreenFour {
func updateButtons(animated: Bool = true) {
if useGPS && gpsAuthorized {
showPin(animated: animated)
selectGPSButton(animated: animated)
enableNextButton()
}
else if useZipCode {
showPin(animated: animated)
selectZipCodeButton(animated: animated)
enableNextButton()
}
else {
hidePin(animated: animated)
disableNextButton()
}
}
func selectZipCodeButton(animated: Bool = true) {
uncloakZipCode()
updateZipCodeText()
movePinToZipCode(animated: animated)
enableMyLocationButton()
cloakMyLocationButton()
}
func selectGPSButton(animated: Bool = true) {
uncloakMyLocationButton()
disableMyLocationButton()
movePinToMyLocation(animated: animated)
enableZipCodeButton()
updateZipCodeText()
cloakZipCode()
}
func enableZipCodeButton() {
zipCodeButton.isEnabled = true
}
func disableZipCodeButton() {
zipCodeButton.isEnabled = false
}
func updateZipCodeText() {
if useZipCode {
let text = NSMutableAttributedString(string: zipCode, attributes: originalZipCodeText.attributes(at: 0, effectiveRange: nil))
if let font = Fonts.uniSansSemiBold(size: 24) {
text.addAttribute(NSFontAttributeName, value: font, range: NSRange.init(location: 0, length: text.string.characters.count))
zipCodeButton.setAttributedTitle(text, for: .normal)
}
}
else {
zipCodeButton.setAttributedTitle(originalZipCodeText, for: .normal)
}
}
func cloakZipCode() {
zipCodeButton.alpha = 0.6
}
func uncloakZipCode() {
zipCodeButton.alpha = 1.0
}
func enableMyLocationButton() {
self.myLocationButton.isEnabled = true
}
func disableMyLocationButton() {
self.myLocationButton.isEnabled = false
}
func cloakMyLocationButton() {
self.myLocationButton.alpha = 0.6
}
func uncloakMyLocationButton() {
self.myLocationButton.alpha = 1.0
}
func enableNextButton() {
let animations = {
self.nextButton.isEnabled = true
self.nextButton.alpha = 1.0
}
animate(withView: self.nextButton, animations: animations)
}
func disableNextButton() {
let animations = {
self.nextButton.isEnabled = false
self.nextButton.alpha = 0.6
}
animate(withView: self.nextButton, animations: animations)
}
func movePinToZipCode(animated: Bool = true) {
let animations = {
self.locationPinCenterXMyLocation.isActive = false
self.locationPinCenterYMyLocation.isActive = false
self.locationPinCenterXZipCode.isActive = true
self.locationPinCenterYZipCode.isActive = true
self.view.layoutIfNeeded()
}
if animated {
animate(withView: self.locationPin, animations: animations)
}
else {
animations()
}
}
func movePinToMyLocation(animated: Bool = true) {
let animations = {
self.locationPinCenterXZipCode.isActive = false
self.locationPinCenterYZipCode.isActive = false
self.locationPinCenterXMyLocation.isActive = true
self.locationPinCenterYMyLocation.isActive = true
self.view.layoutIfNeeded()
}
if animated {
animate(withView: self.locationPin, animations: animations)
}
else {
animations()
}
}
func hidePin(animated: Bool = false) {
let animations = {
self.locationPin.isHidden = true
}
if animated {
animate(withView: self.locationPin, animations: animations)
}
else {
animations()
}
}
func showPin(animated: Bool = false) {
let animations = {
self.locationPin.isHidden = false
}
if animated {
animate(withView: self.locationPin, animations: animations)
}
else {
animations()
}
}
func animate(withView view: UIView, animations: @escaping () -> ()) {
UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseInOut, animations: animations, completion: nil)
}
}
//MARK: Aroma Messages
fileprivate extension WelcomeScreenFour {
var aromaTitle: String { return "Welcome Screen 4" }
func makeNoteThatScreenLaunched() {
let message = "This is where the user selects the location type"
AromaClient.sendLowPriorityMessage(withTitle: aromaTitle, withBody: message)
}
func makeNoteThatUserTappedGPS() {
let message = "User tapped on 'My Location'"
AromaClient.sendLowPriorityMessage(withTitle: aromaTitle, withBody: message)
}
func makeNoteThatUserSelectedGPS() {
let message = "User selected 'My Location'"
AromaClient.sendLowPriorityMessage(withTitle: aromaTitle, withBody: message)
}
func makeNoteThatUserTappedZipCode() {
let message = "User tapped on 'Zip Code' option"
AromaClient.sendLowPriorityMessage(withTitle: aromaTitle, withBody: message)
}
func makeNoteThatUserSelectedZipCode() {
let message = "User selected Zip Code: \(zipCode)"
AromaClient.sendLowPriorityMessage(withTitle: aromaTitle, withBody: message)
}
}
| apache-2.0 | 24b3803d04668e725a237bfa4c4e9dd1 | 24.061503 | 139 | 0.55808 | 5.454636 | false | false | false | false |
zcfsmile/Swifter | BasicSyntax/015属性/015Properties.playground/Contents.swift | 1 | 4928 | //: Playground - noun: a place where people can play
import UIKit
//: 属性
//: 存储属性
//: 存储在特定类或结构体实例的一个常量或变量。
struct Range {
var width: Double
var height: Double
}
var rectRange = Range.init(width: 100, height: 100)
rectRange.width = 200
class Person {
var name: String?
var age: Int?
}
let xiaoMing = Person()
xiaoMing.name = "Xiao Ming"
//: 延迟存储属性
//: 第一次调用的时候才会计算初始值的属性。属性声明前使用 Lazy
//: 延迟属性只能是变量属性。因为延迟属性的值可能在实例构造完成之后才能获取。但是常量属性在构造完成之前必须有初始值。
//: 如果一个被标记为 lazy 的属性在没有初始化时就同时被多个线程访问,则无法保证该属性只会被初始化一次。
//: 计算属性
//: 类、结构体、枚举可以定义计算属性。计算属性不直接存储值,而是提供一个 getter 和一个可选的 setter,来间接获取和设置其他属性或变量的值。
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
print("\(square.origin.x), \(square.origin.y)")
//: 只读计算属性
//: 只有 getter 没有 setter 的计算属性就是只读计算属性。只读计算属性总是返回一个值,可以通过点运算符访问,但不能设置新的值。
//: 属性观察器
//: 属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,即使新值和当前值相同的时候也不例外
//: 可以为除了延迟存储属性之外的其他存储属性添加属性观察器,也可以通过重写属性的方式为继承的属性(包括存储属性和计算属性)添加属性观察器。你不必为非重写的计算属性添加属性观察器,因为可以通过它的 setter 直接监控和响应值的变化。
//: willSet 在新的值被设置之前调用
//: didSet 在新的值被设置之后立即调用
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("newTotalSteps: \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200
stepCounter.totalSteps = 360
stepCounter.totalSteps = 896
//: > 如果将属性通过 in-out 方式传入函数,willSet 和 didSet 也会调用。这是因为 in-out 参数采用了拷入拷出模式:即在函数内部使用的是参数的 copy,函数结束后,又对参数重新赋值。
//: 全局变量、局部变量
//: 全局变量是在函数、方法、闭包或任何类型之外定义的变量。局部变量是在函数、方法或闭包内部定义的变量。
//: 全局的常量或变量都是延迟计算的,跟延迟存储属性相似,不同的地方在于,全局的常量或变量不需要标记lazy修饰符。
//: 局部范围的常量或变量从不延迟计算。
//: 类型属性
//: 实例属性属于一个特定类型的实例。
//: 类型属性用于定义某个类型所有实例共享的数据,比如所有实例都能用的一个常量(就像 C 语言中的静态常量),或者所有实例都能访问的一个变量(就像 C 语言中的静态变量)。
//: 使用关键字 static 来定义类型属性。在为类定义计算型类型属性时,可以改用关键字 class 来支持子类对父类的实现进行重写。
struct SomeStructure {
static var storedTypeProperty = "Some value"
static var computedTypeProperty: Int {
return 1
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value"
static var computedTypeProperty: Int {
return 6
}
}
class SomeClass {
static var storedTypeproperty = "Some value"
static var computedTypeProperty: Int {
return 27
}
class var overrideableComputedTypeProperty: Int {
return 107
}
}
//: 获取和设置计算属性的值
print(SomeStructure.storedTypeProperty)
SomeStructure.storedTypeProperty = "Another value"
print(SomeStructure.storedTypeProperty)
print(SomeEnumeration.computedTypeProperty)
print(SomeClass.overrideableComputedTypeProperty)
| mit | 5254882492e37b426c33d11597e9f295 | 22.970803 | 119 | 0.683009 | 2.880702 | false | false | false | false |
FlameTinary/weiboSwift | weiboSwift/weiboSwift/AppDelegate.swift | 1 | 2585 | //
// AppDelegate.swift
// weiboSwift
//
// Created by 田宇 on 16/4/25.
// Copyright © 2016年 Tinary. All rights reserved.
//
import UIKit
import QorumLogs
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = MainViewController()
window?.makeKeyAndVisible()
QorumLogs.enabled = true
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 84e7f67c8367582a88128ef3e5388bf0 | 41.966667 | 285 | 0.730411 | 5.690949 | false | false | false | false |
qvik/qvik-swift-ios | QvikSwift/UIImageExtensions.swift | 1 | 9064 | // The MIT License (MIT)
//
// Copyright (c) 2015 Qvik (www.qvik.fi)
//
// 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 Accelerate
import Foundation
import ImageIO
import UIKit
/// Extensions to the UIImage class
public extension UIImage {
/// Provides a shorthand for image width.
var width: CGFloat {
return self.size.width
}
/// Provides a shorthand for image height.
var height: CGFloat {
return self.size.height
}
/**
Returns an image with orientation 'removed', ie. rendered again so that
imageOrientation is always 'Up'. If this was the case already, the original image is returned.
- returns: a copy of this image with orientation setting set to 'up'.
*/
func imageWithNormalizedOrientation() -> UIImage {
if imageOrientation == .up {
return self
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
draw(in: rect)
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return normalizedImage!
}
/**
Returns an scaled-down (to the max size) image of the original image, or the
original image if max size was not exceeded. Aspect ratio is preserved.
- parameter maxSize: maximum size for the new image
- parameter imageScale: value for UIImage.scale. Specify 0.0 to match the scale of the device's screen.
- returns: scaled-down image
*/
func scaleDown(maxSize: CGSize, imageScale: CGFloat = 1.0) -> UIImage {
let myWidth = self.size.width
let myHeight = self.size.height
if maxSize.height >= myHeight && maxSize.width >= myWidth {
return self
}
let fittingSize = self.size.aspectSizeToFit(maxDimensions: maxSize)
return scaleTo(size: fittingSize, imageScale: imageScale)
}
/**
Returns a scaled version of this image that 'aspect-fits' inside a given size. Aspect ratio is retained.
- parameter sizeToFit: max dimensions for the scaled image.
- parameter imageScale: value for UIImage.scale. Specify 0.0 to match the scale of the device's screen.
- returns: scaled image
*/
func scaleToFit(sizeToFit: CGSize, imageScale: CGFloat = 1.0) -> UIImage {
let fittingSize = self.size.aspectSizeToFit(maxDimensions: sizeToFit)
return scaleTo(size: fittingSize, imageScale: imageScale)
}
/**
Returns a scaled version of this image. The image is stretched to the given size, thus possibly
changing the aspect ratio.
- parameter scaledSize: size for the scaled image. Specify ```imageScale: 1.0``` to make this exact pixel size.
- parameter imageScale: value for UIImage.scale. Specify 0.0 to match the scale of the device's screen.
- returns: scaled-down image
*/
func scaleTo(size: CGSize, imageScale: CGFloat = 1.0) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, imageScale)
self.draw(in: CGRect(origin: CGPoint.zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
/**
Crops the image to a square; from the middle of the original image, using the largest
possible square area that fits in the original image.
- returns: the cropped image. Note that the dimensions may be off by +-1 pixels.
*/
func cropImageToSquare() -> UIImage {
let contextImage: UIImage = UIImage(cgImage: self.cgImage!)
let contextSize: CGSize = contextImage.size
let posX: CGFloat
let posY: CGFloat
let width: CGFloat
let height: CGFloat
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
width = contextSize.height
height = contextSize.height
} else {
posX = 0
posY = ((contextSize.height - contextSize.width) / 2)
width = contextSize.width
height = contextSize.width
}
let rect = CGRect(x: posX, y: posY, width: width, height: height)
let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
let image: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)
return image
}
/// Blur algorithms
enum BlurAlgorithm {
case boxConvolve
case tentConvolve
}
/**
Returns a blurred version of the image.
- parameter radius: radius of the blur kernel, in pixels.
- parameter algorithm: blur algorithm to use. .TentConvolve is faster than .BoxConvolve.
- returns: the blurred image.
*/
func blur(radius: Double, algorithm: BlurAlgorithm = .tentConvolve) -> UIImage {
let imageRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = vImagePixelCount(context.width)
let height = vImagePixelCount(context.height)
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let effectInContext = UIGraphicsGetCurrentContext()
effectInContext?.scaleBy(x: 1.0, y: -1.0)
effectInContext?.translateBy(x: 0, y: -self.size.height)
effectInContext?.draw(self.cgImage!, in: imageRect) // this takes time
var effectInBuffer = createEffectBuffer(effectInContext!)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = createEffectBuffer(effectOutContext!)
let inputRadius = CGFloat(radius) * UIScreen.main.scale
let f = inputRadius * 3.0 * CGFloat(sqrt(2 * Double.pi))
var radius = UInt32(floor((f / 4) + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
if algorithm == .boxConvolve {
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
} else {
vImageTentConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
let effectImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsEndImageContext()
return effectImage!
}
/**
Creates an animated image from GIF data.
- parameter gifData: The GIF image data
- parameter frameDuration: The duration for each frame, in seconds. Default is 0.1.
*/
class func animatedImage(gifData: Data, frameDuration: TimeInterval = 0.1) -> UIImage? {
guard let source = CGImageSourceCreateWithData(gifData as CFData, nil) else {
return nil
}
let numFrames = CGImageSourceGetCount(source)
var frames = [UIImage]()
for i in 0..<numFrames {
// Extract the image frame
guard let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) else {
continue
}
frames.append(UIImage(cgImage: cgImage))
}
return UIImage.animatedImage(with: frames, duration: frameDuration * Double(numFrames))
}
}
| mit | 1ca43798e4db206529dae3a1492e5838 | 38.408696 | 128 | 0.666593 | 4.860054 | false | false | false | false |
juanm95/Soundwich | Quaggify/LibraryViewController.swift | 1 | 21871 | //
// LibraryViewController.swift
// Quaggify
//
// Created by Jonathan Bijos on 31/01/17.
// Copyright © 2017 Quaggie. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
import Flurry_iOS_SDK
class LibraryViewController: ViewController, SPTAudioStreamingDelegate, SPTAudioStreamingPlaybackDelegate {
private func react(reactionEmoji: String, trackResponse: Track, frommember: String, time: String, elaboration: String) {
API.reactToSong(reaction: "\(reactionEmoji) \(elaboration)", time: time, username: UserDefaults.standard.value(forKey: "username") as! String, to: frommember)
thePlayer.needToReact = false
thePlayer.injected = false
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.previousTrackCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.isEnabled = true
if #available(iOS 9.1, *) {
commandCenter.changePlaybackPositionCommand.isEnabled = true
} else {
// Fallback on earlier versions
}
let playlistId = UserDefaults.standard.value(forKey: "playlistId")
let ownerid = User.current.id
let owner = User(JSON: ["id": ownerid])
var soundwichPlaylist = Playlist(JSON: ["id": UserDefaults.standard.value(forKey: "playlistId")])
soundwichPlaylist?.owner = owner
API.addTrackToPlaylist(track: trackResponse, playlist: soundwichPlaylist) {(string: String?, error: Error?) in
print (string)
}
var plainTextReaction = ""
switch reactionEmoji {
case "😂":
plainTextReaction = "laughing"
break
case "😎":
plainTextReaction = "dope"
break
case "💩":
plainTextReaction = "poop"
break
case "😡":
plainTextReaction = "angry"
break
default:
break
}
let reactionParameters = ["reaction": plainTextReaction, "message": elaboration] as [String: Any]
Flurry.logEvent("Plaintext reactions", withParameters: reactionParameters)
}
func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didStopPlayingTrack trackUri: String!) {
var trackName = "spotify:track:"
if (thePlayer.needToReact) {
thePlayer.nowPlaying?.playSong()
return
}
API.checkQueue() { [weak self] (response) in
guard let strongSelf = self else {
return
}
print(response)
let randomNumber = arc4random_uniform(100)
let response = response as [String:Any]
let chanceOfQueue = 40 as UInt32
if response["queued"] as! Bool && randomNumber < chanceOfQueue {
thePlayer.needToReact = true
thePlayer.injected = true
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = false
commandCenter.previousTrackCommand.isEnabled = false
commandCenter.pauseCommand.isEnabled = false
commandCenter.playCommand.isEnabled = false
if #available(iOS 9.1, *) {
commandCenter.changePlaybackPositionCommand.isEnabled = false
} else {
// Fallback on earlier versions
}
let data = response["data"] as! [String:Any]
let songid = data["songid"] as! String
let time = data["time"] as! String
let tomember = data["tomember"] as! String
let frommember = data["frommember"] as! String
trackName += songid
thePlayer.nowPlaying?.track?.id = songid
API.fetchTrack(track: thePlayer.nowPlaying?.track) { [weak self] (trackResponse, error) in
guard let strongSelf = self else {
return
}
if let error = error {
print(error)
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let trackResponse = trackResponse {
let alertController = UIAlertController(title: "Soundwich", message: "React to this song \(frommember) sent.", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "💩", style: UIAlertActionStyle.default, handler: {[weak self] (alert: UIAlertAction!) in
let elaboration = alertController.textFields![0].text!
self?.react(reactionEmoji: "💩", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration)
}))
alertController.addAction(UIAlertAction(title: "😂", style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in
let elaboration = alertController.textFields![0].text!
self?.react(reactionEmoji: "😂", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration)
}))
alertController.addAction(UIAlertAction(title: "😡", style: UIAlertActionStyle.default, handler: {[weak self] (alert: UIAlertAction!) in
let elaboration = alertController.textFields![0].text!
self?.react(reactionEmoji: "😡", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration)
}))
alertController.addAction(UIAlertAction(title: "😎", style: UIAlertActionStyle.default, handler: {[weak self] (alert: UIAlertAction!) in
let elaboration = alertController.textFields![0].text!
self?.react(reactionEmoji: "😎", trackResponse: trackResponse, frommember: frommember, time: time, elaboration: elaboration)
}))
alertController.addTextField { textfield in
textfield.placeholder = "Attach message to reaction"
}
thePlayer.nowPlaying?.track = trackResponse
DispatchQueue.main.async {
UIApplication.topViewController()?.present(alertController, animated: true)
}
}
}
} else {
thePlayer.indeX += 1
if thePlayer.indeX >= (thePlayer.trackList?.total)! {
thePlayer.indeX = 0
}
if(thePlayer.indeX < 0 ) { thePlayer.indeX = 0}
thePlayer.nowPlaying?.track = thePlayer.trackList?.items?[thePlayer.indeX].track
}
}
}
func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didChangePosition position: TimeInterval){
thePlayer.nowPlaying?.playbackSlider.setValue(Float(position), animated: false)
}
var auth = SPTAuth.defaultInstance()!
var session:SPTSession!
var ACCESS_TOKEN: String? {
return UserDefaults.standard.string(forKey: "ACCESS_TOKEN_KEY")
}
func initializePlayer() {
UIApplication.shared.beginReceivingRemoteControlEvents()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
self.becomeFirstResponder()
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
let CLIENT_ID = "9f0cac5d230c4877a2a769febe804681"
if thePlayer.spotifyPlayer == nil {
thePlayer.spotifyPlayer = SPTAudioStreamingController.sharedInstance()
thePlayer.spotifyPlayer!.playbackDelegate = self
thePlayer.spotifyPlayer!.delegate = self
try! thePlayer.spotifyPlayer!.start(withClientId: CLIENT_ID)
thePlayer.spotifyPlayer!.login(withAccessToken: ACCESS_TOKEN)
}
}
var spotifyObject: SpotifyObject<Playlist>?
var playlists: [Playlist] = [] {
didSet {
collectionView.reloadData()
}
}
lazy var logoutButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logout))
button.tintColor = ColorPalette.white
return button
}()
lazy var searchButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: UIImage(named: "tab_icon_search"), style: .plain, target: self, action: #selector(search))
button.tintColor = ColorPalette.white
return button
}()
var limit = 20
var offset = 0
var isFetching = false
let lineSpacing: CGFloat = 16
let interItemSpacing: CGFloat = 8
let contentInset: CGFloat = 8
lazy var refreshControl: UIRefreshControl = {
let rc = UIRefreshControl()
rc.addTarget(self, action: #selector(refreshPlaylists), for: .valueChanged)
return rc
}()
lazy var collectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.minimumLineSpacing = self.lineSpacing
flowLayout.minimumInteritemSpacing = self.interItemSpacing
let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
cv.addSubview(self.refreshControl)
cv.keyboardDismissMode = .onDrag
cv.alwaysBounceVertical = true
cv.showsVerticalScrollIndicator = false
cv.contentInset = UIEdgeInsets(top: self.contentInset, left: self.contentInset, bottom: self.contentInset, right: self.contentInset)
cv.backgroundColor = .clear
cv.delegate = self
cv.dataSource = self
cv.register(PlaylistCell.self, forCellWithReuseIdentifier: PlaylistCell.identifier)
cv.register(LoadingFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: LoadingFooterView.identifier)
return cv
}()
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
addListeners()
fetchPlaylists()
//addCreateNewPlaylistCell()
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: Layout
override func setupViews() {
super.setupViews()
initializePlayer()
navigationItem.title = "Your Playlists".uppercased()
navigationItem.rightBarButtonItem = logoutButton
navigationItem.leftBarButtonItem = searchButton
view.addSubview(collectionView)
collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
}
// MARK: Actions
extension LibraryViewController {
func addCreateNewPlaylistCell () {
/*if let createNewPlaylistItem = Playlist(JSON: ["name": "Create new playlist"]) {
playlists.append(createNewPlaylistItem)
}*/
}
func logout () {
SpotifyService.shared.logout()
thePlayer.nowPlaying?.pauseSong()
}
func search() {
let searchViewController = SearchViewController()
searchViewController.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
navigationController?.pushViewController(searchViewController, animated: true)
}
func addListeners () {
NotificationCenter.default.addObserver(self, selector: #selector(onUserPlaylistUpdate), name: .onUserPlaylistUpdate, object: nil)
}
func onUserPlaylistUpdate (notification: Notification) {
guard let playlist = notification.object as? Playlist else {
return
}
if playlists[safe: 1] != nil {
playlists.insert(playlist, at: 1)
collectionView.reloadData()
}
}
func fetchPlaylists () {
isFetching = true
API.fetchSoundwichPlaylist() { (soundwichPlaylist: Playlist?, error: Error?) in
self.playlists.append(soundwichPlaylist!)
API.fetchCurrentUsersPlaylists(limit: self.limit, offset: self.offset) { [weak self] (spotifyObject, error) in
guard let strongSelf = self else {
return
}
strongSelf.isFetching = false
strongSelf.refreshControl.endRefreshing()
strongSelf.offset += strongSelf.limit
if let error = error {
print(error)
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let items = spotifyObject?.items {
strongSelf.playlists.append(contentsOf: items)
strongSelf.spotifyObject = spotifyObject
}
}
}
}
func refreshPlaylists () {
if isFetching {
return
}
isFetching = true
print("Refreshing ")
API.fetchSoundwichPlaylist() { (soundwichPlaylist: Playlist?, error: Error?) in
//self.playlists.append(soundwichPlaylist!)
API.fetchCurrentUsersPlaylists(limit: self.limit, offset: self.offset) { [weak self] (spotifyObject, error) in
guard let strongSelf = self else {
return
}
strongSelf.isFetching = false
strongSelf.refreshControl.endRefreshing()
strongSelf.offset += strongSelf.limit
if let error = error {
print(error)
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let items = spotifyObject?.items {
strongSelf.playlists.append(contentsOf: items)
strongSelf.spotifyObject = spotifyObject
}
}
}
/* API.fetchCurrentUsersPlaylists(limit: limit, offset: 0) { [weak self] (spotifyObject, error) in
guard let strongSelf = self else {
return
}
strongSelf.isFetching = false
strongSelf.refreshControl.endRefreshing()
strongSelf.offset = strongSelf.limit
if let error = error {
print(error)
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let items = spotifyObject?.items {
strongSelf.playlists.removeAll()
strongSelf.addCreateNewPlaylistCell()
strongSelf.playlists.append(contentsOf: items)
strongSelf.spotifyObject = spotifyObject
}
}*/
}
func showNewPlaylistModal () {
/*let alertController = UIAlertController(title: "Create new Playlist".uppercased(), message: nil, preferredStyle: .alert)
alertController.addTextField { textfield in
textfield.placeholder = "Playlist name"
textfield.addTarget(self, action: #selector(self.textDidChange(textField:)), for: .editingChanged)
}
let cancelAction = UIAlertAction(title: "Cancel".uppercased(), style: .destructive, handler: nil)
let createAction = UIAlertAction(title: "Create".uppercased(), style: .default) { _ in
if let textfield = alertController.textFields?.first, let playlistName = textfield.text {
API.createNewPlaylist(name: playlistName) { [weak self] (playlist, error) in
if let error = error {
print(error)
// Showing error message
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let playlist = playlist {
if self?.playlists[safe: 1] != nil {
self?.collectionView.performBatchUpdates({
self?.playlists.insert(playlist, at: 1)
self?.collectionView.insertItems(at: [IndexPath(item: 1, section: 0)])
}, completion: nil)
}
}
}
}
}
createAction.isEnabled = false
alertController.addAction(cancelAction)
alertController.addAction(createAction)
present(alertController, animated: true, completion: nil)
}
func textDidChange (textField: UITextField) {
if let topVc = UIApplication.topViewController() as? UIAlertController, let createAction = topVc.actions[safe: 1] {
if let text = textField.text, text != "" {
createAction.isEnabled = true
} else {
createAction.isEnabled = false
}
} */
}
}
// MARK: UICollectionViewDelegate
extension LibraryViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let playlistVC = PlaylistViewController()
playlistVC.playlist = playlists[safe: indexPath.item]
if playlistVC.playlist?.name == "Recommended by Soundwich" {
let playlistParameters = ["playlist": "Soundwich Recommended"] as [String: Any]
Flurry.logEvent("Selecting_a_playlist", withParameters: playlistParameters)
} else if playlistVC.playlist?.name == "Received on Soundwich" {
let playlistParameters = ["playlist": "Soundwich Received"] as [String: Any]
Flurry.logEvent("Selecting_a_playlist", withParameters: playlistParameters)
} else {
let playlistParameters = ["playlist": "Theirs"] as [String: Any]
Flurry.logEvent("Selecting_a_playlist", withParameters: playlistParameters)
}
navigationController?.pushViewController(playlistVC, animated: true)
}
}
// MARK: UICollectionViewDataSource
extension LibraryViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return playlists.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PlaylistCell.identifier, for: indexPath) as? PlaylistCell {
let playlist = playlists[safe: indexPath.item]
cell.playlist = playlist
if indexPath.item == 0 {
cell.subTitleLabel.text = "Soundwich"
}
// Create ne playlist
/*if indexPath.item == 0 {
cell.imageView.image = #imageLiteral(resourceName: "icon_add_playlist").withRenderingMode(.alwaysTemplate)
cell.subTitleLabel.isHidden = true
cell.imageView.tintColor = ColorPalette.white
}*/
if let totalItems = spotifyObject?.items?.count, indexPath.item == totalItems - 1, spotifyObject?.next != nil {
if !isFetching {
fetchPlaylists()
}
}
return cell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionFooter:
if let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: LoadingFooterView.identifier, for: indexPath) as? LoadingFooterView {
return footerView
}
default: break
}
return UICollectionReusableView()
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension LibraryViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width - (contentInset * 2), height: 72)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if spotifyObject?.next != nil {
return CGSize(width: view.frame.width, height: 36)
}
return .zero
}
}
extension LibraryViewController: ScrollDelegate {
func scrollToTop() {
if spotifyObject?.items?.count ?? 0 > 0 {
collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true)
}
}
}
| mit | c6e61f163780c69e625a437559c64cbc | 43.020161 | 227 | 0.61221 | 5.545847 | false | false | false | false |
khizkhiz/swift | test/IRGen/objc_structs.swift | 2 | 3722 | // RUN: rm -rf %t && mkdir %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
// CHECK: [[NSRECT:%VSC6NSRect]] = type <{ [[NSPOINT:%VSC7NSPoint]], [[NSSIZE:%VSC6NSSize]] }>
// CHECK: [[NSPOINT]] = type <{ [[DOUBLE:%Sd]], [[DOUBLE]] }>
// CHECK: [[DOUBLE]] = type <{ double }>
// CHECK: [[NSSIZE]] = type <{ [[DOUBLE]], [[DOUBLE]] }>
// CHECK: [[GIZMO:%CSo5Gizmo]] = type opaque
// CHECK: [[NSSTRING:%CSo8NSString]] = type opaque
// CHECK: [[NSVIEW:%CSo6NSView]] = type opaque
// CHECK: define hidden void @_TF12objc_structs8getFrame{{.*}}([[NSRECT]]* noalias nocapture sret, [[GIZMO]]*) {{.*}} {
func getFrame(g: Gizmo) -> NSRect {
// CHECK: load i8*, i8** @"\01L_selector(frame)"
// CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}})
return g.frame()
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs8setFrame{{.*}}(%CSo5Gizmo*, %VSC6NSRect* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func setFrame(g: Gizmo, frame: NSRect) {
// CHECK: load i8*, i8** @"\01L_selector(setFrame:)"
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}})
g.setFrame(frame)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs8makeRect{{.*}}([[NSRECT]]* noalias nocapture sret, double, double, double, double)
func makeRect(a: Double, b: Double, c: Double, d: Double) -> NSRect {
// CHECK: call void @NSMakeRect([[NSRECT]]* noalias nocapture sret {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}})
return NSMakeRect(a,b,c,d)
}
// CHECK: }
// CHECK: define hidden [[stringLayout:[^@]*]] @_TF12objc_structs14stringFromRect{{.*}}(%VSC6NSRect* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func stringFromRect(r: NSRect) -> String {
// CHECK: call [[OPAQUE0:.*]]* @NSStringFromRect([[NSRECT]]* byval align 8 {{.*}})
return NSStringFromRect(r)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs9insetRect{{.*}}([[NSRECT]]* noalias nocapture sret, %VSC6NSRect* noalias nocapture dereferenceable({{.*}}), double, double)
func insetRect(r: NSRect, x: Double, y: Double) -> NSRect {
// CHECK: call void @NSInsetRect([[NSRECT]]* noalias nocapture sret {{.*}}, [[NSRECT]]* byval align 8 {{.*}}, double {{.*}}, double {{.*}})
return NSInsetRect(r, x, y)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs19convertRectFromBase{{.*}}([[NSRECT]]* noalias nocapture sret, [[NSVIEW]]*, [[NSRECT]]* noalias nocapture dereferenceable({{.*}}))
func convertRectFromBase(v: NSView, r: NSRect) -> NSRect {
// CHECK: load i8*, i8** @"\01L_selector(convertRectFromBase:)", align 8
// CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}})
return v.convertRect(fromBase: r)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs20useStructOfNSStringsFVSC17StructOfNSStringsS0_(%VSC17StructOfNSStrings* noalias nocapture sret, %VSC17StructOfNSStrings* noalias nocapture dereferenceable({{.*}}))
// CHECK: call void @useStructOfNSStringsInObjC(%VSC17StructOfNSStrings* noalias nocapture sret {{%.*}}, %VSC17StructOfNSStrings* byval align 8 {{%.*}})
func useStructOfNSStrings(s: StructOfNSStrings) -> StructOfNSStrings {
return useStructOfNSStringsInObjC(s)
}
| apache-2.0 | 360914201c466f9af6a3a1bd9c8d797a | 53.735294 | 231 | 0.637023 | 3.833162 | false | false | false | false |
srn214/Floral | Floral/Floral/Classes/Expand/Extensions/Network/Codable/ObservableType+Codable.swift | 1 | 1016 | //
// ObservableType+Codable.swift
// Floral
//
// Created by LDD on 2019/7/18.
// Copyright © 2019 文刂Rn. All rights reserved.
//
import UIKit
import Moya
import CleanJSON
public extension ObservableType where Element == Response {
func mapObject<T: Codable>(_ type: T.Type, atKeyPath path: String? = nil, using decoder: JSONDecoder = CleanJSONDecoder()) -> Observable<T> {
return map {
guard let response = try? $0.mapObject(type, atKeyPath: path, using: decoder, failsOnEmptyData: true) else {
throw MoyaError.jsonMapping($0)
}
return response
}
}
func mapObject<T: Codable>(_ type: T.Type, using decoder: JSONDecoder = CleanJSONDecoder()) -> Observable<T> {
return map {
guard let response = try? $0.mapObject(type, using: decoder) else {
throw MoyaError.jsonMapping($0)
}
return response
}
}
}
| mit | 318030b154a087bd210d404e8670d88c | 26.324324 | 145 | 0.576657 | 4.473451 | false | false | false | false |
tedinpcshool/classmaster | classmaster_good/classmaster/RegisterVC.swift | 1 | 5660 | //
// RegisterVC.swift
// classmaster
//
// Created by 黃威淵 on 2017/5/23.
// Copyright © 2017年 pcschool. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class RegisterVC: UIViewController,UITextFieldDelegate,ZHDropDownMenuDelegate {
@IBOutlet weak var newUserNameTextField: UITextField!
@IBOutlet weak var newPassWordTextField: UITextField!
@IBOutlet weak var genderMenu: ZHDropDownMenu!
@IBOutlet weak var newEmailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
let userDefault = UserDefaults.standard
var users = [String]()
var passWords = [String]()
var genderStr:String?
var emails = [String]()
var phones = [String]()
var nUserInfo:[NSData] = []
var userInfo:UserInfo?
var classInfo:[ClassModel] = []
override func viewDidLoad() {
super.viewDidLoad()
newUserNameTextField.delegate = self
newPassWordTextField.delegate = self
newEmailTextField.delegate = self
phoneTextField.delegate = self
genderMenu.options = ["男","女"]
genderMenu.showBorder = true
genderMenu.menuHeight = 100
genderMenu.delegate = self
// userDefault.removeObject(forKey: "userInfo")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerBtn(_ sender: UIButton) {
if newEmailTextField.text == "" && phoneTextField.text == ""
{
msg(myTitle: "抱歉", myMessage: "請留完整資料")
return
}
Auth.auth().createUser(withEmail: newEmailTextField.text!, password: newPassWordTextField.text!) { (user, error) in
if error != nil{
print(error!.localizedDescription)
return
}
self.userDefault.set(user?.uid, forKey: "useruid")
}
// if userDefault.object(forKey: "userInfo") != nil
// {
//
// nUserInfo = userDefault.array(forKey: "userInfo") as! [UserInfo]
//
//// users = userDefault.array(forKey: "usernames") as! [String]
//// passWords = userDefault.array(forKey: "passwords") as! [String]
//// genders = userDefault.array(forKey: "genders") as! [String]
//// emails = userDefault.array(forKey: "emails") as! [String]
//// phones = userDefault.array(forKey: "phones") as! [String]
//
// }
// if nUserInfo.count == 0
// {
// let delegate = UIApplication.shared.delegate as! AppDelegate
// if delegate.aUserInfo.count == 0
// {
//
// delegate.aUserInfo = [userInfo!]
// }
// nUserInfo = delegate.aUserInfo
// }
//
let newUser = UserInfo(userName: newUserNameTextField.text!, gender: genderStr!, email: newEmailTextField.text!, passWord: newPassWordTextField.text!, phone: phoneTextField.text!)
let newName = NSKeyedArchiver.archivedData(withRootObject: newUser.userName!) as NSData
let newGender = NSKeyedArchiver.archivedData(withRootObject: newUser.gender!) as NSData
let newEmail = NSKeyedArchiver.archivedData(withRootObject: newUser.email!) as NSData
let newPassWord = NSKeyedArchiver.archivedData(withRootObject: newUser.passWord!) as NSData
let newPhone = NSKeyedArchiver.archivedData(withRootObject: newUser.phone!) as NSData
nUserInfo = [newName ,newGender ,newEmail ,newPassWord ,newPhone]
userDefault.set(nUserInfo, forKey: "userInfo")
userDefault.synchronize()
// users.insert(newUserNameTextField.text!, at: users.count)
// passWords.insert(newPassWordTextField.text!, at: passWords.count)
// genders.insert(genderTextField.text!, at: genders.count)
// emails.insert(newEmailTextField.text!, at: emails.count)
// phones.insert(phoneTextField.text!, at: phones.count)
// userDefault.set(users, forKey: "usernames")
// userDefault.set(passWords, forKey: "passwords")
// userDefault.set(genders, forKey: "genders")
// userDefault.set(emails, forKey: "emails")
// userDefault.set(phones, forKey: "phones")
self.navigationController?.popViewController(animated: true)
}
func msg(myTitle:String,myMessage:String){
let alertController = UIAlertController(title: myTitle, message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
let btn1 = UIAlertAction(title: "確定", style: UIAlertActionStyle.default) {(btn1)in
}
alertController.addAction(btn1)
present(alertController, animated: false, completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
newUserNameTextField.resignFirstResponder()
newPassWordTextField.resignFirstResponder()
newEmailTextField.resignFirstResponder()
phoneTextField.resignFirstResponder()
return true
}
func dropDownMenu(_ menu: ZHDropDownMenu!, didChoose index: Int) {
genderStr = menu.options[index]
// print("\(menu) choosed at index \(index)")
}
func dropDownMenu(_ menu: ZHDropDownMenu!, didInput text: String!) {
print("\(menu) input text \(text)")
}
}
| mit | 90971fbc87ba566a1ec468bc405fe310 | 33.10303 | 189 | 0.61507 | 4.658113 | false | false | false | false |
Sharelink/Bahamut | Bahamut/BahamutCommon/NormalDistribution.swift | 1 | 4331 | //
// NormalDistribution.swift
// FidgetSpinner
//
// Created by Alex Chow on 2017/5/30.
// Copyright © 2017年 Bahamut. All rights reserved.
//
import Foundation
class NormalDistribution {
static func calculate(m:Double,sd:Double,x1:Double) -> Double {
var plx1 = 0.0
let intx1=integrate(x: x1, m: m, sd: sd)
if x1 < m{
plx1 = 0.5 - intx1
}
if x1 > m{
plx1 = 0.5 + intx1
}
if x1 == m{
plx1 = 0.5;
}
if plx1 < 0{
plx1 = 0
}
if plx1 > 1{
plx1 = 1
}
return round(plx1*1000000)/1000000;
}
static private func integrate(x:Double, m:Double, sd:Double) -> Double{
let z = round(abs((m-x)/sd)*100)/100;
let index = Int(z*100)
return index >= nd.count ? 1 : index < 0 ? 0 : nd[index]
}
}
private let nd:[Double] = [0,0.004,0.008,0.012,0.016,0.0199,0.0239,0.0279,0.0319,0.0359,
0.0398,0.0438,0.0478,0.0517,0.0557,0.0596,0.0636,0.0675,0.0714,0.0753,
0.0793,0.0832,0.0871,0.091,0.0948,0.0987,0.1026,0.1064,0.1103,0.1141,
0.1179,0.1217,0.1255,0.1293,0.1331,0.1368,0.1406,0.1443,0.148,0.1517,
0.1554,0.1591,0.1628,0.1664,0.17,0.1736,0.1772,0.1808,0.1844,0.1879,
0.1915,0.195,0.1985,0.2019,0.2054,0.2088,0.2123,0.2157,0.219,0.2224,
0.2257,0.2291,0.2324,0.2357,0.2389,0.2422,0.2454,0.2486,0.2517,0.2549,
0.258,0.2611,0.2642,0.2673,0.2704,0.2734,0.2764,0.2794,0.2823,0.2852,
0.2881,0.291,0.2939,0.2967,0.2995,0.3023,0.3051,0.3078,0.3106,0.3133,
0.3159,0.3186,0.3212,0.3238,0.3264,0.3289,0.3315,0.334,0.3365,0.3389,
0.3413,0.3438,0.3461,0.3485,0.3508,0.3531,0.3554,0.3577,0.3599,0.3621,
0.3643,0.3665,0.3686,0.3708,0.3729,0.3749,0.377,0.379,0.381,0.383,
0.3849,0.3869,0.3888,0.3907,0.3925,0.3944,0.3962,0.398,0.3997,0.4015,
0.4032,0.4049,0.4066,0.4082,0.4099,0.4115,0.4131,0.4147,0.4162,0.4177,
0.4192,0.4207,0.4222,0.4236,0.4251,0.4265,0.4279,0.4292,0.4306,0.4319,
0.4332,0.4345,0.4357,0.437,0.4382,0.4394,0.4406,0.4418,0.4429,0.4441,
0.4452,0.4463,0.4474,0.4484,0.4495,0.4505,0.4515,0.4525,0.4535,0.4545,
0.4554,0.4564,0.4573,0.4582,0.4591,0.4599,0.4608,0.4616,0.4625,0.4633,
0.4641,0.4649,0.4656,0.4664,0.4671,0.4678,0.4686,0.4693,0.4699,0.4706,
0.4713,0.4719,0.4726,0.4732,0.4738,0.4744,0.475,0.4756,0.4761,0.4767,
0.4772,0.4778,0.4783,0.4788,0.4793,0.4798,0.4803,0.4808,0.4812,0.4817,
0.4821,0.4826,0.483,0.4834,0.4838,0.4842,0.4846,0.485,0.4854,0.4857,
0.4861,0.4864,0.4868,0.4871,0.4875,0.4878,0.4881,0.4884,0.4887,0.489,
0.4893,0.4896,0.4898,0.4901,0.4904,0.4906,0.4909,0.4911,0.4913,0.4916,
0.4918,0.492,0.4922,0.4925,0.4927,0.4929,0.4931,0.4932,0.4934,0.4936,
0.4938,0.494,0.4941,0.4943,0.4945,0.4946,0.4948,0.4949,0.4951,0.4952,
0.4953,0.4955,0.4956,0.4957,0.4959,0.496,0.4961,0.4962,0.4963,0.4964,
0.4965,0.4966,0.4967,0.4968,0.4969,0.497,0.4971,0.4972,0.4973,0.4974,
0.4974,0.4975,0.4976,0.4977,0.4977,0.4978,0.4979,0.4979,0.498,0.4981,
0.4981,0.4982,0.4982,0.4983,0.4984,0.4984,0.4985,0.4985,0.4986,0.4986,
0.4987,0.4987,0.4987,0.4988,0.4988,0.4989,0.4989,0.4989,0.499,0.499,
0.499,0.4991,0.4991,0.4991,0.4992,0.4992,0.4992,0.4992,0.4993,0.4993,
0.4993,0.4993,0.4994,0.4994,0.4994,0.4994,0.4994,0.4995,0.4995,0.4995,
0.4995,0.4995,0.4995,0.4996,0.4996,0.4996,0.4996,0.4996,0.4996,0.4997,
0.4997,0.4997,0.4997,0.4997,0.4997,0.4997,0.4997,0.4997,0.4997,0.4998];
| mit | 5957a9edcf61da4f20ab0c07f5992b06 | 52.432099 | 98 | 0.502542 | 2.160759 | false | false | false | false |
sarvex/Stormy | Stormy/AppDelegate.swift | 1 | 6189 | //
// AppDelegate.swift
// Stormy
//
// Created by Sarvex Jatasra on 12/04/2015.
// Copyright (c) 2015 Sarvex Jatasra. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.setStatusBarHidden(true, withAnimation: .None)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.sarvex.Stormy" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Stormy", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Stormy.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| isc | 932373dd86ff039a68a66eae0d6b1a00 | 54.258929 | 290 | 0.715624 | 5.704147 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.Pm25Density.swift | 1 | 2057 | import Foundation
public extension AnyCharacteristic {
static func pm25Density(
_ value: Float = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "PM2.5 Density",
format: CharacteristicFormat? = .float,
unit: CharacteristicUnit? = .microgramsPerMCubed,
maxLength: Int? = nil,
maxValue: Double? = 1000,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.pm25Density(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func pm25Density(
_ value: Float = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "PM2.5 Density",
format: CharacteristicFormat? = .float,
unit: CharacteristicUnit? = .microgramsPerMCubed,
maxLength: Int? = nil,
maxValue: Double? = 1000,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Float> {
GenericCharacteristic<Float>(
type: .pm25Density,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 276293a3a173fa177381d8698f66d13d | 32.721311 | 67 | 0.578512 | 5.168342 | false | false | false | false |
DouglasHeriot/protobuf-swift | Source/GeneratedMessage.swift | 1 | 4512 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public protocol GeneratedMessageProtocol: ProtocolBuffersMessage {
associatedtype BuilderType:GeneratedMessageBuilderProtocol
static func parseFrom(data: Data) throws -> Self
static func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> Self
static func parseFrom(inputStream:InputStream) throws -> Self
static func parseFrom(inputStream:InputStream, extensionRegistry:ExtensionRegistry) throws -> Self
static func parseFrom(codedInputStream:CodedInputStream) throws -> Self
static func parseFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self
subscript(key: String) -> Any? { get }
}
public protocol GeneratedEnum:RawRepresentable, CustomDebugStringConvertible, CustomStringConvertible, Hashable {
func toString() -> String
static func fromString(_ str:String) throws -> Self
}
public protocol GeneratedMessageBuilderProtocol: ProtocolBuffersMessageBuilder {
subscript(key: String) -> Any? { get set }
}
open class GeneratedMessage:AbstractProtocolBuffersMessage
{
public var memoizedSerializedSize:Int32 = -1
required public init()
{
super.init()
self.unknownFields = UnknownFieldSet(fields: [:])
}
//Override
open class func className() -> String
{
return "GeneratedMessage"
}
open func className() -> String
{
return "GeneratedMessage"
}
open override class func classBuilder() -> ProtocolBuffersMessageBuilder
{
return GeneratedMessageBuilder()
}
open override func classBuilder() -> ProtocolBuffersMessageBuilder
{
return GeneratedMessageBuilder()
}
//
}
open class GeneratedMessageBuilder:AbstractProtocolBuffersMessageBuilder
{
open var internalGetResult:GeneratedMessage
{
get
{
return GeneratedMessage()
}
}
override open var unknownFields:UnknownFieldSet
{
get
{
return internalGetResult.unknownFields
}
set (fields)
{
internalGetResult.unknownFields = fields
}
}
public func checkInitialized() throws {
let result = internalGetResult
try result.isInitialized()
}
public func checkInitializedParsed() throws {
let result = internalGetResult
try result.isInitialized()
}
override open func isInitialized() throws {
try internalGetResult.isInitialized()
}
@discardableResult
override open func merge(unknownField: UnknownFieldSet) throws -> Self
{
let result:GeneratedMessage = internalGetResult
result.unknownFields = try UnknownFieldSet.builderWithUnknownFields(copyFrom: result.unknownFields).merge(unknownFields: unknownField).build()
return self
}
public func parse(codedInputStream:CodedInputStream ,unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, tag:Int32) throws -> Bool {
return try unknownFields.mergeFieldFrom(tag: tag, input:codedInputStream)
}
}
extension GeneratedMessage:CustomDebugStringConvertible {
public var debugDescription:String {
return description
}
}
extension GeneratedMessage:CustomStringConvertible {
public var description:String {
get {
var output:String = ""
output += try! getDescription(indent: "")
return output
}
}
}
extension GeneratedMessageBuilder:CustomDebugStringConvertible {
public var debugDescription:String {
return internalGetResult.description
}
}
extension GeneratedMessageBuilder:CustomStringConvertible {
public var description:String {
get {
return internalGetResult.description
}
}
}
| apache-2.0 | 47d5573760f89415ae4cb0a3ea2d4472 | 29.693878 | 160 | 0.702128 | 5.64 | false | false | false | false |
proversity-org/edx-app-ios | Source/OEXColors.swift | 1 | 4711 | //
// OEXColors.swift
// edX
//
// Created by Danial Zahid on 8/17/16.
// Copyright © 2016 edX. All rights reserved.
//
import UIKit
public class OEXColors: NSObject {
//MARK: - Shared Instance
@objc public static let sharedInstance = OEXColors()
@objc public enum ColorsIdentifiers: Int {
case PrimaryXDarkColor = 1, PrimaryDarkColor, PrimaryBaseColor, PrimaryLightColor, PrimaryXLightColor,
SecondaryXDarkColor, SecondaryDarkColor, SecondaryBaseColor, SecondaryLightColor, SecondaryXLightColor,
NeutralBlack, NeutralBlackT, NeutralXDark, NeutralDark, NeutralBase,
NeutralLight, NeutralXLight, NeutralXXLight, NeutralWhite, NeutralWhiteT,
UtilitySuccessDark, UtilitySuccessBase, UtilitySuccessLight,
WarningDark, WarningBase, WarningLight,
ErrorDark, ErrorBase, ErrorLight,
Banner, Random
}
public var colorsDictionary = [String: AnyObject]()
private override init() {
super.init()
colorsDictionary = initializeColorsDictionary()
}
private func initializeColorsDictionary() -> [String: AnyObject] {
guard let filePath = Bundle.main.path(forResource: "colors", ofType: "json") else {
return fallbackColors()
}
if let data = NSData(contentsOfFile: filePath) {
var error : NSError?
if let json = JSON(data: data as Data, error: &error).dictionaryObject{
return json as [String : AnyObject]
}
return fallbackColors()
}
return fallbackColors()
}
@discardableResult public func fallbackColors() -> [String: AnyObject] {
return OEXColorsDataFactory.colors as [String : AnyObject]
}
@objc public func color(forIdentifier identifier: ColorsIdentifiers) -> UIColor {
return color(forIdentifier: identifier, alpha: 1.0)
}
public func color(forIdentifier identifier: ColorsIdentifiers, alpha: CGFloat) -> UIColor {
if let hexValue = colorsDictionary[getIdentifier(identifier: identifier)] as? String {
let color = UIColor(hexString: hexValue, alpha: alpha)
return color
}
return UIColor(hexString: getIdentifier(identifier: ColorsIdentifiers.Random), alpha: 1.0)
}
private func getIdentifier(identifier: ColorsIdentifiers) -> String {
switch identifier {
case .PrimaryXDarkColor:
return "primaryXDarkColor"
case .PrimaryDarkColor:
return "primaryDarkColor"
case .PrimaryBaseColor:
return "primaryBaseColor"
case .PrimaryLightColor:
return "primaryLightColor"
case .PrimaryXLightColor:
return "primaryXLightColor"
case .SecondaryXDarkColor:
return "secondaryXDarkColor"
case .SecondaryDarkColor:
return "secondaryDarkColor"
case .SecondaryBaseColor:
return "secondaryBaseColor"
case .SecondaryLightColor:
return "secondaryLightColor"
case .SecondaryXLightColor:
return "secondaryXLightColor"
case .NeutralBlack:
return "neutralBlack"
case .NeutralBlackT:
return "neutralBlackT"
case .NeutralXDark:
return "neutralXDark"
case .NeutralDark:
return "neutralDark"
case .NeutralBase:
return "neutralBase"
case .NeutralLight:
return "neutralLight"
case .NeutralXLight:
return "neutralXLight"
case .NeutralXXLight:
return "neutralXXLight"
case .NeutralWhite:
return "neutralWhite"
case .NeutralWhiteT:
return "neutralWhiteT"
case .UtilitySuccessDark:
return "utilitySuccessDark"
case .UtilitySuccessBase:
return "utilitySuccessBase"
case .UtilitySuccessLight:
return "utilitySuccessLight"
case .WarningDark:
return "warningDark"
case .WarningBase:
return "warningBase"
case .WarningLight:
return "warningLight"
case .ErrorDark:
return "errorDark"
case .ErrorBase:
return "errorBase"
case .ErrorLight:
return "errorLight"
case .Banner:
return "banner"
case .Random:
fallthrough
default:
//Assert to crash on development, and return a random color for distribution
assert(false, "Could not find the required color in colors.json")
return "#FABA12"
}
}
}
| apache-2.0 | 165d460fd09cd67da7b0bbf26e00d461 | 33.632353 | 111 | 0.619533 | 5.042827 | false | false | false | false |
brunophilipe/Noto | Noto/Extensions/NSMenuItem+EditorTheme.swift | 1 | 1384 | //
// Created by Bruno Philipe on 12/3/17.
// Copyright (c) 2017 Bruno Philipe. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Cocoa
extension NSMenuItem
{
static func itemForEditorTheme(_ theme: EditorTheme,
_ selectedItem: inout NSMenuItem?,
target: AnyObject,
_ selector: Selector,
selectedThemeName: String = Preferences.instance.editorThemeName) -> NSMenuItem
{
let menuItem = NSMenuItem(title: theme.name,
action: selector,
keyEquivalent: "")
menuItem.target = target
menuItem.representedObject = theme
if selectedItem == nil && theme.preferenceName == selectedThemeName
{
selectedItem = menuItem
menuItem.state = .on
}
return menuItem
}
}
| gpl-3.0 | a045776aaf18f3995a763c70b51072ed | 29.755556 | 90 | 0.700867 | 4.156156 | false | false | false | false |
easytargetmixel/micopi_ios | micopi/Engine/Foliage/Foliage.swift | 1 | 5036 | import CoreGraphics
class Foliage {
let maxJitter: Double
var firstNode: FoliageNode!
var worldSize: Double
var age = 0
let maxAge = 1024 * 32
var totalNodeCounter = 0
var maxNumOfNodesAddedPerRound = 2 // 4
var maxNumOfTotalNodes = 256
var nodeAddCounter = 0
var nodeDensity: Int
var stopped = false
var addNodes = false
var lineGray = 1.0
var lineAlpha = 0.2
var randomNumberGenerator: RandomNumberGenerator = RandomNumberGenerator()
var jitter: Double {
get {
return randomNumberGenerator.d(
greater: -maxJitter,
smaller: maxJitter
)
}
}
init(
worldSize: Double,
numOfInitialNodes: Int,
maxJitter: Double,
startX: Double,
startY: Double,
radius: Double
) {
self.worldSize = worldSize
self.maxJitter = maxJitter
nodeDensity = numOfInitialNodes / 16
initCircle(
numOfInitialNodes: numOfInitialNodes,
startX: startX,
startY: startY,
radius: radius
)
}
fileprivate func initCircle(
numOfInitialNodes: Int,
startX: Double,
startY: Double,
radius: Double
) {
let circleCenterX = startX
let circleCenterY = startY
let minSqueezeFactorMin = 0.66
let squeezeFactor = randomNumberGenerator.d(
greater: minSqueezeFactorMin,
smaller: minSqueezeFactorMin * 2.0
)
var lastNode: FoliageNode!
for nodeIndex in 0 ..< numOfInitialNodes {
let angleOfNode = Double.pi
* ((Double(nodeIndex) + 1.0) / Double(numOfInitialNodes))
let x = circleCenterX
+ ((cos(angleOfNode) * radius) * squeezeFactor)
+ jitter
let y = circleCenterY
+ (sin(angleOfNode) * radius)
+ jitter
let nodePosition = Vector2(x, y)
let node = FoliageNode(
positionVector: nodePosition,
maxJitter: maxJitter,
worldSize: worldSize
)
if firstNode == nil {
firstNode = node
lastNode = node
} else if (nodeIndex == numOfInitialNodes - 1) {
lastNode.next = node
node.next = firstNode
} else {
lastNode.next = node
lastNode = node
}
}
totalNodeCounter += 1
}
func stop() {
self.stopped = true
}
func updateAndDraw(
nodeDrawer: FoliageNodeCGDrawer,
invertMovement: Bool = false
) -> Bool {
age += 1
guard age < maxAge else {
return false
}
var currentNode: FoliageNode!
var nodeCounter = 0
adjustColor()
repeat {
if let currentNode = currentNode {
nodeDrawer.addNodeToLine(node: currentNode)
} else {
currentNode = firstNode
nodeDrawer.startLine(
firstNode: firstNode,
gray: lineGray,
alpha: lineAlpha
)
}
guard let nextNode = currentNode?.next else {
return true
}
currentNode.update(invertMovement: invertMovement)
if addNodes,
nodeAddCounter < maxNumOfNodesAddedPerRound,
totalNodeCounter < maxNumOfTotalNodes,
nodeCounter % nodeDensity == 0
{
addNodeNextTo(node: currentNode)
}
currentNode = nextNode
nodeCounter += 1
} while (!stopped && currentNode !== firstNode)
nodeDrawer.closeAndDrawLine()
nodeAddCounter = 0
return true
}
fileprivate func adjustColor() {
let maxColorStep = 0.05
lineGray += randomNumberGenerator.d(
greater: -maxColorStep,
smaller: maxColorStep
)
if lineGray < 0 {
lineGray = 0
} else if lineGray > 1 {
lineGray = 1
}
}
fileprivate func addNodeNextTo(node: FoliageNode) {
guard let oldNeighbour = node.next else {
return
}
let newNeighbourPos = (node.positionVector + oldNeighbour.positionVector) * 0.5
// .add()
// .mult(0.5)
let newNeighbour = FoliageNode(
positionVector: newNeighbourPos,
maxJitter: maxJitter,
worldSize: worldSize
)
node.next = newNeighbour
newNeighbour.next = oldNeighbour
nodeAddCounter += 1
totalNodeCounter += 1
}
}
| gpl-3.0 | 0c76b0ee7d0dbdfaf977b1bbbd218fc5 | 26.221622 | 87 | 0.504369 | 4.976285 | false | false | false | false |
inderdhir/DatWeatherDoe | DatWeatherDoe/Reachability/WeatherReachability.swift | 1 | 1732 | //
// NetworkReachability.swift
// DatWeatherDoe
//
// Created by Inder Dhir on 1/11/22.
// Copyright © 2022 Inder Dhir. All rights reserved.
//
import Reachability
final class NetworkReachability {
private let logger: DatWeatherDoeLoggerType
private var reachability: Reachability?
private var retryWhenReachable = false
init(
logger: DatWeatherDoeLoggerType,
onBecomingReachable: @escaping () -> Void
) {
self.logger = logger
setupWith(callback: onBecomingReachable)
}
private func setupWith(callback: @escaping () ->Void) {
do {
try createReachability()
try startReachability()
updateReachabilityWhenReachable(callback: callback)
updateReachabilityWhenUnreachable()
} catch {
logger.error("Reachability error!")
}
}
private func createReachability() throws {
reachability = try Reachability()
}
private func startReachability() throws {
try reachability?.startNotifier()
}
private func updateReachabilityWhenReachable(callback: @escaping () ->Void) {
reachability?.whenReachable = { [weak self] _ in
self?.logger.debug("Reachability status: Reachable")
if self?.retryWhenReachable == true {
self?.retryWhenReachable = false
callback()
}
}
}
private func updateReachabilityWhenUnreachable() {
reachability?.whenUnreachable = { [weak self] _ in
self?.logger.debug("Reachability status: Unreachable")
self?.retryWhenReachable = true
}
}
}
| apache-2.0 | 8a60046a3ea0bc4b836bcad565815723 | 26.47619 | 81 | 0.602542 | 5.359133 | false | false | false | false |
Roche/viper-module-generator | VIPERGenDemo/VIPERGenDemo/Libraries/Swifter/Swifter/String+Swifter.swift | 5 | 3613 | //
// String+Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension String {
internal func indexOf(sub: String) -> Int? {
var pos: Int?
if let range = self.rangeOfString(sub) {
if !range.isEmpty {
pos = distance(self.startIndex, range.startIndex)
}
}
return pos
}
internal subscript (r: Range<Int>) -> String {
get {
let startIndex = advance(self.startIndex, r.startIndex)
let endIndex = advance(startIndex, r.endIndex - r.startIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String {
let charactersToBeEscaped = ":/?&=;+!@#$()',*" as CFStringRef
let charactersToLeaveUnescaped = "[]." as CFStringRef
let str = self as NSString
let result = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str as CFString, charactersToLeaveUnescaped, charactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) as NSString
return result as String
}
func parametersFromQueryString() -> Dictionary<String, String> {
var parameters = Dictionary<String, String>()
let scanner = NSScanner(string: self)
var key: NSString?
var value: NSString?
while !scanner.atEnd {
key = nil
scanner.scanUpToString("=", intoString: &key)
scanner.scanString("=", intoString: nil)
value = nil
scanner.scanUpToString("&", intoString: &value)
scanner.scanString("&", intoString: nil)
if key != nil && value != nil {
parameters.updateValue(value!, forKey: key!)
}
}
return parameters
}
func SHA1DigestWithKey(key: String) -> NSData {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = UInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_SHA1_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)
let keyLen = UInt(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), keyStr!, keyLen, str!, strLen, result)
return NSData(bytes: result, length: digestLen)
}
}
| mit | 6185701e3631dfee84eac4a3606e0358 | 34.772277 | 214 | 0.664821 | 4.882432 | false | false | false | false |
ryanglobus/Augustus | Augustus/AULog.swift | 1 | 1700 | //
// AULog.swift
// Augustus
//
// Created by Ryan Globus on 8/8/15.
// Copyright (c) 2015 Ryan Globus. All rights reserved.
//
import Foundation
class AULog {
enum Level: Int, CustomStringConvertible {
case debug = 1, info, warn, error
var description: String {
switch self {
case .debug: return "DEBUG"
case .info: return "INFO"
case .warn: return "WARN"
case .error: return "ERROR"
}
}
}
static let instance = AULog(minLevel: .debug)
let minLevel: Level
init(minLevel: Level) {
self.minLevel = minLevel
}
func log(_ message_: Any?, level: Level, file: String = #file, line: Int = #line) {
var file = file
guard level.rawValue >= self.minLevel.rawValue else {
return
}
file = (file as NSString).lastPathComponent
if let message = message_ {
NSLog("\(level) (\(file):\(line)) - \(message)")
} else {
NSLog("\(level) (\(file):\(line)) - ")
}
}
func debug(_ message_: Any?, file: String = #file, line: Int = #line) {
log(message_, level: .debug, file: file, line: line)
}
func info(_ message_: Any?, file: String = #file, line: Int = #line) {
log(message_, level: .info, file: file, line: line)
}
func warn(_ message_: Any?, file: String = #file, line: Int = #line) {
log(message_, level: .warn, file: file, line: line)
}
func error(_ message_: Any?, file: String = #file, line: Int = #line) {
log(message_, level: .error, file: file, line: line)
}
}
| gpl-2.0 | 27acfb3bb437bf4b7c9728a58c85dfdf | 25.984127 | 87 | 0.523529 | 3.846154 | false | false | false | false |
iOS-Swift-Developers/Swift | 实战项目一/JQLiveTV/JQLiveTV/Classes/Home/Controller/AnchorViewController.swift | 1 | 3113 | //
// AnchorViewController.swift
// JQLiveTV
//
// Created by 韩俊强 on 2017/7/31.
// Copyright © 2017年 HaRi. All rights reserved.
// 欢迎加入iOS交流群: ①群:446310206 ②群:426087546
import UIKit
private let kEdgeMargin : CGFloat = 8
private let kAnchorCellID = "kAnchorCellID"
class AnchorViewController: UIViewController {
// MARK: 对外属性
var homeType : HomeType!
// MARK: 自定义属性
fileprivate lazy var homeVM : HomeViewModel = HomeViewModel()
fileprivate lazy var collectionView : UICollectionView = {
let layout = WaterfallLayout()
layout.sectionInset = UIEdgeInsets(top: kEdgeMargin, left: kEdgeMargin, bottom: kEdgeMargin, right: kEdgeMargin)
layout.minimumLineSpacing = kEdgeMargin
layout.minimumInteritemSpacing = kEdgeMargin
layout.dataSource = self
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "HomeViewCell", bundle: nil),forCellWithReuseIdentifier: kAnchorCellID)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData(index: 0)
}
}
// MARK:- 设置UI界面内容
extension AnchorViewController {
fileprivate func setupUI() {
view.addSubview(collectionView)
}
}
extension AnchorViewController {
fileprivate func loadData(index : Int) {
homeVM.loadHomeData(type: homeType, index: index, finishedCallback: {
self.collectionView.reloadData()
})
}
}
// AMRK:- collectionView的数据源&代理
extension AnchorViewController : UICollectionViewDataSource, WaterfallLayoutDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return homeVM.anchorModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAnchorCellID, for: indexPath) as! HomeViewCell
cell.anchorModel = homeVM.anchorModels[indexPath.item]
if indexPath.item == homeVM.anchorModels.count - 1 {
loadData(index: homeVM.anchorModels.count)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let roomVc = RoomViewController()
roomVc.anchor = homeVM.anchorModels[indexPath.item]
navigationController?.pushViewController(roomVc, animated: true)
}
func waterfallLayout(_ latout: WaterfallLayout, indexPath: IndexPath) -> CGFloat {
return indexPath.item % 2 == 0 ? kScreenWidth * 2 / 3 : kScreenWidth * 0.5
}
}
| mit | 3f5775c63fc5eb6c2c61fb2ed1bf39f0 | 33.157303 | 122 | 0.694408 | 5.16129 | false | false | false | false |
gegeburu3308119/ZCweb | ZCwebo/ZCwebo/Classes/Tools/NET/ZCNeTWorkSessionManager.swift | 1 | 2806 | //
// ZCNeTWorkSessionManager.swift
// ZCwebo
//
// Created by 张葱 on 17/8/11.
// Copyright © 2017年 张葱. All rights reserved.
//
import UIKit
import AFNetworking
enum ZCHttpMethod{
case GET
case POST
}
class ZCNeTWorkSessionManager: AFHTTPSessionManager {
static let shared: ZCNeTWorkSessionManager = {
let instance = ZCNeTWorkSessionManager()
instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
return instance
}()
/// 封装 AFN 的 GET / POST 请求
/// 封装 AFN 的 GET / POST 请求
///
/// - parameter method: GET / POST
/// - parameter URLString: URLString
/// - parameter parameters: 参数字典
/// - parameter completion: 完成回调[json(字典/数组), 是否成功]
func request (method : ZCHttpMethod = .GET , URLString : String,parameters:[String: AnyObject]?,completion : @escaping (_ json : Any? , _ isSUccess : Bool) -> ()){
let success = {(task : URLSessionDataTask?,json: Any?) ->() in
completion(json as AnyObject,true)
}
let failure = {(task : URLSessionDataTask?,error : Error) -> () in
completion("\(error.localizedDescription)",false)
}
if method == .GET {
get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
}else{
post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
}
}
}
//调用接口们
extension ZCNeTWorkSessionManager{
//list
func requestTodayFireVoice(key : String, URLString : String,completion : @escaping (_ json : Any? , _ isSUccess : Bool) -> ()){
let url = kBaseUrl + "mobile/discovery/v2/rankingList/track"
let params = ["device": "iPhone",
"key": key,
"pageId": "1",
"pageSize": "30"]
request(method: .GET, URLString: url, parameters: params as [String : AnyObject]?, completion: completion)
}
// 顶部标题栏
func requestTodayFireItem(key: String ,URString : String ,completion : @escaping (_ json : Any? , _ isSUccess : Bool) -> ()){
let url = kBaseUrl + "mobile/discovery/v2/rankingList/track"
let params = ["device": "iPhone",
"key": "ranking:track:scoreByTime:1:0",
"pageId": "1",
"pageSize": "0"]
request(method: .GET, URLString: url, parameters: params as [String : AnyObject]?, completion: completion)
}
}
| apache-2.0 | 76fee88e922c1f6382e29fff7f558a58 | 23.079646 | 167 | 0.545388 | 4.381643 | false | false | false | false |
myandy/shi_ios | shishi/UI/Main/PoetryScrollView.swift | 1 | 1626 | //
// PoetryScrollView.swift
// shishi
//
// Created by tb on 2017/8/6.
// Copyright © 2017年 andymao. All rights reserved.
//
import UIKit
//主页视图封装,暂时未使用到
class PoetryScrollView: UIView {
var contentText: String? {
get {
return self.poetryView.contentLabel.text
}
set {
self.poetryView.contentLabel.text = contentText
}
}
internal lazy var poetryScrollView: UIScrollView = {
let poetryScrollView = UIScrollView()
return poetryScrollView
}()
internal lazy var poetryView: SharePoetryView = {
let poetryContainerView = SharePoetryView(frame: CGRect.zero)
return poetryContainerView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupSubviews() {
self.addSubview(self.poetryScrollView)
self.poetryScrollView.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.centerX.equalToSuperview()
make.width.equalToSuperview()
make.height.equalTo(self.poetryScrollView.snp.width)
}
self.poetryScrollView.addSubview(self.poetryView)
self.poetryView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
make.width.equalToSuperview()
make.height.greaterThanOrEqualToSuperview()
}
}
}
| apache-2.0 | 440a29019dcd4d852fbc8f639d98d656 | 24.758065 | 69 | 0.612398 | 4.460894 | false | false | false | false |
JensRavens/Interstellar | Sources/Interstellar/ObserverToken.swift | 1 | 1716 | // Copyright (c) 2015 Jens Ravens (http://jensravens.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/// Observer tokens are created by observables to hande unsubscription. You are not supposed to create them directly.
public final class ObserverToken: Hashable {
private weak var observable: Unsubscribable?
public let hashValue: Int
internal init (observable: Unsubscribable, hashValue: Int) {
self.observable = observable
self.hashValue = hashValue
}
public func unsubscribe() {
observable?.unsubscribe(self)
}
}
public func ==(lhs: ObserverToken, rhs: ObserverToken) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | 42a03040133fa1b80ea3af2bfd2056c9 | 44.157895 | 117 | 0.741841 | 4.637838 | false | false | false | false |
erikmartens/NearbyWeather | NearbyWeather/Routing/Weather List Flow/WeatherListFlow.swift | 1 | 8888 | //
// ListFlow.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 19.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import RxSwift
import RxFlow
import Swinject
// MARK: - Dependencies
extension WeatherListFlow {
struct Dependencies {
let dependencyContainer: Container
}
}
// MARK: - Class Definition
final class WeatherListFlow: Flow {
// MARK: - Assets
var root: Presentable {
rootViewController
}
private lazy var rootViewController = Factory.NavigationController.make(fromType: .standardTabbed(
tabTitle: R.string.localizable.tab_weatherList(),
systemImageName: "text.justify"
))
// MARK: - Properties
let dependencies: Dependencies
// MARK: - Initialization
init(dependencies: Dependencies) {
self.dependencies = dependencies
}
deinit {
printDebugMessage(
domain: String(describing: self),
message: "was deinitialized",
type: .info
)
}
// MARK: - Functions
func navigate(to step: Step) -> FlowContributors { // swiftlint:disable:this cyclomatic_complexity
guard let step = transform(step: step) as? WeatherListStep else {
return .none
}
switch step {
case .list:
return summonWeatherListController()
case .emptyList:
return summonEmptyWeatherListController()
case .loadingList:
return summonLoadingListController()
case let .weatherDetails(identity):
return summonWeatherDetailsController(identity: identity)
case .changeListTypeAlert:
return .none // will be handled via `func adapt(step:)`
case let .changeListTypeAlertAdapted(selectionDelegate, currentSelectedOptionValue):
return summonChangeListTypeAlert(selectionDelegate: selectionDelegate, currentSelectedOptionValue: currentSelectedOptionValue)
case .changeAmountOfResultsAlert:
return .none // will be handled via `func adapt(step:)`
case let .changeAmountOfResultsAlertAdapted(selectionDelegate, currentSelectedOptionValue):
return summonChangeAmountOfResultsAlert(selectionDelegate: selectionDelegate, currentSelectedOptionValue: currentSelectedOptionValue)
case .changeSortingOrientationAlert:
return .none // will be handled via `func adapt(step:)`
case let .changeSortingOrientationAlertAdapted(selectionDelegate, currentSelectedOptionValue):
return summonChangeSortingOrientationAlert(selectionDelegate: selectionDelegate, currentSelectedOptionValue: currentSelectedOptionValue)
case .dismiss:
return dismissPresentedViewController()
case .pop:
return popPushedViewController()
}
}
func adapt(step: Step) -> Single<Step> {
guard let step = step as? WeatherListStep else {
return .just(step)
}
switch step {
case let .changeListTypeAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(PreferencesService.self)!.createGetListTypeOptionObservable().map { $0.value }.take(1),
resultSelector: WeatherListStep.changeListTypeAlertAdapted
)
.take(1)
.asSingle()
case let .changeAmountOfResultsAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(PreferencesService.self)!.createGetAmountOfNearbyResultsOptionObservable().map { $0.value }.take(1),
resultSelector: WeatherListStep.changeAmountOfResultsAlertAdapted
)
.take(1)
.asSingle()
case let .changeSortingOrientationAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(PreferencesService.self)!.createGetSortingOrientationOptionObservable().map { $0.value }.take(1),
resultSelector: WeatherListStep.changeSortingOrientationAlertAdapted
)
.take(1)
.asSingle()
default:
return .just(step)
}
}
private func transform(step: Step) -> Step? {
if let weatherDetailStep = step as? WeatherStationMeteorologyDetailsStep {
switch weatherDetailStep {
case .weatherStationMeteorologyDetails:
return nil
case .end:
return WeatherListStep.dismiss
}
}
return step
}
}
// MARK: - Summoning Functions
private extension WeatherListFlow {
func summonWeatherListController() -> FlowContributors {
let weatherListViewController = WeatherListViewController(dependencies: WeatherListViewController.ViewModel.Dependencies(
weatherInformationService: dependencies.dependencyContainer.resolve(WeatherInformationService.self)!,
weatherStationService: dependencies.dependencyContainer.resolve(WeatherStationService.self)!,
userLocationService: dependencies.dependencyContainer.resolve(UserLocationService.self)!,
preferencesService: dependencies.dependencyContainer.resolve(PreferencesService.self)!,
apiKeyService: dependencies.dependencyContainer.resolve(ApiKeyService.self)!
))
rootViewController.setViewControllers([weatherListViewController], animated: false)
return .one(flowContributor: .contribute(
withNextPresentable: weatherListViewController,
withNextStepper: weatherListViewController.viewModel,
allowStepWhenNotPresented: true
))
}
func summonEmptyWeatherListController() -> FlowContributors {
let listErrorViewController = WeatherListErrorViewController(dependencies: WeatherListErrorViewController.ViewModel.Dependencies(
apiKeyService: dependencies.dependencyContainer.resolve(ApiKeyService.self)!,
weatherInformationService: dependencies.dependencyContainer.resolve(WeatherInformationService.self)!,
networkReachabilityService: dependencies.dependencyContainer.resolve(NetworkReachabilityService.self)!
))
rootViewController.setViewControllers([listErrorViewController], animated: false)
return .none
}
func summonLoadingListController() -> FlowContributors {
let loadingViewController = LoadingViewController(dependencies: LoadingViewController.ViewModel.Dependencies(title: R.string.localizable.tab_weatherList()))
rootViewController.setViewControllers([loadingViewController], animated: false)
return .none
}
func summonWeatherDetailsController(identity: PersistencyModelIdentity) -> FlowContributors {
let weatherDetailFlow = WeatherStationMeteorologyDetailsFlow(dependencies: WeatherStationMeteorologyDetailsFlow.Dependencies(
flowPresentationStyle: .pushed(navigationController: rootViewController),
endingStep: WeatherListStep.pop,
weatherInformationIdentity: identity,
dependencyContainer: dependencies.dependencyContainer
))
let weatherDetailStepper = WeatherStationMeteorologyDetailsStepper()
return .one(flowContributor: .contribute(withNextPresentable: weatherDetailFlow, withNextStepper: weatherDetailStepper))
}
func summonChangeListTypeAlert(selectionDelegate: ListTypeSelectionAlertDelegate, currentSelectedOptionValue: ListTypeOptionValue) -> FlowContributors {
let alert = ListTypeSelectionAlert(dependencies: ListTypeSelectionAlert.Dependencies(
selectionDelegate: selectionDelegate,
selectedOptionValue: currentSelectedOptionValue
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func summonChangeAmountOfResultsAlert(selectionDelegate: AmountOfResultsSelectionAlertDelegate, currentSelectedOptionValue: AmountOfResultsOptionValue) -> FlowContributors {
let alert = AmountOfNearbyResultsSelectionAlert(dependencies: AmountOfNearbyResultsSelectionAlert.Dependencies(
selectionDelegate: selectionDelegate,
selectedOptionValue: currentSelectedOptionValue
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func summonChangeSortingOrientationAlert(selectionDelegate: SortingOrientationSelectionAlertDelegate, currentSelectedOptionValue: SortingOrientationOptionValue) -> FlowContributors {
let alert = SortingOrientationSelectionAlert(dependencies: SortingOrientationSelectionAlert.Dependencies(
selectionDelegate: selectionDelegate,
selectedOptionValue: currentSelectedOptionValue
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func dismissPresentedViewController() -> FlowContributors {
rootViewController.presentedViewController?.dismiss(animated: true, completion: nil)
return .none
}
func popPushedViewController() -> FlowContributors {
rootViewController.popViewController(animated: true)
return .none
}
}
| mit | c7d423f2069f859134d94a4e746cb48b | 39.031532 | 184 | 0.762237 | 5.280452 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Extensions/CGRect-Extensions.swift | 1 | 806 | //
// CGRect-Extensions.swift
// Habitica
//
// Created by Phillip on 11.08.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import Foundation
extension CGRect {
func replaceWidth(newValue: CGFloat) -> CGRect {
var rect = self
rect.size.width = newValue
return rect
}
func replaceHeight(newValue: CGFloat) -> CGRect {
var rect = self
rect.size.height = newValue
return rect
}
func replaceX(newValue: CGFloat) -> CGRect {
var rect = self
rect.origin.x = newValue
return rect
}
func replaceY(newValue: CGFloat) -> CGRect {
var rect = self
rect.origin.y = newValue
return rect
}
var totalHeight: CGFloat {
return origin.y + size.height
}
}
| gpl-3.0 | a931e04fa4dfbb4ad53cd0d56bbf1937 | 21.361111 | 55 | 0.590062 | 4.192708 | false | false | false | false |
practicalswift/swift | benchmark/single-source/DictionaryCompactMapValues.swift | 21 | 1726 | //===--- DictionaryCompactMapValues.swift ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
let size = 100
let oddNumbers = stride(from: 1, to: size, by: 2)
let smallOddNumMap: [Int: Int?] =
Dictionary(uniqueKeysWithValues: zip(oddNumbers, oddNumbers))
let compactOddNums: [Int: Int] =
Dictionary(uniqueKeysWithValues: zip(oddNumbers, oddNumbers))
let oddStringMap: [Int: String] = Dictionary(uniqueKeysWithValues:
(1...size).lazy.map { ($0, $0 % 2 == 0 ? "dummy" : "\($0)") })
let t: [BenchmarkCategory] = [.validation, .api, .Dictionary]
public let DictionaryCompactMapValues = [
BenchmarkInfo(name: "DictionaryCompactMapValuesOfNilValue",
runFunction: compactMapValues, tags: t,
setUpFunction: { blackHole(smallOddNumMap); blackHole(compactOddNums)},
legacyFactor: 50),
BenchmarkInfo(name: "DictionaryCompactMapValuesOfCastValue",
runFunction: compactMapValuesInt, tags: t,
setUpFunction: { blackHole(oddStringMap); blackHole(compactOddNums)},
legacyFactor: 54),
]
func compactMapValues(N: Int) {
for _ in 1...20*N {
CheckResults(smallOddNumMap.compactMapValues({$0}) == compactOddNums)
}
}
func compactMapValuesInt(N: Int) {
for _ in 1...20*N {
CheckResults(oddStringMap.compactMapValues(Int.init) == compactOddNums)
}
}
| apache-2.0 | 1895b3a36461a69b3b8feb9c89e67b29 | 35.723404 | 80 | 0.676709 | 4.013953 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Controllers/Settings/Models/ProfileEditConfigurator.swift | 1 | 1550 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import UIKit
final class ProfileEditConfigurator {
private var item: ProfileEditItem = ProfileEditItem(.none)
init(item: ProfileEditItem) {
self.item = item
}
func configure(cell: InputCell) {
cell.selectionStyle = .none
cell.titleLabel.text = item.titleText
cell.textField.text = item.detailText
cell.switchControl.isOn = item.switchMode
cell.switchControl.isHidden = (item.type != ProfileEditItemType.visibility)
cell.textField.isHidden = (item.type == ProfileEditItemType.visibility)
cell.textField.autocapitalizationType = item.type.autocapitalizationType
cell.updater = self
}
}
extension ProfileEditConfigurator: InputCellUpdater {
func inputDidUpdate(_ detailText: String?, _ switchMode: Bool) {
item.update(detailText, switchMode)
}
}
| gpl-3.0 | 39f90537afc30470d450dbd7d60957d5 | 33.444444 | 83 | 0.718065 | 4.403409 | false | true | false | false |
roop/GiveAndTake | Take/Take/TextEditorViewController.swift | 1 | 6087 | //
// TextEditController.swift
// Take
//
// Created by Roopesh Chander on 18/07/14.
// Copyright (c) 2014 Roopesh Chander. All rights reserved.
//
import UIKit
class TextEditorViewController: UIViewController {
weak var _documentsManager: DocumentsManager?
var _document: TextDocument? {
didSet {
if (self._view != nil) {
if let document = self._document {
if (!(self._view!.text as NSString).isEqualToString(document.textContents)) {
self._view!.text = document.textContents
}
} else {
self._view!.text = ""
}
}
}
}
var _isDownloadingDocument: Bool = false
var _title: NSMutableString = ""
var _view: UITextView?
// Create a text editor to create a new document
init(documentsManager: DocumentsManager) {
super.init(nibName: nil, bundle: nil)
_documentsManager = documentsManager
}
// Create a text editor to open an existing document
init(documentURL: NSURL) {
super.init(nibName: nil, bundle: nil)
let urlMetaData = documentURL.promisedItemResourceValuesForKeys(
[ NSURLIsUbiquitousItemKey,
NSURLUbiquitousItemDownloadingStatusKey
], error: nil)
let ubiquityStatus = DocumentUbiquityStatus(urlMetaData: urlMetaData)
if (ubiquityStatus.documentIsUbiquitous && !ubiquityStatus.documentIsUpToDate) {
_isDownloadingDocument = true
NSFileManager.defaultManager().startDownloadingUbiquitousItemAtURL(documentURL, error: nil)
}
if let document = TextDocument(fileURL: documentURL) {
document.openWithCompletionHandler( { (success: Bool) in
if (success) {
self._isDownloadingDocument = false
self._view?.editable = true
self._document = document
document.editorDelegate = self
var title = document.localizedName
self._title = title.mutableCopy() as NSMutableString
self.navigationItem.title = title
}
})
}
}
required init(coder: NSCoder) {
// Explicitly disallow initing from an archive
fatalError("Object of type TextEditorViewController cannot be initialized with an NSCoder")
}
override func loadView() {
self.navigationItem.title = (_isDownloadingDocument ? "Downloading ..." : "Untitled")
_view = {
let v = UITextView()
v.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
v.delegate = self
if (self._document != nil) {
v.text = self._document!.textContents
} else {
v.text = ""
}
return v
}()
if (_isDownloadingDocument) {
_view?.editable = false
}
self.view = _view! as UIView
}
}
extension TextEditorViewController: UITextViewDelegate {
func textView(textView: UITextView!, shouldChangeTextInRange range: NSRange,
replacementText text: String!) -> Bool {
// If we've already created the document, nothing to do for now
if let document = self._document {
document.textContents.replaceCharactersInRange(range, withString: text)
document.updateChangeCount(.Done)
return true
}
var isDocumentTitleFinalized = false
// If we've not created the document yet, and if the edit
// involves the first line, update our figured-out title
if (range.location <= _title.length) {
var replacementText: NSString = text as NSString
var posOfLF = replacementText.rangeOfString("\n").location
if (posOfLF != NSNotFound) {
replacementText = replacementText.substringToIndex(posOfLF)
isDocumentTitleFinalized = true
}
_title.replaceCharactersInRange(range, withString: replacementText)
self.navigationItem.title = _title.length > 0 ? _title : "Untitled"
} else {
isDocumentTitleFinalized = true
}
// Once the user types past the first line,
// create the document
if (isDocumentTitleFinalized) {
let textContents = (textView.text as NSString).stringByReplacingCharactersInRange(
range, withString: text)
_documentsManager?.createDocument(name: _title,
textContents: textContents,
completionHandler: { (document: TextDocument?) in
if (document != nil && self._document == nil) {
self._document = document
println("Created")
}
})
}
return true
}
}
extension TextEditorViewController: TextDocumentEditorDelegate {
func disableEditing() {
if let view = _view {
view.editable = false
}
}
func enableEditing() {
if let view = _view {
view.editable = true
}
}
}
extension TextEditorViewController {
override func viewWillDisappear(animated: Bool) {
if (self._document == nil) {
if (_title.length > 0) {
_documentsManager?.createDocument(name: _title,
textContents: _title,
completionHandler: nil)
}
return
}
self._document!.closeWithCompletionHandler({ success in
if (success) {
println("Saved and closed")
} else {
println("Error while saving/closing")
}
})
}
} | mit | d0bfae03d55e63adbb3daa4a55b29c2b | 34.811765 | 103 | 0.547889 | 5.454301 | false | false | false | false |
boyXiong/XWSwiftRefresh | XWSwiftRefresh/Footer/XWRefreshAutoStateFooter.swift | 2 | 2065 | //
// XWRefreshAutoStateFooter.swift
// XWSwiftRefresh
//
// Created by Xiong Wei on 15/10/6.
// Copyright © 2015年 Xiong Wei. All rights reserved.
// 简书:猫爪
import UIKit
/** footerView 只有状态文字 */
public class XWRefreshAutoStateFooter: XWRefreshAutoFooter {
//MARK: 外部
/** 显示刷新状态的label */
lazy var stateLabel:UILabel = {
[unowned self] in
let lable = UILabel().Lable()
self.addSubview(lable)
return lable
}()
/** 隐藏刷新状态的文字 */
public var refreshingTitleHidden:Bool = false
/** 设置状态的显示文字 */
public func setTitle(title:String, state:XWRefreshState){
self.stateLabel.text = self.stateTitles[self.state];
}
//MARK: 私有的
/** 每个状态对应的文字 */
private var stateTitles:Dictionary<XWRefreshState, String> = [
XWRefreshState.Idle : XWRefreshFooterStateIdleText,
XWRefreshState.Refreshing : XWRefreshFooterStateRefreshingText,
XWRefreshState.NoMoreData : XWRefreshFooterStateNoMoreDataText
]
override func prepare() {
super.prepare()
self.stateLabel.userInteractionEnabled = true
self.stateLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(XWRefreshAutoStateFooter.stateLabelClick)))
self.stateLabel.text = self.stateTitles[state]
}
func stateLabelClick(){
if self.state == XWRefreshState.Idle {
self.beginRefreshing()
}
}
override func placeSubvies() {
super.placeSubvies()
self.stateLabel.frame = self.bounds
}
override var state:XWRefreshState {
didSet{
if oldValue == state { return }
if self.refreshingTitleHidden && state == XWRefreshState.Refreshing {
self.stateLabel.text = nil
}else {
self.stateLabel.text = self.stateTitles[state]
}
}
}
}
| mit | 82ed46852dbc4c736112b8b135cc93a2 | 25.513514 | 143 | 0.618247 | 4.649289 | false | false | false | false |
sarfraz-akhtar01/SPCalendar | SPCalendar/Classes/CVCalendarView.swift | 1 | 13002 | //
// CVCalendarView.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public typealias WeekView = CVCalendarWeekView
public typealias CalendarView = CVCalendarView
public typealias MonthView = CVCalendarMonthView
public typealias Manager = CVCalendarManager
public typealias DayView = CVCalendarDayView
public typealias ContentController = CVCalendarContentViewController
public typealias Appearance = CVCalendarViewAppearance
public typealias Coordinator = CVCalendarDayViewControlCoordinator
public typealias CalendarMode = CVCalendarViewPresentationMode
public typealias Weekday = CVCalendarWeekday
public typealias Animator = CVCalendarViewAnimator
public typealias Delegate = CVCalendarViewDelegate
public typealias AppearanceDelegate = CVCalendarViewAppearanceDelegate
public typealias AnimatorDelegate = CVCalendarViewAnimatorDelegate
public typealias ContentViewController = CVCalendarContentViewController
public typealias MonthContentViewController = CVCalendarMonthContentViewController
public typealias WeekContentViewController = CVCalendarWeekContentViewController
public typealias MenuViewDelegate = CVCalendarMenuViewDelegate
public typealias TouchController = CVCalendarTouchController
public typealias SelectionType = CVSelectionType
public final class CVCalendarView: UIView {
// MARK: - Public properties
public var manager: Manager!
public var appearance: Appearance!
public var touchController: TouchController!
public var coordinator: Coordinator!
public var animator: Animator!
public var contentController: ContentViewController!
public var calendarMode: CalendarMode!
public var (weekViewSize, dayViewSize): (CGSize?, CGSize?)
fileprivate var validated = false
fileprivate var currentOrientation: UIDeviceOrientation
fileprivate var maxHeight: CGFloat = 0
public var selectedDate: Date {
get {
if let delegate = delegate, let currentDate: Date = delegate.calendarSelectedDate() {
return currentDate
}
else {
return Date()
}
}
}
public var firstWeekday: Weekday {
if let delegate = delegate {
return delegate.firstWeekday()
} else {
return .sunday
}
}
public var shouldShowWeekdaysOut: Bool! {
if let delegate = delegate, let shouldShow = delegate.shouldShowWeekdaysOut?() {
return shouldShow
} else {
return false
}
}
public var presentedDate: CVDate! {
didSet {
let calendar = self.delegate?.calendar?() ?? Calendar.current
if oldValue != nil && presentedDate.convertedDate(calendar: calendar) != oldValue.convertedDate(calendar: calendar) {
delegate?.presentedDateUpdated?(presentedDate)
}
}
}
public var shouldAnimateResizing: Bool {
if let delegate = delegate, let should = delegate.shouldAnimateResizing?() {
return should
}
return true
}
public var shouldAutoSelectDayOnMonthChange: Bool {
if let delegate = delegate, let should = delegate.shouldAutoSelectDayOnMonthChange?() {
return should
}
return true
}
public var shouldAutoSelectDayOnWeekChange: Bool {
if let delegate = delegate, let should = delegate.shouldAutoSelectDayOnWeekChange?() {
return should
}
return true
}
public var shouldScrollOnOutDayViewSelection: Bool {
if let delegate = delegate, let should = delegate.shouldScrollOnOutDayViewSelection?() {
return should
}
return true
}
public var shouldSelectRange: Bool {
get {
if let delegate = delegate, let should = delegate.shouldSelectRange?() {
return should
}
return false
}
}
public var disableScrollingBeyondDate: Date? {
get {
if let delegate = delegate, let date = delegate.disableScrollingBeforeDate?() {
return date
}
return nil
}
}
public var maxSelectableRange: Int {
get {
if let delegate = delegate, let range = delegate.maxSelectableRange?() {
return range
}
return 0
}
}
public var earliestSelectableDate: Date? {
get {
if let delegate = delegate, let date = delegate.earliestSelectableDate?() {
return date
}
return nil
}
}
public var latestSelectableDate: Date? {
get {
if let delegate = delegate, let date = delegate.latestSelectableDate?() {
return date
}
return nil
}
}
// MARK: - Calendar View Delegate
@IBOutlet public weak var calendarDelegate: AnyObject? {
set {
if let calendarDelegate = newValue as? Delegate {
delegate = calendarDelegate
}
}
get {
return delegate
}
}
public weak var delegate: CVCalendarViewDelegate? {
didSet {
if manager == nil {
manager = Manager(calendarView: self)
}
if appearance == nil {
appearance = Appearance()
}
if touchController == nil {
touchController = TouchController(calendarView: self)
}
if coordinator == nil {
coordinator = Coordinator(calendarView: self)
}
if animator == nil {
animator = Animator(calendarView: self)
}
if calendarMode == nil {
loadCalendarMode()
}
}
}
// MARK: - Calendar Appearance Delegate
@IBOutlet public weak var calendarAppearanceDelegate: AnyObject? {
set {
if let calendarAppearanceDelegate = newValue as? AppearanceDelegate {
if appearance == nil {
appearance = Appearance()
}
appearance.delegate = calendarAppearanceDelegate
}
}
get {
return appearance
}
}
// MARK: - Calendar Animator Delegate
@IBOutlet public weak var animatorDelegate: AnyObject? {
set {
if let animatorDelegate = newValue as? AnimatorDelegate {
animator.delegate = animatorDelegate
}
}
get {
return animator
}
}
// MARK: - Initialization
public init() {
currentOrientation = UIDevice.current.orientation
super.init(frame: CGRect.zero)
isHidden = true
}
public override init(frame: CGRect) {
currentOrientation = UIDevice.current.orientation
super.init(frame: frame)
isHidden = true
}
// IB Initialization
public required init?(coder aDecoder: NSCoder) {
currentOrientation = UIDevice.current.orientation
super.init(coder: aDecoder)
isHidden = true
}
}
// MARK: - Frames update
extension CVCalendarView {
public func commitCalendarViewUpdate() {
if currentOrientation != UIDevice.current.orientation {
validated = false
currentOrientation = UIDevice.current.orientation
}
setNeedsLayout()
layoutIfNeeded()
if let _ = delegate, let contentController = contentController {
let contentViewSize = contentController.bounds.size
let selfSize = bounds.size
let screenSize = UIScreen.main.bounds.size
let allowed = selfSize.width <= screenSize.width && selfSize.height <= screenSize.height
if !validated && allowed {
let width = selfSize.width
let height: CGFloat
let countOfWeeks = CGFloat(6)
let vSpace = appearance.spaceBetweenWeekViews!
let hSpace = appearance.spaceBetweenDayViews!
if selfSize.height > maxHeight {
maxHeight = selfSize.height
}
if let mode = calendarMode {
switch mode {
case .weekView:
height = contentViewSize.height
contentController.updateHeight(height, animated: false)
case .monthView :
height = (maxHeight / countOfWeeks) - (vSpace * countOfWeeks)
}
// If no height constraint found we set it manually.
var found = false
for constraint in constraints {
if constraint.firstAttribute == .height {
found = true
}
}
if !found {
addConstraint(NSLayoutConstraint(item: self, attribute: .height,
relatedBy: .equal, toItem: nil, attribute: .height,
multiplier: 1, constant: frame.height))
}
weekViewSize = CGSize(width: width, height: height)
dayViewSize = CGSize(width: (width / 7.0) - hSpace, height: height)
validated = true
contentController
.updateFrames(selfSize != contentViewSize ? bounds : CGRect.zero)
}
}
}
}
}
// MARK: - Coordinator callback
extension CVCalendarView {
public func didSelectDayView(_ dayView: CVCalendarDayView) {
if let controller = contentController {
presentedDate = dayView.date
delegate?.didSelectDayView?(dayView, animationDidFinish: false)
controller.performedDayViewSelection(dayView) // TODO: Update to range selection
}
}
}
// MARK: - Convenience API
extension CVCalendarView {
public func changeDaysOutShowingState(_ shouldShow: Bool) {
contentController.updateDayViews(shouldShow)
}
public func toggleViewWithDate(_ date: Foundation.Date) {
contentController.togglePresentedDate(date)
}
public func toggleCurrentDayView() {
contentController.togglePresentedDate(Foundation.Date())
}
public func loadNextView() {
contentController.presentNextView(nil)
}
public func loadPreviousView() {
contentController.presentPreviousView(nil)
}
public func changeMode(_ mode: CalendarMode, completion: @escaping () -> () = {}) {
let calendar = self.delegate?.calendar?() ?? Calendar.current
guard let selectedDate = coordinator.selectedDayView?.date.convertedDate(calendar: calendar) ,
calendarMode != mode else {
return
}
calendarMode = mode
let newController: ContentController
switch mode {
case .weekView:
contentController.updateHeight(dayViewSize!.height, animated: true)
newController = WeekContentViewController(calendarView: self, frame: bounds, presentedDate: selectedDate)
case .monthView:
contentController.updateHeight(
contentController.presentedMonthView.potentialSize.height, animated: true)
newController = MonthContentViewController(calendarView: self, frame: bounds, presentedDate: selectedDate)
}
newController.updateFrames(bounds)
newController.scrollView.alpha = 0
addSubview(newController.scrollView)
UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions(), animations: { [weak self] in
self?.contentController.scrollView.alpha = 0
newController.scrollView.alpha = 1
}) { [weak self] _ in
self?.contentController.scrollView.removeAllSubviews()
self?.contentController.scrollView.removeFromSuperview()
self?.contentController = newController
completion()
}
}
}
// MARK: - Mode load
private extension CVCalendarView {
func loadCalendarMode() {
if let delegate = delegate {
calendarMode = delegate.presentationMode()
switch delegate.presentationMode() {
case .monthView:
contentController =
MonthContentViewController(calendarView: self, frame: bounds)
case .weekView:
contentController =
WeekContentViewController(calendarView: self, frame: bounds)
}
addSubview(contentController.scrollView)
}
}
}
| mit | e39a1920362c2b938037b37cec6eec5b | 30.712195 | 129 | 0.598139 | 5.91807 | false | false | false | false |
carloscorreia94/AEISTMobileIOS | AEISTMobile/SwiftyJSON.swift | 1 | 35429 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
///Error domain
public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int! = 999
public let ErrorIndexOutOfBounds: Int! = 900
public let ErrorWrongType: Int! = 901
public let ErrorNotExist: Int! = 500
// MARK: - JSON Type
/**
JSON's type definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
self.init(object)
} catch let error1 as NSError {
error.memory = error1
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/// Private object
private var _object: AnyObject = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError?
/// Object in JSON
public var object: AnyObject {
get {
return _object
}
set {
_object = newValue
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
case let string as NSString:
_type = .String
case let null as NSNull:
_type = .Null
case let array as [AnyObject]:
_type = .Array
case let dictionary as [String : AnyObject]:
_type = .Dictionary
default:
_type = .Unknown
_object = NSNull()
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
public static var nullJSON: JSON { get { return JSON(NSNull()) } }
}
// MARK: - SequenceType
extension JSON: SequenceType{
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
var isEmpty: Bool {
get {
switch self.type {
case .Array:
return (self.object as! [AnyObject]).isEmpty
case .Dictionary:
return (self.object as! [String : AnyObject]).isEmpty
default:
return false
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
get {
switch self.type {
case .Array:
return self.arrayValue.count
case .Dictionary:
return self.dictionaryValue.count
default:
return 0
}
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary, otherwise return a generator over empty.
- returns: Return a *generator* over the elements of this *sequence*.
*/
public func generate() -> AnyGenerator<(String, JSON)> {
switch self.type {
case .Array:
let array_ = object as! [AnyObject]
var generate_ = array_.generate()
var index_: Int = 0
return anyGenerator {
if let element_: AnyObject = generate_.next() {
return ("\(index_++)", JSON(element_))
} else {
return nil
}
}
case .Dictionary:
let dictionary_ = object as! [String : AnyObject]
var generate_ = dictionary_.generate()
return anyGenerator {
if let (key_, value_): (String, AnyObject) = generate_.next() {
return (key_, JSON(value_))
} else {
return nil
}
}
default:
return anyGenerator {
return nil
}
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public protocol SubscriptType {}
extension Int: SubscriptType {}
extension String: SubscriptType {}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
if self.type != .Array {
var errorResult_ = JSON.nullJSON
errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return errorResult_
}
let array_ = self.object as! [AnyObject]
if index >= 0 && index < array_.count {
return JSON(array_[index])
}
var errorResult_ = JSON.nullJSON
errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return errorResult_
}
set {
if self.type == .Array {
var array_ = self.object as! [AnyObject]
if array_.count > index {
array_[index] = newValue.object
self.object = array_
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
var returnJSON = JSON.nullJSON
if self.type == .Dictionary {
if let object_: AnyObject = self.object[key] {
returnJSON = JSON(object_)
} else {
returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return returnJSON
}
set {
if self.type == .Dictionary {
var dictionary_ = self.object as! [String : AnyObject]
dictionary_[key] = newValue.object
self.object = dictionary_
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: SubscriptType) -> JSON {
get {
if sub is String {
return self[key:sub as! String]
} else {
return self[index:sub as! Int]
}
}
set {
if sub is String {
self[key:sub as! String] = newValue
} else {
self[index:sub as! Int] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [SubscriptType]) -> JSON {
get {
if path.count == 0 {
return JSON.nullJSON
}
var next = self
for sub in path {
next = next[sub:sub]
}
return next
}
set {
switch path.count {
case 0: return
case 1: self[sub:path[0]] = newValue
default:
var last = newValue
var newPath = path
newPath.removeLast()
for sub in Array(path.reverse()) {
var previousLast = self[newPath]
previousLast[sub:sub] = last
last = previousLast
if newPath.count <= 1 {
break
}
newPath.removeLast()
}
self[sub:newPath[0]] = last
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: SubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
var dictionary_ = [String : AnyObject]()
for (key_, value) in elements {
dictionary_[key_] = value
}
self.init(dictionary_)
}
}
extension JSON: ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
do {
let data = try self.rawData(options: opt)
return NSString(data: data, encoding: encoding) as String?
} catch _ {
return nil
}
case .String:
return (self.object as! String)
case .Number:
return (self.object as! NSNumber).stringValue
case .Bool:
return (self.object as! Bool).description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return (self.object as! [AnyObject]).map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.object as? [AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableArray(array: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] {
var result = [Key: NewValue](minimumCapacity:source.count)
for (key,value) in source {
result[key] = transform(value)
}
return result
}
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
get {
if self.type == .Dictionary {
return _map(self.object as! [String : AnyObject]){ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
get {
return self.dictionary ?? [:]
}
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.object as? [String : AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.object.boolValue
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSNumber(bool: newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSString(string:newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .String:
return self.object as! String
case .Number:
return self.object.stringValue
case .Bool:
return (self.object as! Bool).description
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.object as? NSNumber
default:
return nil
}
}
set {
self.object = newValue?.copy() ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let scanner = NSScanner(string: self.object as! String)
if scanner.scanDouble(nil){
if (scanner.atEnd) {
return NSNumber(double:(self.object as! NSString).doubleValue)
}
}
return NSNumber(double: 0.0)
case .Number, .Bool:
return self.object as! NSNumber
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue.copy()
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return NSNull()
default:
return nil
}
}
set {
self.object = NSNull()
}
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if newValue != nil {
self.object = NSNumber(double: newValue!)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if newValue != nil {
self.object = NSNumber(float: newValue!)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if newValue != nil {
self.object = NSNumber(integer: newValue!)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if newValue != nil {
self.object = NSNumber(char: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedChar: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if newValue != nil {
self.object = NSNumber(short: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedShort: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if newValue != nil {
self.object = NSNumber(int: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedInt: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if newValue != nil {
self.object = NSNumber(longLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLongLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON: Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) == (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) == (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) <= (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) >= (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as! NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) > (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) > (rhs.object as! String)
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) < (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) < (rhs.object as! String)
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber: Comparable {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(rhs == rhs)
}
public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
}
//MARK:- Unavailable
@available(*, unavailable, renamed="JSON")
public typealias JSONValue = JSON
extension JSON {
@available(*, unavailable, message="use 'init(_ object:AnyObject)' instead")
public init(object: AnyObject) {
self = JSON(object)
}
@available(*, unavailable, renamed="dictionaryObject")
public var dictionaryObjects: [String : AnyObject]? {
get { return self.dictionaryObject }
}
@available(*, unavailable, renamed="arrayObject")
public var arrayObjects: [AnyObject]? {
get { return self.arrayObject }
}
@available(*, unavailable, renamed="int8")
public var char: Int8? {
get {
return self.number?.charValue
}
}
@available(*, unavailable, renamed="int8Value")
public var charValue: Int8 {
get {
return self.numberValue.charValue
}
}
@available(*, unavailable, renamed="uInt8")
public var unsignedChar: UInt8? {
get{
return self.number?.unsignedCharValue
}
}
@available(*, unavailable, renamed="uInt8Value")
public var unsignedCharValue: UInt8 {
get{
return self.numberValue.unsignedCharValue
}
}
@available(*, unavailable, renamed="int16")
public var short: Int16? {
get{
return self.number?.shortValue
}
}
@available(*, unavailable, renamed="int16Value")
public var shortValue: Int16 {
get{
return self.numberValue.shortValue
}
}
@available(*, unavailable, renamed="uInt16")
public var unsignedShort: UInt16? {
get{
return self.number?.unsignedShortValue
}
}
@available(*, unavailable, renamed="uInt16Value")
public var unsignedShortValue: UInt16 {
get{
return self.numberValue.unsignedShortValue
}
}
@available(*, unavailable, renamed="int")
public var long: Int? {
get{
return self.number?.longValue
}
}
@available(*, unavailable, renamed="intValue")
public var longValue: Int {
get{
return self.numberValue.longValue
}
}
@available(*, unavailable, renamed="uInt")
public var unsignedLong: UInt? {
get{
return self.number?.unsignedLongValue
}
}
@available(*, unavailable, renamed="uIntValue")
public var unsignedLongValue: UInt {
get{
return self.numberValue.unsignedLongValue
}
}
@available(*, unavailable, renamed="int64")
public var longLong: Int64? {
get{
return self.number?.longLongValue
}
}
@available(*, unavailable, renamed="int64Value")
public var longLongValue: Int64 {
get{
return self.numberValue.longLongValue
}
}
@available(*, unavailable, renamed="uInt64")
public var unsignedLongLong: UInt64? {
get{
return self.number?.unsignedLongLongValue
}
}
@available(*, unavailable, renamed="uInt64Value")
public var unsignedLongLongValue: UInt64 {
get{
return self.numberValue.unsignedLongLongValue
}
}
@available(*, unavailable, renamed="int")
public var integer: Int? {
get {
return self.number?.integerValue
}
}
@available(*, unavailable, renamed="intValue")
public var integerValue: Int {
get {
return self.numberValue.integerValue
}
}
@available(*, unavailable, renamed="uInt")
public var unsignedInteger: Int? {
get {
return self.number?.unsignedIntegerValue
}
}
@available(*, unavailable, renamed="uIntValue")
public var unsignedIntegerValue: Int {
get {
return self.numberValue.unsignedIntegerValue
}
}
}
| gpl-2.0 | c6ce609a2ca29692989555813fbad43e | 25.479073 | 264 | 0.526941 | 4.725127 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/ALCameraViewController/ALCameraViewController/Utilities/SingleImageSaver.swift | 8 | 2533 | //
// SingleImageSavingInteractor.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2016/02/16.
// Copyright © 2016 zero. All rights reserved.
//
import UIKit
import Photos
public typealias SingleImageSaverSuccess = (PHAsset) -> Void
public typealias SingleImageSaverFailure = (NSError) -> Void
public class SingleImageSaver {
private let errorDomain = "com.zero.singleImageSaver"
private var success: SingleImageSaverSuccess?
private var failure: SingleImageSaverFailure?
private var image: UIImage?
public init() { }
public func onSuccess(_ success: @escaping SingleImageSaverSuccess) -> Self {
self.success = success
return self
}
public func onFailure(_ failure: @escaping SingleImageSaverFailure) -> Self {
self.failure = failure
return self
}
public func setImage(_ image: UIImage) -> Self {
self.image = image
return self
}
public func save() -> Self {
_ = PhotoLibraryAuthorizer { error in
if error == nil {
self._save()
} else {
self.failure?(error!)
}
}
return self
}
private func _save() {
guard let image = image else {
self.invokeFailure()
return
}
var assetIdentifier: PHObjectPlaceholder?
PHPhotoLibrary.shared()
.performChanges({
let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
assetIdentifier = request.placeholderForCreatedAsset
}) { finished, error in
guard let assetIdentifier = assetIdentifier, finished else {
self.invokeFailure()
return
}
self.fetch(assetIdentifier)
}
}
private func fetch(_ assetIdentifier: PHObjectPlaceholder) {
let assets = PHAsset.fetchAssets(withLocalIdentifiers: [assetIdentifier.localIdentifier], options: nil)
DispatchQueue.main.async {
guard let asset = assets.firstObject else {
self.invokeFailure()
return
}
self.success?(asset)
}
}
private func invokeFailure() {
let error = errorWithKey("error.cant-fetch-photo", domain: errorDomain)
failure?(error)
}
}
| mit | 5f2a5829f7b71cc32d2b0f08e430d115 | 25.93617 | 111 | 0.565956 | 5.480519 | false | false | false | false |
data-licious/ceddl4swift | ceddl4swift/ceddl4swift/BaseItem.swift | 1 | 3071 | //
// BaseItem.swift
// ceddl4swift
//
// Created by Sachin Vas on 20/10/16.
// Copyright © 2016 Sachin Vas. All rights reserved.
//
import Foundation
open class BaseItem<T>: NSObject {
private var items: Dictionary<String, AnyObject> = [:]
//JSON id - security
private var security: Security!
private var previousField: String!
/// Returns the current Object.
/// - Returns: current object
internal func returnSelf() -> T {
return self as! T
}
internal func getMap() -> Dictionary<String, AnyObject> {
var returnDict = items
if security != nil {
returnDict["security"] = security.getMap() as AnyObject
}
return returnDict
}
internal func addItem(_ field: String, value: AnyObject) {
items[field] = value
previousField = field
}
/// Add the provided security access categories to the previous Object.
///
/// This method will throw an IllegalStateException when a previous Object is not available.
///
/// - Parameter accessCategories: Array of strings
/// - Returns: current object
///
/// The following example adds security to `{page.pageInfo.pageName}`
///
/// DigitalData.create()
/// .page()
/// .pageInfo()
/// .pageName("Nikon SLR Camera")
/// .security("Analytics", "Personalization")
open func security(_ accessCategories: Array<String>) throws -> T {
if previousField == nil {
throw DigitalDataError.illegalStateException("No field found to secure - Call addSecurity directly after setting a field to secure it.")
}
if security == nil {
security = Security()
}
security.addSecurity(previousField, accessCategories: accessCategories)
return returnSelf()
}
/// Add the Default security category to the previous Object.
///
/// This method will throw an IllegalStateException when a previous Object is not available.
///
/// - Returns: current object
///
/// The following example adds security to `{page.pageInfo.pageName}`
///
/// DigitalData.create()
/// .page()
/// .pageInfo()
/// .pageName("Nikon SLR Camera")
/// .defaultSecurity()
open func defaultSecurity() throws -> T {
if previousField == nil {
throw DigitalDataError.illegalStateException("No field found to secure - Call addDefaultSecurity directly after setting a field to secure it.")
}
if security == nil {
security = Security()
}
security.addSecurity(previousField, accessCategories: [DigitalData.DEFAULT_SECURITY])
return returnSelf()
}
/// Add a custom property.
/// - Parameter name: custom property name
/// - Parameter value: custom property value
/// - Returns: current object
open func custom(_ name: String, value: AnyObject) -> T {
addItem(name, value: value)
return returnSelf()
}
}
| bsd-3-clause | 9ba7d6b1c363b3c13da294d144911df2 | 29.7 | 155 | 0.610098 | 4.665653 | false | false | false | false |
mudithsilva/SwiftySideMenu | SwiftySideMenu/SwiftySideMenuImageView.swift | 1 | 3325 | //
// SwiftySideMenuImageView.swift
// navigationTest
//
// Created by Mudith Chathuranga on 5/30/17.
// Copyright © 2017 Mudith Chathuranga. All rights reserved.
//
import UIKit
public class SwiftySideMenuImageView: UIView {
@IBOutlet weak var menuButtonImage: UIImageView!
@IBAction func openMenu(_ sender: UIButton) {
SwiftySideMenuInfo.shared.swiftySideMenu.menuButtonClicked()
}
override public func layoutSubviews() {
super.layoutSubviews()
let podBundle = Bundle(for: SwiftySideMenuImageView.self)
self.menuButtonImage.image = UIImage(named: "menuButton", in: podBundle, compatibleWith: nil)
self.backgroundColor = UIColor.clear
}
public class func getMenuImageView() -> SwiftySideMenuImageView {
let podBundle = Bundle(for: SwiftySideMenuImageView.self)
if let bundleURL = podBundle.url(forResource: "SwiftySideMenu", withExtension: "bundle") {
if let bundle = Bundle(url: bundleURL) {
return UINib(nibName: "SwiftySideMenuImageView", bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
} else {
return UINib(nibName: "SwiftySideMenuImageView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
}
} else {
return UINib(nibName: "SwiftySideMenuImageView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
}
// return UINib(nibName: "SwiftySideMenuImageView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
}
public class func addMenuImageView(addMenuViewTo parentView: UIView) {
let podBundle = Bundle(for: SwiftySideMenuImageView.self)
if let bundleURL = podBundle.url(forResource: "SwiftySideMenu", withExtension: "bundle") {
if let bundle = Bundle(url: bundleURL) {
let childView = UINib(nibName: "SwiftySideMenuImageView", bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
childView.frame = parentView.bounds
parentView.addSubview(childView)
} else {
let childView = UINib(nibName: "SwiftySideMenuImageView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
childView.frame = parentView.bounds
parentView.addSubview(childView)
}
} else {
let childView = UINib(nibName: "SwiftySideMenuImageView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
childView.frame = parentView.bounds
parentView.addSubview(childView)
}
// let childView = UINib(nibName: "SwiftySideMenuImageView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SwiftySideMenuImageView
// childView.frame = parentView.bounds
// parentView.addSubview(childView)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| mit | 6dbaa4a65b86ef93e894c4802dcb62b9 | 45.166667 | 162 | 0.664862 | 4.762178 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Profile/ProfileViewController.swift | 1 | 58394 | //
// ProfileViewController.swift
// Yep
//
// Created by NIX on 15/3/16.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import SafariServices
import CoreLocation
import RealmSwift
import YepNetworking
import YepKit
import OpenGraph
import MonkeyKing
import Navi
import Kingfisher
import Proposer
let profileAvatarAspectRatio: CGFloat = 12.0 / 16.0
final class ProfileViewController: SegueViewController {
private var socialAccount: SocialAccount?
enum FromType {
case None
case OneToOneConversation
case GroupConversation
}
var fromType: FromType = .None
var oAuthCompleteAction: (() -> Void)?
var afterOAuthAction: ((socialAccount: SocialAccount) -> Void)?
var profileUser: ProfileUser?
var profileUserIsMe = true {
didSet {
if !profileUserIsMe {
if fromType == .OneToOneConversation {
sayHiView.hidden = true
} else {
sayHiView.tapAction = { [weak self] in
self?.sayHi()
}
profileCollectionView.contentInset.bottom = sayHiView.bounds.height
}
} else {
sayHiView.hidden = true
let settingsBarButtonItem = UIBarButtonItem(image: UIImage.yep_iconSettings, style: .Plain, target: self, action: #selector(ProfileViewController.showSettings(_:)))
customNavigationItem.rightBarButtonItem = settingsBarButtonItem
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProfileViewController.createdFeed(_:)), name: YepConfig.Notification.createdFeed, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProfileViewController.deletedFeed(_:)), name: YepConfig.Notification.deletedFeed, object: nil)
}
}
}
private var numberOfItemsInSectionBlog: Int {
if profileUserIsMe {
return 1
} else {
if let _ = profileUser?.blogURL {
return 1
} else {
return 0
}
}
}
private var numberOfItemsInSectionSocialAccount: Int {
return (profileUser?.providersCount ?? 0)
}
private var needSeparationLine: Bool {
return (numberOfItemsInSectionBlog > 0) || (numberOfItemsInSectionSocialAccount > 0)
}
private var insetForSectionBlog: UIEdgeInsets {
if numberOfItemsInSectionBlog > 0 {
if numberOfItemsInSectionSocialAccount > 0 {
return UIEdgeInsets(top: 30, left: 0, bottom: 0, right: 0)
} else {
return UIEdgeInsets(top: 30, left: 0, bottom: 40, right: 0)
}
} else {
return UIEdgeInsetsZero
}
}
private var insetForSectionSocialAccount: UIEdgeInsets {
if numberOfItemsInSectionBlog > 0 {
if numberOfItemsInSectionSocialAccount > 0 {
return UIEdgeInsets(top: 10, left: 0, bottom: 30, right: 0)
} else {
return UIEdgeInsetsZero
}
} else {
if numberOfItemsInSectionSocialAccount > 0 {
return UIEdgeInsets(top: 30, left: 0, bottom: 30, right: 0)
} else {
return UIEdgeInsetsZero
}
}
}
private lazy var shareView: ShareProfileView = {
let share = ShareProfileView(frame: CGRect(x: 0, y: 0, width: 120, height: 120))
share.alpha = 0
self.view.addSubview(share)
return share
}()
#if DEBUG
private lazy var profileFPSLabel: FPSLabel = {
let label = FPSLabel()
return label
}()
#endif
private var statusBarShouldLight = false
private var noNeedToChangeStatusBar = false
@IBOutlet private weak var topShadowImageView: UIImageView!
@IBOutlet weak var profileCollectionView: UICollectionView! {
didSet {
profileCollectionView.registerNibOf(SkillCell)
profileCollectionView.registerNibOf(ProfileHeaderCell)
profileCollectionView.registerNibOf(ProfileFooterCell)
profileCollectionView.registerNibOf(ProfileSeparationLineCell)
profileCollectionView.registerNibOf(ProfileSocialAccountCell)
profileCollectionView.registerNibOf(ProfileSocialAccountBlogCell)
profileCollectionView.registerNibOf(ProfileSocialAccountImagesCell)
profileCollectionView.registerNibOf(ProfileSocialAccountGithubCell)
profileCollectionView.registerNibOf(ProfileFeedsCell)
profileCollectionView.registerHeaderNibOf(ProfileSectionHeaderReusableView)
profileCollectionView.registerFooterClassOf(UICollectionReusableView)
profileCollectionView.alwaysBounceVertical = true
}
}
@IBOutlet private weak var sayHiView: BottomButtonView!
private lazy var customNavigationItem: UINavigationItem = UINavigationItem(title: "Details")
private lazy var customNavigationBar: UINavigationBar = {
let bar = UINavigationBar(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 64))
bar.tintColor = UIColor.whiteColor()
bar.tintAdjustmentMode = .Normal
bar.alpha = 0
bar.setItems([self.customNavigationItem], animated: false)
bar.backgroundColor = UIColor.clearColor()
bar.translucent = true
bar.shadowImage = UIImage()
bar.barStyle = UIBarStyle.BlackTranslucent
bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
let textAttributes = [
NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont.navigationBarTitleFont()
]
bar.titleTextAttributes = textAttributes
return bar
}()
private lazy var collectionViewWidth: CGFloat = {
return CGRectGetWidth(self.profileCollectionView.bounds)
}()
private lazy var sectionLeftEdgeInset: CGFloat = { return YepConfig.Profile.leftEdgeInset }()
private lazy var sectionRightEdgeInset: CGFloat = { return YepConfig.Profile.rightEdgeInset }()
private lazy var sectionBottomEdgeInset: CGFloat = { return 0 }()
private lazy var introductionText: String = {
var introduction: String?
if let profileUser = self.profileUser {
switch profileUser {
case .DiscoveredUserType(let discoveredUser):
if let _introduction = discoveredUser.introduction {
if !_introduction.isEmpty {
introduction = _introduction
}
}
case .UserType(let user):
if !user.introduction.isEmpty {
introduction = user.introduction
}
if user.friendState == UserFriendState.Me.rawValue {
YepUserDefaults.introduction.bindListener(self.listener.introduction) { [weak self] introduction in
SafeDispatch.async {
self?.introductionText = introduction ?? NSLocalizedString("No Introduction yet.", comment: "")
self?.updateProfileCollectionView()
}
}
}
}
}
return introduction ?? NSLocalizedString("No Introduction yet.", comment: "")
}()
private var masterSkills = [Skill]()
private var learningSkills = [Skill]()
private func updateMyMasterSkills() {
guard let profileUser = profileUser where profileUser.isMe else {
return
}
guard let realm = try? Realm() else {
return
}
if let me = meInRealm(realm) {
let _ = try? realm.write {
me.masterSkills.removeAll()
let userSkills = userSkillsFromSkills(self.masterSkills, inRealm: realm)
me.masterSkills.appendContentsOf(userSkills)
}
}
}
private func updateMyLearningSkills() {
guard let profileUser = profileUser where profileUser.isMe else {
return
}
guard let realm = try? Realm() else {
return
}
if let me = meInRealm(realm) {
let _ = try? realm.write {
me.learningSkills.removeAll()
let userSkills = userSkillsFromSkills(self.learningSkills, inRealm: realm)
me.learningSkills.appendContentsOf(userSkills)
}
}
}
private var dribbbleWork: DribbbleWork?
private var instagramWork: InstagramWork?
private var githubWork: GithubWork?
private var feeds: [DiscoveredFeed]?
private var feedAttachments: [DiscoveredAttachment?]?
private let skillTextAttributes = [NSFontAttributeName: UIFont.skillTextFont()]
private var footerCellHeight: CGFloat {
let attributes = [
NSFontAttributeName: YepConfig.Profile.introductionFont
]
let labelWidth = self.collectionViewWidth - (YepConfig.Profile.leftEdgeInset + YepConfig.Profile.rightEdgeInset)
let rect = self.introductionText.boundingRectWithSize(CGSize(width: labelWidth, height: CGFloat(FLT_MAX)), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes:attributes, context:nil)
return 10 + 24 + 4 + 18 + 10 + ceil(rect.height) + 6
}
private struct Listener {
let nickname: String
let introduction: String
let avatar: String
let blog: String
}
private lazy var listener: Listener = {
let suffix = NSUUID().UUIDString
return Listener(
nickname: "Profile.Title" + suffix,
introduction: "Profile.introductionText" + suffix,
avatar: "Profile.Avatar" + suffix,
blog: "Profile.Blog" + suffix
)
}()
// MARK: Life cycle
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
YepUserDefaults.nickname.removeListenerWithName(listener.nickname)
YepUserDefaults.introduction.removeListenerWithName(listener.introduction)
YepUserDefaults.avatarURLString.removeListenerWithName(listener.avatar)
YepUserDefaults.blogURLString.removeListenerWithName(listener.blog)
profileCollectionView?.delegate = nil
println("deinit Profile")
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
if statusBarShouldLight {
return UIStatusBarStyle.LightContent
} else {
return UIStatusBarStyle.Default
}
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Profile", comment: "")
view.addSubview(customNavigationBar)
automaticallyAdjustsScrollViewInsets = false
Kingfisher.ImageCache(name: "default").calculateDiskCacheSizeWithCompletionHandler({ (size) -> () in
let cacheSize = Double(size)/1000000
println(String(format: "Kingfisher.ImageCache cacheSize: %.2f MB", cacheSize))
if cacheSize > 300 {
Kingfisher.ImageCache.defaultCache.clearDiskCache()
}
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProfileViewController.cleanForLogout(_:)), name: EditProfileViewController.Notification.Logout, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProfileViewController.handleOAuthResult(_:)), name: YepConfig.Notification.OAuthResult, object: nil)
if let profileUser = profileUser {
// 如果是 DiscoveredUser,也可能是好友或已存储的陌生人,查询本地 User 替换
switch profileUser {
case .DiscoveredUserType(let discoveredUser):
guard let realm = try? Realm() else {
break
}
if let user = userWithUserID(discoveredUser.id, inRealm: realm) {
self.profileUser = ProfileUser.UserType(user)
masterSkills = skillsFromUserSkillList(user.masterSkills)
learningSkills = skillsFromUserSkillList(user.learningSkills)
updateProfileCollectionView()
}
default:
break
}
if let realm = try? Realm() {
if let user = userWithUserID(profileUser.userID, inRealm: realm) {
if user.friendState == UserFriendState.Normal.rawValue {
sayHiView.title = String.trans_titleChat
}
}
}
} else {
// 为空的话就要显示自己
syncMyInfoAndDoFurtherAction {
// 提示没有 Skills
guard let me = me() else {
return
}
if me.masterSkills.count == 0 && me.learningSkills.count == 0 {
YepAlert.confirmOrCancel(title: NSLocalizedString("Notice", comment: ""), message: NSLocalizedString("You don't have any skills!\nWould you like to pick some?", comment: ""), confirmTitle: NSLocalizedString("OK", comment: ""), cancelTitle: NSLocalizedString("Not now", comment: ""), inViewController: self, withConfirmAction: { [weak self] in
self?.pickSkills()
}, cancelAction: {})
}
}
if let me = me() {
profileUser = ProfileUser.UserType(me)
masterSkills = skillsFromUserSkillList(me.masterSkills)
learningSkills = skillsFromUserSkillList(me.learningSkills)
updateProfileCollectionView()
}
}
profileUserIsMe = profileUser?.isMe ?? false
if let profileLayout = profileCollectionView.collectionViewLayout as? ProfileLayout {
profileLayout.scrollUpAction = { [weak self] progress in
if let strongSelf = self {
let indexPath = NSIndexPath(forItem: 0, inSection: Section.Header.rawValue)
if let coverCell = strongSelf.profileCollectionView.cellForItemAtIndexPath(indexPath) as? ProfileHeaderCell {
let beginChangePercentage: CGFloat = 1 - 64 / strongSelf.collectionViewWidth * profileAvatarAspectRatio
let normalizedProgressForChange: CGFloat = (progress - beginChangePercentage) / (1 - beginChangePercentage)
coverCell.avatarBlurImageView.alpha = progress < beginChangePercentage ? 0 : normalizedProgressForChange
let shadowAlpha = 1 - normalizedProgressForChange
if shadowAlpha < 0.2 {
strongSelf.topShadowImageView.alpha = progress < beginChangePercentage ? 1 : 0.2
} else {
strongSelf.topShadowImageView.alpha = progress < beginChangePercentage ? 1 : shadowAlpha
}
coverCell.locationLabel.alpha = progress < 0.5 ? 1 : 1 - min(1, (progress - 0.5) * 2 * 2) // 特别对待,在后半程的前半段即完成 alpha -> 0
}
}
}
}
//Make sure when pan edge screen collectionview not scroll
if let gestures = navigationController?.view.gestureRecognizers {
for recognizer in gestures {
if recognizer.isKindOfClass(UIScreenEdgePanGestureRecognizer) {
profileCollectionView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer as! UIScreenEdgePanGestureRecognizer)
println("Require UIScreenEdgePanGestureRecognizer to failed")
break
}
}
}
if let tabBarController = tabBarController {
profileCollectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: CGRectGetHeight(tabBarController.tabBar.bounds), right: 0)
}
if let profileUser = profileUser {
switch profileUser {
case .DiscoveredUserType(let discoveredUser):
customNavigationItem.title = discoveredUser.nickname
case .UserType(let user):
customNavigationItem.title = user.nickname
if user.friendState == UserFriendState.Me.rawValue {
YepUserDefaults.nickname.bindListener(listener.nickname) { [weak self] nickname in
SafeDispatch.async {
self?.customNavigationItem.title = nickname
self?.updateProfileCollectionView()
}
}
YepUserDefaults.avatarURLString.bindListener(listener.avatar) { [weak self] avatarURLString in
SafeDispatch.async {
let indexPath = NSIndexPath(forItem: 0, inSection: Section.Header.rawValue)
if let cell = self?.profileCollectionView.cellForItemAtIndexPath(indexPath) as? ProfileHeaderCell {
if let avatarURLString = avatarURLString {
cell.blurredAvatarImage = nil // need reblur
cell.updateAvatarWithAvatarURLString(avatarURLString)
}
}
}
}
YepUserDefaults.blogURLString.bindListener(listener.blog, action: { [weak self] _ in
self?.updateProfileCollectionView()
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProfileViewController.updateUIForUsername(_:)), name: EditProfileViewController.Notification.NewUsername, object: nil)
}
}
if !profileUserIsMe {
let userID = profileUser.userID
userInfoOfUserWithUserID(userID, failureHandler: nil, completion: { userInfo in
//println("userInfoOfUserWithUserID \(userInfo)")
// 对非好友来说,必要
SafeDispatch.async { [weak self] in
if let realm = try? Realm() {
let _ = try? realm.write {
updateUserWithUserID(userID, useUserInfo: userInfo, inRealm: realm)
}
}
if let discoveredUser = parseDiscoveredUser(userInfo) {
switch profileUser {
case .DiscoveredUserType:
self?.profileUser = ProfileUser.DiscoveredUserType(discoveredUser)
default:
break
}
}
self?.updateProfileCollectionView()
}
})
}
if profileUserIsMe {
// share my profile button
if customNavigationItem.leftBarButtonItem == nil {
let shareMyProfileButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(ProfileViewController.tryShareMyProfile(_:)))
customNavigationItem.leftBarButtonItem = shareMyProfileButton
}
} else {
// share others' profile button
if let _ = profileUser.username {
let shareOthersProfileButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(ProfileViewController.shareOthersProfile(_:)))
customNavigationItem.rightBarButtonItem = shareOthersProfileButton
}
}
}
if profileUserIsMe {
proposeToAccess(.Location(.WhenInUse), agreed: {
YepLocationService.turnOn()
YepLocationService.sharedManager.afterUpdatedLocationAction = { [weak self] newLocation in
let indexPath = NSIndexPath(forItem: 0, inSection: Section.Footer.rawValue)
if let cell = self?.profileCollectionView.cellForItemAtIndexPath(indexPath) as? ProfileFooterCell {
cell.location = newLocation
}
}
}, rejected: {
println("Yep can NOT get Location. :[\n")
})
}
if profileUserIsMe {
tryUpdateBlogTitle()
remindUserToReview()
}
#if DEBUG
//view.addSubview(profileFPSLabel)
#endif
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: true)
customNavigationBar.alpha = 1.0
statusBarShouldLight = false
if noNeedToChangeStatusBar {
statusBarShouldLight = true
}
self.setNeedsStatusBarAppearanceUpdate()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
statusBarShouldLight = true
self.setNeedsStatusBarAppearanceUpdate()
}
// MARK: Actions
private func tryUpdateBlogTitle() {
guard let blogURLString = YepUserDefaults.blogURLString.value where !blogURLString.isEmpty, let blogURL = NSURL(string: blogURLString)?.yep_validSchemeNetworkURL else {
return
}
titleOfURL(blogURL, failureHandler: nil, completion: { blogTitle in
println("blogTitle: \(blogTitle)")
if YepUserDefaults.blogTitle.value != blogTitle {
let info: JSONDictionary = [
"website_url": blogURLString,
"website_title": blogTitle,
]
updateMyselfWithInfo(info, failureHandler: nil, completion: { success in
SafeDispatch.async {
YepUserDefaults.blogTitle.value = blogTitle
YepUserDefaults.blogURLString.value = blogURLString
}
})
} else {
println("not need update blogTitle")
}
})
}
private func tryShareProfile() {
guard let username = profileUser?.username, profileURL = NSURL(string: "https://\(yepHost)/\(username)"), nickname = profileUser?.nickname else {
return
}
var thumbnail: UIImage?
if let
avatarURLString = profileUser?.avatarURLString,
realm = try? Realm(),
avatar = avatarWithAvatarURLString(avatarURLString, inRealm: realm) {
if let
avatarFileURL = NSFileManager.yepAvatarURLWithName(avatar.avatarFileName),
avatarFilePath = avatarFileURL.path,
image = UIImage(contentsOfFile: avatarFilePath) {
thumbnail = image.navi_centerCropWithSize(CGSize(width: 100, height: 100))
}
}
let info = MonkeyKing.Info(
title: nickname,
description: NSLocalizedString("From Yep, with Skills.", comment: ""),
thumbnail: thumbnail,
media: .URL(profileURL)
)
let sessionMessage = MonkeyKing.Message.WeChat(.Session(info: info))
let weChatSessionActivity = WeChatActivity(
type: .Session,
message: sessionMessage,
finish: { success in
println("share Profile to WeChat Session success: \(success)")
}
)
let timelineMessage = MonkeyKing.Message.WeChat(.Timeline(info: info))
let weChatTimelineActivity = WeChatActivity(
type: .Timeline,
message: timelineMessage,
finish: { success in
println("share Profile to WeChat Timeline success: \(success)")
}
)
let activityViewController = UIActivityViewController(activityItems: ["\(nickname), \(NSLocalizedString("From Yep, with Skills.", comment: "")) \(profileURL)"], applicationActivities: [weChatSessionActivity, weChatTimelineActivity])
activityViewController.excludedActivityTypes = [UIActivityTypeMessage, UIActivityTypeMail]
self.presentViewController(activityViewController, animated: true, completion: nil)
}
@objc private func tryShareMyProfile(sender: AnyObject?) {
if let _ = profileUser?.username {
tryShareProfile()
} else {
YepAlert.textInput(title: String.trans_titleCreateUsername, message: NSLocalizedString("In order to share your profile, create a unique username first.", comment: ""), placeholder: NSLocalizedString("use letters, numbers, and underscore", comment: ""), oldText: nil, confirmTitle: String.trans_titleCreate, cancelTitle: String.trans_cancel, inViewController: self, withConfirmAction: { text in
let newUsername = text
updateMyselfWithInfo(["username": newUsername], failureHandler: { [weak self] reason, errorMessage in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
let message = errorMessage ?? String.trans_promptCreateUsernameFailed
YepAlert.alertSorry(message: message, inViewController: self)
}, completion: { success in
SafeDispatch.async { [weak self] in
guard let realm = try? Realm() else {
return
}
if let me = meInRealm(realm) {
let _ = try? realm.write {
me.username = newUsername
}
}
self?.tryShareProfile()
}
})
}, cancelAction: {
})
}
}
@objc private func shareOthersProfile(sender: AnyObject) {
tryShareProfile()
}
private func pickSkills() {
let vc = UIStoryboard.Scene.registerPickSkills
vc.isRegister = false
vc.masterSkills = self.masterSkills
vc.learningSkills = self.learningSkills
vc.afterChangeSkillsAction = { [weak self] masterSkills, learningSkills in
self?.masterSkills = masterSkills
self?.learningSkills = learningSkills
SafeDispatch.async {
self?.updateMyMasterSkills()
self?.updateMyLearningSkills()
self?.updateProfileCollectionView()
}
}
self.navigationController?.pushViewController(vc, animated: true)
}
@objc private func showSettings(sender: AnyObject) {
self.performSegueWithIdentifier("showSettings", sender: self)
}
func setBackButtonWithTitle() {
let backBarButtonItem = UIBarButtonItem(image: UIImage.yep_iconBack, style: .Plain, target: self, action: #selector(ProfileViewController.back(_:)))
customNavigationItem.leftBarButtonItem = backBarButtonItem
}
@objc private func back(sender: AnyObject) {
if let presentingViewController = presentingViewController {
presentingViewController.dismissViewControllerAnimated(true, completion: nil)
} else {
navigationController?.popViewControllerAnimated(true)
}
}
@objc private func cleanForLogout(sender: NSNotification) {
profileUser = nil
}
@objc private func updateUIForUsername(sender: NSNotification) {
updateProfileCollectionView()
}
private func updateFeedAttachmentsAfterUpdateFeeds() {
feedAttachments = feeds!.map({ feed -> DiscoveredAttachment? in
if let attachment = feed.attachment {
if case let .Images(attachments) = attachment {
return attachments.first
}
}
return nil
})
updateProfileCollectionView()
}
@objc private func createdFeed(sender: NSNotification) {
guard feeds != nil else {
return
}
let feed = (sender.object as! Box<DiscoveredFeed>).value
feeds!.insert(feed, atIndex: 0)
updateFeedAttachmentsAfterUpdateFeeds()
}
@objc private func deletedFeed(sender: NSNotification) {
guard feeds != nil else {
return
}
let feedID = sender.object as! String
var indexOfDeletedFeed: Int?
for (index, feed) in feeds!.enumerate() {
if feed.id == feedID {
indexOfDeletedFeed = index
break
}
}
guard let index = indexOfDeletedFeed else {
return
}
feeds!.removeAtIndex(index)
updateFeedAttachmentsAfterUpdateFeeds()
}
private func updateProfileCollectionView() {
SafeDispatch.async {
self.profileCollectionView.collectionViewLayout.invalidateLayout()
self.profileCollectionView.reloadData()
self.profileCollectionView.layoutIfNeeded()
}
}
private func sayHi() {
if let profileUser = profileUser {
guard let realm = try? Realm() else {
return
}
switch profileUser {
case .DiscoveredUserType(let discoveredUser):
realm.beginWrite()
let conversation = conversationWithDiscoveredUser(discoveredUser, inRealm: realm)
_ = try? realm.commitWrite()
if let conversation = conversation {
performSegueWithIdentifier("showConversation", sender: conversation)
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.changedConversation, object: nil)
}
case .UserType(let user):
if user.friendState != UserFriendState.Me.rawValue {
if user.conversation == nil {
let newConversation = Conversation()
newConversation.type = ConversationType.OneToOne.rawValue
newConversation.withFriend = user
let _ = try? realm.write {
realm.add(newConversation)
}
}
if let conversation = user.conversation {
performSegueWithIdentifier("showConversation", sender: conversation)
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.changedConversation, object: nil)
}
}
}
}
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier else {
return
}
switch identifier {
case "showProfileWithUsername":
let vc = segue.destinationViewController as! ProfileViewController
let profileUser = (sender as! Box<ProfileUser>).value
vc.prepare(withProfileUser: profileUser)
case "showConversation":
let vc = segue.destinationViewController as! ConversationViewController
vc.conversation = sender as! Conversation
case "showFeedsWithSkill":
let vc = segue.destinationViewController as! FeedsViewController
if let
skillInfo = sender as? [String: AnyObject],
skill = skillInfo["skill"] as? SkillCellSkill {
vc.skill = Skill(category: nil, id: skill.ID, name: skill.localName, localName: skill.localName, coverURLString: skill.coverURLString)
}
vc.hidesBottomBarWhenPushed = true
case "showFeedsOfProfileUser":
let vc = segue.destinationViewController as! FeedsViewController
if let
info = (sender as? Box<[String: AnyObject]>)?.value,
profileUser = (info["profileUser"] as? Box<ProfileUser>)?.value,
feeds = (info["feeds"] as? Box<[DiscoveredFeed]>)?.value {
vc.profileUser = profileUser
vc.feeds = feeds
vc.preparedFeedsCount = feeds.count
}
vc.hideRightBarItem = true
vc.hidesBottomBarWhenPushed = true
case "showEditSkills":
if let skillInfo = sender as? [String: AnyObject] {
let vc = segue.destinationViewController as! EditSkillsViewController
if let skillSet = skillInfo["skillSet"] as? Int {
vc.skillSet = SkillSet(rawValue: skillSet)
}
vc.afterChangedSkillsAction = { [weak self] in
self?.updateProfileCollectionView()
}
}
case "showSocialWorkGithub":
if let providerName = sender as? String {
let vc = segue.destinationViewController as! SocialWorkGithubViewController
vc.socialAccount = SocialAccount(rawValue: providerName)
vc.profileUser = profileUser
vc.githubWork = githubWork
vc.afterGetGithubWork = {[weak self] githubWork in
self?.githubWork = githubWork
}
}
case "showSocialWorkDribbble":
if let providerName = sender as? String {
let vc = segue.destinationViewController as! SocialWorkDribbbleViewController
vc.socialAccount = SocialAccount(rawValue: providerName)
vc.profileUser = profileUser
vc.dribbbleWork = dribbbleWork
vc.afterGetDribbbleWork = { [weak self] dribbbleWork in
self?.dribbbleWork = dribbbleWork
}
}
case "showSocialWorkInstagram":
if let providerName = sender as? String {
let vc = segue.destinationViewController as! SocialWorkInstagramViewController
vc.socialAccount = SocialAccount(rawValue: providerName)
vc.profileUser = profileUser
vc.instagramWork = instagramWork
vc.afterGetInstagramWork = { [weak self] instagramWork in
self?.instagramWork = instagramWork
}
}
default:
break
}
}
}
// MARK: UICollectionView
extension ProfileViewController: UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate {
enum Section: Int {
case Header
case Footer
case Master
case Learning
case SeparationLine
case Blog
case SocialAccount
case SeparationLine2
case Feeds
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 9
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let section = Section(rawValue: section) else {
fatalError()
}
switch section {
case .Header:
return 1
case .Master:
return profileUser?.masterSkillsCount ?? 0
case .Learning:
return profileUser?.learningSkillsCount ?? 0
case .Footer:
return 1
case .SeparationLine:
return needSeparationLine ? 1 : 0
case .Blog:
return numberOfItemsInSectionBlog
case .SocialAccount:
return numberOfItemsInSectionSocialAccount
case .SeparationLine2:
return 1
case .Feeds:
return 1
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
guard let section = Section(rawValue: indexPath.section) else {
fatalError()
}
switch section {
case .Header:
let cell: ProfileHeaderCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
if let profileUser = profileUser {
switch profileUser {
case .DiscoveredUserType(let discoveredUser):
cell.configureWithDiscoveredUser(discoveredUser)
case .UserType(let user):
cell.configureWithUser(user)
}
}
cell.updatePrettyColorAction = { [weak self] prettyColor in
self?.customNavigationBar.tintColor = prettyColor
let textAttributes = [
NSForegroundColorAttributeName: prettyColor,
NSFontAttributeName: UIFont.navigationBarTitleFont()
]
self?.customNavigationBar.titleTextAttributes = textAttributes
}
return cell
case .Master:
let cell: SkillCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
cell.skill = profileUser?.cellSkillInSkillSet(.Master, atIndexPath: indexPath)
if cell.skill == nil {
if let profileUser = profileUser {
println("Master profileUser: \(profileUser)")
} else {
println("Master profileUser is nil")
}
}
cell.tapAction = { [weak self] skill in
self?.performSegueWithIdentifier("showFeedsWithSkill", sender: ["skill": skill, "preferedSkillSet": SkillSet.Master.rawValue])
}
return cell
case .Learning:
let cell: SkillCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
cell.skill = profileUser?.cellSkillInSkillSet(.Learning, atIndexPath: indexPath)
if cell.skill == nil {
if let profileUser = profileUser {
println("Learning profileUser: \(profileUser)")
} else {
println("Learning profileUser is nil")
}
}
cell.tapAction = { [weak self] skill in
self?.performSegueWithIdentifier("showFeedsWithSkill", sender: ["skill": skill, "preferedSkillSet": SkillSet.Learning.rawValue])
}
return cell
case .Footer:
let cell: ProfileFooterCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
if let profileUser = profileUser {
cell.configureWithProfileUser(profileUser, introduction: introductionText)
cell.tapUsernameAction = { [weak self] username in
self?.tryShowProfileWithUsername(username)
}
}
return cell
case .SeparationLine:
let cell: ProfileSeparationLineCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
return cell
case .Blog:
let cell: ProfileSocialAccountBlogCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureWithProfileUser(profileUser)
return cell
case .SocialAccount:
let index = indexPath.item
if let providerName = profileUser?.providerNameWithIndex(index), socialAccount = SocialAccount(rawValue: providerName) {
if socialAccount == .Github {
let cell: ProfileSocialAccountGithubCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureWithProfileUser(profileUser, socialAccount: socialAccount, githubWork: githubWork, completion: { githubWork in
self.githubWork = githubWork
})
return cell
} else {
let cell: ProfileSocialAccountImagesCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
cell.socialAccount = socialAccount
var socialWork: SocialWork?
switch socialAccount {
case .Dribbble:
if let dribbbleWork = dribbbleWork {
socialWork = SocialWork.Dribbble(dribbbleWork)
}
case .Instagram:
if let instagramWork = instagramWork {
socialWork = SocialWork.Instagram(instagramWork)
}
default:
break
}
cell.configureWithProfileUser(profileUser, socialAccount: socialAccount, socialWork: socialWork, completion: { socialWork in
switch socialWork {
case .Dribbble(let dribbbleWork):
self.dribbbleWork = dribbbleWork
case .Instagram(let instagramWork):
self.instagramWork = instagramWork
}
})
return cell
}
}
let cell: ProfileSocialAccountCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
return cell
case .SeparationLine2:
let cell: ProfileSeparationLineCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
return cell
case .Feeds:
let cell: ProfileFeedsCell = collectionView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureWithProfileUser(profileUser, feedAttachments: feedAttachments, completion: { [weak self] feeds, feedAttachments in
self?.feeds = feeds
self?.feedAttachments = feedAttachments
})
return cell
}
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let header: ProfileSectionHeaderReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, forIndexPath: indexPath)
guard let section = Section(rawValue: indexPath.section) else {
fatalError()
}
switch section {
case .Master:
header.titleLabel.text = SkillSet.Master.name
case .Learning:
header.titleLabel.text = SkillSet.Learning.name
default:
header.titleLabel.text = ""
}
if profileUserIsMe {
header.tapAction = { [weak self] in
let skillSet: SkillSet
switch section {
case .Master:
skillSet = .Master
case .Learning:
skillSet = .Learning
default:
skillSet = .Master
}
self?.performSegueWithIdentifier("showEditSkills", sender: ["skillSet": skillSet.rawValue])
}
} else {
header.accessoryImageView.hidden = true
}
return header
} else {
let footer: UICollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, forIndexPath: indexPath)
return footer
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
guard let section = Section(rawValue: section) else {
fatalError()
}
switch section {
case .Header:
return UIEdgeInsets(top: 0, left: 0, bottom: sectionBottomEdgeInset, right: 0)
case .Master:
return UIEdgeInsets(top: 0, left: sectionLeftEdgeInset, bottom: 15, right: sectionRightEdgeInset)
case .Learning:
return UIEdgeInsets(top: 0, left: sectionLeftEdgeInset, bottom: sectionBottomEdgeInset, right: sectionRightEdgeInset)
case .Footer:
return UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
case .SeparationLine:
return UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0)
case .Blog:
return insetForSectionBlog
case .SocialAccount:
return insetForSectionSocialAccount
case .SeparationLine2:
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
case .Feeds:
return UIEdgeInsets(top: 30, left: 0, bottom: 30, right: 0)
}
}
func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize {
guard let section = Section(rawValue: indexPath.section) else {
fatalError()
}
switch section {
case .Header:
return CGSize(width: collectionViewWidth, height: collectionViewWidth * profileAvatarAspectRatio)
case .Master:
let skillLocalName = profileUser?.cellSkillInSkillSet(.Master, atIndexPath: indexPath)?.localName ?? ""
let rect = skillLocalName.boundingRectWithSize(CGSize(width: CGFloat(FLT_MAX), height: SkillCell.height), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: skillTextAttributes, context: nil)
return CGSize(width: rect.width + 24, height: SkillCell.height)
case .Learning:
let skillLocalName = profileUser?.cellSkillInSkillSet(.Learning, atIndexPath: indexPath)?.localName ?? ""
let rect = skillLocalName.boundingRectWithSize(CGSize(width: CGFloat(FLT_MAX), height: SkillCell.height), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: skillTextAttributes, context: nil)
return CGSize(width: rect.width + 24, height: SkillCell.height)
case .Footer:
return CGSize(width: collectionViewWidth, height: footerCellHeight)
case .SeparationLine:
return CGSize(width: collectionViewWidth, height: 1)
case .Blog:
return CGSize(width: collectionViewWidth, height: numberOfItemsInSectionBlog > 0 ? 40 : 0)
case .SocialAccount:
return CGSize(width: collectionViewWidth, height: numberOfItemsInSectionSocialAccount > 0 ? 40 : 0)
case .SeparationLine2:
return CGSize(width: collectionViewWidth, height: 1)
case .Feeds:
return CGSize(width: collectionViewWidth, height: 40)
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard let profileUser = profileUser else {
return CGSizeZero
}
guard let section = Section(rawValue: section) else {
fatalError()
}
let normalHeight: CGFloat = 40
if profileUser.isMe {
switch section {
case .Master:
return CGSizeMake(collectionViewWidth, normalHeight)
case .Learning:
return CGSizeMake(collectionViewWidth, normalHeight)
default:
return CGSizeZero
}
} else {
switch section {
case .Master:
let height: CGFloat = (profileUser.masterSkillsCount > 0 && profileUser.userID != YepUserDefaults.userID.value) ? normalHeight : 0
return CGSizeMake(collectionViewWidth, height)
case .Learning:
let height: CGFloat = (profileUser.learningSkillsCount > 0 && profileUser.userID != YepUserDefaults.userID.value) ? normalHeight : 0
return CGSizeMake(collectionViewWidth, height)
default:
return CGSizeZero
}
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSizeZero
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
guard let section = Section(rawValue: indexPath.section) else {
fatalError()
}
switch section {
case .Learning, .Master:
// do in SkillCell's tapAction
break
case .Blog:
guard let profileUser = profileUser else {
break
}
if profileUser.isMe {
if let blogURLString = YepUserDefaults.blogURLString.value where !blogURLString.isEmpty, let blogURL = NSURL(string: blogURLString) {
yep_openURL(blogURL)
} else {
YepAlert.textInput(title: NSLocalizedString("Set Blog", comment: ""), message: NSLocalizedString("Input your blog's URL.", comment: ""), placeholder: "example.com", oldText: nil, confirmTitle: NSLocalizedString("Set", comment: ""), cancelTitle: String.trans_cancel, inViewController: self, withConfirmAction: { text in
let blogURLString = text
if blogURLString.isEmpty {
YepUserDefaults.blogTitle.value = nil
YepUserDefaults.blogURLString.value = nil
return
}
guard let blogURL = NSURL(string: blogURLString)?.yep_validSchemeNetworkURL else {
YepUserDefaults.blogTitle.value = nil
YepUserDefaults.blogURLString.value = nil
YepAlert.alertSorry(message: NSLocalizedString("You have entered an invalid URL!", comment: ""), inViewController: self)
return
}
YepHUD.showActivityIndicator()
titleOfURL(blogURL, failureHandler: { [weak self] reason, errorMessage in
YepHUD.hideActivityIndicator()
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
YepAlert.alertSorry(message: errorMessage ?? NSLocalizedString("Set blog failed!", comment: ""), inViewController: self)
}, completion: { blogTitle in
println("blogTitle: \(blogTitle)")
let info: JSONDictionary = [
"website_url": blogURLString,
"website_title": blogTitle,
]
updateMyselfWithInfo(info, failureHandler: { [weak self] reason, errorMessage in
YepHUD.hideActivityIndicator()
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
YepAlert.alertSorry(message: errorMessage ?? NSLocalizedString("Set blog failed!", comment: ""), inViewController: self)
}, completion: { success in
YepHUD.hideActivityIndicator()
SafeDispatch.async {
YepUserDefaults.blogTitle.value = blogTitle
YepUserDefaults.blogURLString.value = blogURLString
}
})
})
}, cancelAction: {
})
}
} else {
if let blogURL = profileUser.blogURL {
yep_openURL(blogURL)
}
}
case .SocialAccount:
let index = indexPath.item
guard let
profileUser = profileUser,
providerName = profileUser.providerNameWithIndex(index),
socialAccount = SocialAccount(rawValue: providerName) else {
break
}
if profileUser.enabledSocialAccount(socialAccount) {
performSegueWithIdentifier("showSocialWork\(socialAccount.segue)", sender: providerName)
} else {
guard profileUserIsMe else {
break
}
afterOAuthAction = { [weak self] socialAccount in
// 更新自己的 provider enabled 状态
let providerName = socialAccount.rawValue
SafeDispatch.async {
guard let realm = try? Realm() else {
return
}
guard let me = meInRealm(realm) else {
return
}
var haveSocialAccountProvider = false
for socialAccountProvider in me.socialAccountProviders {
if socialAccountProvider.name == providerName {
let _ = try? realm.write {
socialAccountProvider.enabled = true
}
haveSocialAccountProvider = true
break
}
}
// 如果之前没有,这就新建一个
if !haveSocialAccountProvider {
let provider = UserSocialAccountProvider()
provider.name = providerName
provider.enabled = true
let _ = try? realm.write {
me.socialAccountProviders.append(provider)
}
}
self?.updateProfileCollectionView()
// OAuth 成功后,自动跳转去显示对应的 social work
delay(1) {
self?.performSegueWithIdentifier("showSocialWork\(socialAccount.segue)", sender: providerName)
}
}
}
do {
self.socialAccount = SocialAccount(rawValue: providerName)
guard let accessToken = YepUserDefaults.v1AccessToken.value else {
return
}
let safariViewController = SFSafariViewController(URL: NSURL(string: "\(socialAccount.authURL)?_tkn=\(accessToken)")!)
presentViewController(safariViewController, animated: true, completion: nil)
oAuthCompleteAction = {
safariViewController.dismissViewControllerAnimated(true, completion: {
// OAuth 成功后,自动跳转去显示对应的 social work
delay(1) { [weak self] in
self?.performSegueWithIdentifier("showSocialWork\(socialAccount.segue)", sender: providerName)
}
})
}
}
}
case .Feeds:
guard let profileUser = profileUser else {
break
}
let info: [String: AnyObject] = [
"profileUser": Box(profileUser),
"feeds": Box(feeds ?? []),
]
performSegueWithIdentifier("showFeedsOfProfileUser", sender: Box(info))
default:
break
}
}
}
extension ProfileViewController: UIScrollViewDelegate {
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if shareView.progress >= 1.0 {
shareView.shareActionAnimationAndDoFurther({
SafeDispatch.async { [weak self] in
self?.tryShareMyProfile(nil)
}
})
}
}
}
// MARK: - OAuthResult
extension ProfileViewController {
func handleOAuthResult(notification: NSNotification) {
oAuthCompleteAction?()
if let result = notification.object as? NSNumber where result == 1, let socialAccount = self.socialAccount {
socialAccountWithProvider(socialAccount.rawValue, failureHandler: { reason, errorMessage in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
}, completion: { provider in
println("provider: \(provider)")
SafeDispatch.async { [weak self] in
self?.afterOAuthAction?(socialAccount: socialAccount)
}
})
} else {
YepAlert.alertSorry(message: NSLocalizedString("OAuth Error", comment: ""), inViewController: self, withDismissAction: {})
}
}
}
| mit | 174611723f0e1ffc1d132f88ce494ff1 | 34.381995 | 405 | 0.568577 | 6.124237 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Sources/TouchKeyView.swift | 1 | 4183 | //
// TouchKeyView.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import Cocoa
public class TouchKeyView: NSButton {
public var letters = ""
public var number = "1"
public init(numeral: String = "1", text: String = "") {
super.init(frame:
CGRect(x:0, y:0, width:100, height: 100))
letters = text
number = numeral
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func drawRect(rect: CGRect) {
drawKey(text: letters, numeral: number)
}
func drawKey(text text: String = "A B C", numeral: String = "1") {
//// Gradient Declarations
let gradient = NSGradient(startingColor: NSColor.darkGrayColor(), endingColor: NSColor.lightGrayColor())!
//// Rectangle Drawing
let rectanglePath = NSBezierPath(roundedRect: NSMakeRect(0, 0, 100, 100), xRadius: 20, yRadius: 20)
gradient.drawInBezierPath(rectanglePath, angle: -90)
//// Letters Drawing
let lettersRect = NSMakeRect(0, 73, 100, 21)
let lettersStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
lettersStyle.alignment = .Center
let lettersFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 25)!, NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: lettersStyle]
let lettersTextHeight: CGFloat = NSString(string: text).boundingRectWithSize(NSMakeSize(lettersRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: lettersFontAttributes).size.height
let lettersTextRect: NSRect = NSMakeRect(lettersRect.minX, lettersRect.minY + (lettersRect.height - lettersTextHeight) / 2, lettersRect.width, lettersTextHeight)
NSGraphicsContext.saveGraphicsState()
NSRectClip(lettersRect)
NSString(string: text).drawInRect(NSOffsetRect(lettersTextRect, 0, 0), withAttributes: lettersFontAttributes)
NSGraphicsContext.restoreGraphicsState()
//// Number Drawing
let numberRect = NSMakeRect(0, 0, 100, 73)
let numberStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
numberStyle.alignment = .Center
let numberFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 60)!, NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: numberStyle]
let numberTextHeight: CGFloat = NSString(string: numeral).boundingRectWithSize(NSMakeSize(numberRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: numberFontAttributes).size.height
let numberTextRect: NSRect = NSMakeRect(numberRect.minX, numberRect.minY + (numberRect.height - numberTextHeight) / 2, numberRect.width, numberTextHeight)
NSGraphicsContext.saveGraphicsState()
NSRectClip(numberRect)
NSString(string: numeral).drawInRect(NSOffsetRect(numberTextRect, 0, 0), withAttributes: numberFontAttributes)
NSGraphicsContext.restoreGraphicsState()
}
}
extension AKPlaygroundView {
public func addTouchKey(
num: String, text: String, action: Selector) -> TouchKeyView {
let newButton = TouchKeyView(numeral: num, text: text)
// Line up multiple buttons in a row
if let button = lastButton {
newButton.frame.origin.x += button.frame.origin.x + button.frame.width + 10
yPosition -= horizontalSpacing
}
horizontalSpacing = Int((newButton.frame.height)) + 10
yPosition += horizontalSpacing
newButton.frame.origin.y = self.bounds.height - CGFloat(yPosition)
newButton.target = self
newButton.action = action
self.addSubview(newButton)
lastButton = newButton
return newButton
}
}
| apache-2.0 | 8a1fd9b38eb7b2ec56f496e16064067a | 44.467391 | 236 | 0.683959 | 5.255025 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftLearning/SwiftLearning/VC/JWSwiftBaseViewController.swift | 1 | 67193 | //
// JWSwiftBaseViewController.swift
// JSwiftTest
//
// Created by apple on 17/3/7.
// Copyright © 2017年 BP. All rights reserved.
//
import UIKit
// MARK: - 一·结构体
struct Caculator {
func sum(a:Int,b:Int) -> Int {
return a + b
}
@discardableResult
func func1(a:Int,b:Int) ->Int {
return a - b + 1
}
}
// MARK: - 二·协议中的可选方法
@objc protocol MyProtocol {
@objc optional func func1() //old: optional func func1()
func func2()
}
// MARK: - 三·自定义类
// MARK: - 类扩展-------double转str
extension Double {
func format(f: String) -> String {
return NSString(format: "%\(f)f" as NSString,self) as String
}
}
/*
作为一门面向对象语言,类当然是Swift中的一等类型。通过下面的例子让大家对Swift的class有一个简单的印象,在下面的例子中可以看到Swift中的属性、方法(包括构造方法和析构方法)
*/
// MARK: - 例1
//Swift中一个类可以不继承于任何其他基类,那么此类本身就是一个基类
class Person{
//定义属性
var name:String
var height=0.0
//构造器方法,注意如果不编写构造方法默认会自动创建一个无参构造方法
init(name:String){
self.name=name
}
//定义方法
func showMessage(){
print("name=\(name),height=\(height)")
}
//析构方法,在对象被释放时调用,类似于ObjC的dealloc,注意此函数没有括号,没有参数,无法直接调用
deinit{
print("deinit...")
}
}
//调用例1中的Person类
func namePerson(name:String) -> Bool {
var p = Person(name: "Kenhin")
p.height=172.0
p.showMessage() //结果:name=Kenhin,height=172.0
//类是引用类型
var p2 = p
p2.name = "Kaoru"
print(p.name) //结果:Kaoru
if p === p2 { //“===”表示等价于,这里不能使用等于“==”(等于用于比较值相等,p和p2是不同的值,只是指向的对象相同)
print("p===p2") //p等价于p2,二者指向同一个对象
return p === p2
}
return p === p2
}
/*
从上面的例子不难看出:
Swift中的类不必须继承一个基类(但是ObjC通常必须继承于NSObject),如果一个类没有继承于任何其他类则这个类也称为“基类”;
Swift中的属性定义形式类似于其他语句中的成员变量(或称之为“实例变量”),尽管它有着成员变量没有的特性;
Swift中如果开发者没有自己编写构造方法那么默认会提供一个无参数构造方法(否则不会自动生成构造方法);
Swift中的析构方法没有括号和参数,并且不支持自行调用;
*/
// MARK: - 例2
class MyNameClass{
// 从第一个参数就必须指定参数名,除非使用"_"明确指出省略参数
@objc func sum(num1:Int,num2:Int)->Int{
return num1 + num2
}
func func1(){//调用方法
let _ = #selector(sum(num1:num2:))
}
//取消var参数
func increase(a:Int){
var a = a
a += 1
}
//inout参数修饰改放到类型前
func increase( a:inout Int) {
a += 1
}
func otherSelector(){
//取消++、--操作符
var d = 1
d += 1 //d++报错,可以改写成 d += 1 或者 d = d + 1
//取消C风格for循环
for i in 0 ..< 10 {
debugPrint(i)
}
}
//例2调用例1中的Person类
var p = Person(name: "Kenhin")
func namePerson(name:String) -> Bool {
p.height=172.0
p.showMessage() //结果:name=Kenhin,height=172.0
//类是引用类型
var p2 = p
p2.name = "Kaoru"
print(p.name) //结果:Kaoru
if p === p2 { //“===”表示等价于,这里不能使用等于“==”(等于用于比较值相等,p和p2是不同的值,只是指向的对象相同)
print("p===p2") //p等价于p2,二者指向同一个对象
return p === p2
}
return p === p2
}
}
// MARK: - 属性
/*
Swift中的属性分为两种:存储属性(用于类、结构体)和计算属性(用于类、结构体、枚举),并且在Swift中并不强调成员变量的概念。 无论从概念上还是定义方式上来看存储属性更像其他语言中的成员变量,但是不同的是可以控制读写操作、通过属性监视器来属性的变化以及快速实现懒加载功能
*/
class Account {
var balance:Double=0.0
}
class PersonWithProperty {
//firstName、lastName、age是存储属性
var firstName:String
var lastName:String
let age:Int
//fullName是一个计算属性,并且由于只定义了get方法,所以是一个只读属性
var fullName:String{
get{
return firstName + "." + lastName
}
set{
var array = ["hello","world"]
if array.count == 2 {
firstName=array[0]
lastName=array[1]
}
}
//set方法中的newValue表示即将赋的新值,可以自己设置set中的newValue变量,如下:
// set(myValue){
// }
}
//如果fullName只有get则是一个只读属性,只读属性可以简写如下:
// var fullName:String{
// return firstName + "." + lastName
// }
//属性的懒加载,第一次访问才会计算初始值,在Swift中懒加载的属性不一定就是对象类型,也可以是基本类型
lazy var account = Account()
//构造器方法,注意如果不编写构造方法默认会自动创建一个无参构造方法
init(firstName:String,lastName:String,age:Int){
self.firstName=firstName
self.lastName=lastName
self.age=age
}
//定义方法
func showMessage(){
print("name=\(self.fullName)")
}
}
//方法调用
func PersonWithPropertyAction() {
var p=PersonWithProperty(firstName: "Kenshin", lastName: "Cui",age:29)
p.fullName="Kaoru.Sun"
p.account.balance=10
p.showMessage()
}
/*
计算属性并不直接存储一个值,而是提供getter来获取一个值,或者利用setter来间接设置其他属性;
lazy属性必须有初始值,必须是变量不能是常量(因为常量在构造完成之前就已经确定了值);
在构造方法之前存储属性必须有值,无论是变量属性(var修饰)还是常量属性(let修饰)这个值既可以在属性创建时指定也可以在构造方法内指定
上面的例子中不难区分存储属性和计算属性,计算属性通常会有一个setter、getter方法,如果要监视一个计算属性的变化在setter方法中即可办到(因为在setter方法中可以newValue或者自定义参数名),但是如果是存储属性就无法通过监视属性的变化过程了,因为在存储属性中是无法定义setter方法的。不过Swift为我们提供了另外两个方法来监视属性的变化那就是willSet和didSet,通常称之为“属性监视器”或“属性观察器”
*/
class AccountNew {
//注意设置默认值0.0时监视器不会被调用
var balance:Double=0.0{
willSet{
self.balance=2.0
//注意newValue可以使用自定义值,并且在属性监视器内部调用属性不会引起监视器循环调用,注意此时修改balance的值没有用
print("Account.balance willSet,newValue=\(newValue),value=\(self.balance)")
}
didSet{
self.balance=3.0
//注意oldValue可以使用自定义值,并且在属性监视器内部调用属性不会引起监视器循环调用,注意此时修改balance的值将作为最终结果
print("Account.balance didSet,oldValue=\(oldValue),value=\(self.balance)")
}
}
}
class PersonNew {
var firstName:String
var lastName:String
let age:Int
var fullName:String{
get{
return firstName + "." + lastName
}
set{
//对于计算属性可以直接在set方法中进行属性监视
var array = ["hello","world"]
if array.count == 2 {
firstName=array[0]
lastName=array[1]
}
}
}
lazy var account = AccountNew()
init(firstName:String,lastName:String,age:Int){
self.firstName=firstName
self.lastName=lastName
self.age=age
}
//类型属性
static var skin:Array<String>{
return ["yellow","white","black"];
}
}
//方法调用
func PersonNewWithPropertyAction() {
var p=PersonNew(firstName: "Kenshin", lastName: "Cui",age:29)
p.account.balance=1.0
print("p.account.balance=\(p.account.balance)") //结果:p.account.balance=3.0
for color in PersonNew.skin {
print(color)
}
}
/*
和setter方法中的newValue一样,默认情况下载willSet和didSet中会有一个newValue和oldValue参数表示要设置的新值和已经被修改过的旧值(当然参数名同样可以自定义);
存储属性的默认值设置不会引起属性监视器的调用(另外在构造方法中赋值也不会引起属性监视器调用),只有在外部设置存储属性才会引起属性监视器调用;
存储属性的属性监视器willSet、didSet内可以直接访问属性,但是在计算属性的get、set方法中不能直接访问计算属性,否则会引起循环调用;
在didSet中可以修改属性的值,这个值将作为最终值(在willSet中无法修改);
*/
// MARK: - 方法
/*
方法就是与某个特定类关联的函数,其用法和前面介绍的函数并无二致,但是和ObjC相比,ObjC中的函数必须是C语言,而方法则必须是ObjC。此外其他语言中方法通常存在于类中,但是Swift中的方法除了在类中使用还可以在结构体、枚举中使用。关于普通的方法这里不做过多赘述,用法和前面的函数区别也不大,这里主要看一下构造方法
*/
class PersonAction {
//定义属性
var name:String
var height:Double
var age=0
//指定构造器方法,注意如果不编写构造方法默认会自动创建一个无参构造方法
init(name:String,height:Double,age:Int){
self.name=name
self.height=height
self.age=age
}
//便利构造方法,通过调用指定构造方法、提供默认值来简化构造方法实现
convenience init(name:String){
self.init(name:name,height:0.0,age:0)
}
//实例方法
func modifyInfoWithAge(age:Int,height:Double){
self.age=age
self.height=height
}
//类型方法
class func showClassName(){
print("Class name is \"Person\"")
}
//析构方法,在对象被释放时调用,类似于ObjC的dealloc,注意此函数没有括号,没有参数,无法直接调用
deinit{
print("deinit...")
}
}
//通过便利构造方法创建对象
var p=PersonAction(name: "kenshin")
/*
除构造方法、析构方法外的其他方法的参数默认除了第一个参数是局部参数,从第二个参数开始既是局部参数又是外部参数(这种方式和ObjC的调用方式很类似,当然,可以使用“#”将第一个参数同时声明为外部参数名,也可以使用“_”将其他参数设置为非外部参数名)。但是,对于函数,默认情况下只有默认参数既是局部参数又是外部参数,其他参数都是局部参数。
构造方法的所有参数默认情况下既是外部参数又是局部参数;
Swift中的构造方法分为“指定构造方法”和“便利构造方法(convenience)”,指定构造方法是主要的构造方法,负责初始化所有存储属性,而便利构造方法是辅助构造方法,它通过调用指定构造方法并指定默认值的方式来简化多个构造方法的定义,但是在一个类中至少有一个指定构造方法。
*/
// MARK: - 下标脚本
/*
下标脚本是一种访问集合的快捷方式,例如:var a:[string],我们经常使用a[0]、a[1]这种方式访问a中的元素,0和1在这里就是一个索引,通过这种方式访问或者设置集合中的元素在Swift中称之为“下标脚本”(类似于C#中的索引器)。从定义形式上通过“subscript”关键字来定义一个下标脚本,很像方法的定义,但是在实现上通过getter、setter实现读写又类似于属性。假设用Record表示一条记录,其中有多列,下面示例中演示了如何使用下标脚本访问并设置某一列的值
*/
class Record {
//定义属性,假设store是Record内部的存储结构
var store:[String:String]
init(data:[String:String]){
self.store=data
}
//下标脚本(注意也可以实现只有getter的只读下标脚本)
subscript(index:Int)->String{
get{
var key=self.store.keys.sorted()[index]
return self.store[key]!
}
set{
var key=self.store.keys.sorted()[index]
self.store[key]=newValue //newValue参数名可以像属性一样重新自定义
}
}
//下标脚本(重载)
subscript(key:String)->String{
get{
return store[key]!
}
set{
store[key]=newValue
}
}
}
func RecordAction() {
var r=Record(data:["name":"kenshin","sex":"male"])
print("r[0]=\(r[0])") //结果:r[0]=kenshin
r["sex"]="female"
print(r[1]) //结果:female
}
// MARK: - 继承
/*
和ObjC一样,Swift也是单继承的(可以实现多个协议,此时协议放在后面),子类可以调用父类的属性、方法,重写父类的方法,添加属性监视器,甚至可以将只读属性重写成读写属性
*/
class Father {
var firstName:String,lastName:String
var age:Int=0
var fullName:String{
get{
return firstName+" "+lastName
}
}
init(firstName:String,lastName:String){
self.firstName=firstName
self.lastName=lastName
}
func showMessage(){
print("name=\(fullName),age=\(age)")
}
//通过final声明,子类无法重写
final func sayHello(){
print("hello world.")
}
}
class Student: Father {
//重写属性监视器
override var firstName:String{
willSet{
print("oldValue=\(firstName)")
}
didSet{
print("newValue=\(firstName)")
}
}
var score:Double
//子类指定构造方法一定要调用父类构造方法
//并且必须在子类存储属性初始化之后调用父类构造方法
init(firstName:String,lastName:String, score:Double){
self.score=score
super.init(firstName: firstName, lastName: lastName)
}
convenience init(){
self.init(firstName:"",lastName:"",score:0)
}
//将只读属性重写成了可写属性
override var fullName:String{
get{
return super.fullName;
}
set{
let array = ["Jack","Json"]
if array.count == 2 {
firstName=array[0]
lastName=array[1]
}
}
}
//重写方法
override func showMessage() {
print("name=\(fullName),age=\(age),score=\(score)")
}
}
/*
在使用ObjC开发时init构造方法并不安全,首先无法保证init方法只调用一次,其次在init中不能访问属性。但是这些完全依靠文档约定,编译时并不能发现问题,出错检测是被动的。在Swift中构造方法(init)有了更为严格的规定:构造方法执行完之前必须保证所有存储属性都有值。这一点不仅在当前类中必须遵循,在整个继承关系中也必须保证,因此就有了如下的规定:
子类的指定构造方法必须调用父类构造方法,并确保调用发生在子类存储属性初始化之后。而且指定构造方法不能调用同一个类中的其他指定构造方法;
便利构造方法必须调用同一个类中的其他指定构造方法(可以是指定构造方法或者便利构造方法),不能直接调用父类构造方法(用以保证最终以指定构造方法结束);
如果父类仅有一个无参构造方法(不管是否包含便利构造方法),子类的构造方法默认就会自动调用父类的无参构造方法(这种情况下可以不用手动调用);
常量属性必须默认指定初始值或者在当前类的构造方法中初始化,不能在子类构造方法中初始化
*/
// MARK : - 协议
/*
协议是对实例行为的一种约束,和ObjC类似,在Swift中可以定义属性和方法(ObjC中之所以能定义属性是因为@property的本质就是setter、getter方法)。和其他语言不同的是Swift中的协议不仅限于类的实现,它同样可以应用于枚举、结构体(如果只想将一个协议应用于类,可以在定义协议时在后面添加class关键字来限制其应用范围)
*/
protocol Named{
//定义一个实例属性
var name:String { get set }
//定义一个类型属性
static var className:String { get }
//定义构造方法
init(name:String)
//定义一个实例方法
func showName()
//定义一个类型方法
static func showClassName()
}
protocol Scored{
var score:Double { get set }
}
//Person遵循了Named协议
class Person1:Named {
//注意从Named协议中并不知道name是存储属性还是计算属性,这里将其作为存储属性实现
var name:String
var age:Int = 0
static var className:String{
return "Person"
}
//协议中规定的构造方法,必须使用required关键字声明,除非类使用final修饰
required init(name:String){
self.name=name
}
//遵循showName方法
func showName() {
print("name=\(name)")
}
//遵循showClassName方法
static func showClassName() {
print("Class name is \"Person\"")
}
}
//Student继承于Person并且实现了Scored协议
class Student1: Person1,Scored {
var score:Double=0.0
init(name:String, score:Double){
self.score = score
super.init(name: name)
}
//由于上面自定义了构造方法则必须实现协议中规定的构造方法
required init(name: String) {
super.init(name: name)
}
func test(){
print("\(self.name) is testing.")
}
}
func testAction() {
var p=Person1(name: "Kenshin Cui")
p.showName() //结果:name=Kenshin Cui
print("className=\(Person1.className)") //结果:className=Person
Person1.showClassName() //结果:Class name is "Person"
p.age=28
var s:Named=Student1(name: "Kaoru",score:100.0) //尽管这里将s声明为Named类型,但是运行时仍然可以正确的解析(多态),但是注意此时编译器并不知道s有test方法,所以此时调用test()会报错
s.showName()
//在下面的函数中要求参数stu必须实现两个协议
func showMessage(stu:protocol<Named,Scored>){
print("name=\(stu.name),score=\(stu.score)")
}
var s2=Student1(name: "Tom",score:99.0)
showMessage(stu: s2) //结果:name=Tom,age=99.0
//检测协议
let b1 = s is Scored //判断p是否遵循了Scored协议
if b1 {
print("s has score property.")
}
//类型转化
if let s3 = s as? Scored { //如果s转化成了Scored类型则返回实例,否则为nil
print("s3' score is \(s3.score)") //结果:s3' score is 100.0
}
let s4 = s as! Scored //强制转换,如果转化失败则报错
print("s4' score is \(s4.score)") //结果:s4' score is 100.0
}
/*
协议中虽然可以指定属性的读写,但即使协议中规定属性是只读的但在使用时也可以将其实现成可读写的;
Swift的协议中可以约定属性是实例属性还是类型属性、是读写属性还是只读属性,但是不能约束其是存储属性还是计算属性;
协议中的类型属性和类型方法使用static修饰而不是class(尽管对于类的实现中类型属性、类型方法使用class修饰);
协议中约定的方法支持可变参数,但是不支持默认参数;
协议中约定的构造方法,在实现时如果不是final类则必须使用require修饰(以保证子类如果需要自定义构造方法则必须覆盖父类实现的协议构造方法,如果子类不需要自定义构造方法则不必);
一个协议可以继承于另外一个或多个协议,一个类只能继承于一个类但可以实现多个协议;
协议本身就是一种类型,这也体现除了面向对象的多态特征,可以使用多个协议的合成来约束一个实例参数必须实现某几个协议;
*/
// MARK : -扩展
/*
Swift中的扩展就类似于ObjC中的分类(事实上在其他高级语言中更多的称之为扩展而非分类),但是它要比分类强大的多,它不仅可以扩展类还可以扩展协议、枚举、结构体,另外扩展也不局限于扩展方法(实例方法或者类型方法),还可以扩展便利构造方法、计算属性、下标脚本
*/
class Person2 {
var firstName:String,lastName:String
var age:Int=0
var fullName:String{
get{
return firstName+" "+lastName
}
}
init(firstName:String,lastName:String){
self.firstName=firstName
self.lastName=lastName
}
func showMessage(){
print("name=\(fullName),age=\(age)")
}
}
extension Person2{
//只能扩展便利构造方法,不能扩展指定构造方法
convenience init(){
self.init(firstName:"",lastName:"")
}
//只能扩展计算属性,无法扩展存储属性
var personInfo:String{
return "firstName=\(firstName),lastName=\(lastName),age=\(age)";
}
//扩展实例方法
func sayHello(){
print("hello world.")
}
//嵌套类型
enum SkinColor{
case Yellow,White,Black
}
//扩展类型方法
static func skin()->[SkinColor]{
return [.Yellow,.White,.Black]
}
}
func testAction2() {
var p=Person2()
p.firstName="Kenshin"
p.lastName="Cui"
p.age=28
print(p.personInfo) //结果:firstName=Kenshin,lastName=Cui,age=28
p.sayHello() //结果:hello world.
Person2.skin()
}
// MARK : - 枚举和结构体
// MARK : - 结构体
/*
结构体和类是构造复杂数据类型时常用的构造体,在其他高级语言中结构体相比于类要简单的多(在结构体内部仅仅能定义一些简单成员),但是在Swift中结构体和类的关系要紧密的多,这也是为什么将结构体放到后面来说的原因。Swift中的结构体可以定义属性、方法、下标脚本、构造方法,支持扩展,可以实现协议等等,很多类可以实现的功能结构体都能实现,但是结构体和类有着本质区别:类是引用类型,结构体是值类型。
*/
struct Person3 {
var firstName:String
var lastName:String
var fullName:String{
return firstName + " " + lastName
}
var age:Int=0
//构造函数,如果定义了构造方法则不会再自动生成默认构造函数
// init(firstName:String,lastName:String){
// self.firstName=firstName
// self.lastName=lastName
// }
func showMessage(){
print("firstName=\(firstName),lastName=\(lastName),age=\(age)")
}
//注意对于类中声明类型方法使用关键字class修饰,但结构体里使用static修饰
static func showStructName(){
print("Struct name is \"Person\"")
}
}
func testAction3() {
//注意所有结构体默认生成一个全员逐一构造函数,一旦自定义构造方法,这个默认构造方法将不会自动生成
var p=Person3(firstName: "Kenshin", lastName: "Cui", age: 28)
print(p.fullName) //结果:Kenshin Cui
p.showMessage() //结果:firstName "Kenshin", lastName "Cui", age 28
Person3.showStructName() //结果:Struct name is "Person"
//由于结构体(包括枚举)是值类型所以赋值、参数传递时值会被拷贝(所以下面的实例中p2修改后p并未修改,但是如果是类则情况不同)
var p2 = p
p2.firstName = "Tom"
print(p2.fullName) //结果:Tom Cui
print(p.fullName) //结果:Kenshin Cui
}
/*
默认情况下如果不自定义构造函数那么将自动生成一个无参构造函数和一个全员的逐一构造函数;
由于结构体是值类型,所以它虽然有构造函数但是没有析构函数,内存释放系统自动管理不需要开发人员过多关注;
类的类型方法使用class修饰(以便子类可以重写),而结构体、枚举的类型方法使用static修饰(补充:类方法也可以使用static修饰,但是不是类型方法而是静态方法;另外类的存储属性如果是类型属性使用static修饰,而类中的计算属性如果是类型属性使用class修饰以便可以被子类重写;换句话说class作为“类型范围作用域”来理解时只有在类中定义类型方法或者类型计算属性时使用,其他情况使用static修饰[包括结构体、枚举、协议和类型存储属性]);
*/
// MARK : -枚举
/*
在其他语言中枚举本质就是一个整形,只是将这组相关的值组织起来并指定一个有意义的名称。但是在Swift中枚举不强调一个枚举成员必须对应一个整形值(当然如果有必要仍然可以指定),并且枚举类型的可以是整形、浮点型、字符、字符串。首先看一下枚举的基本使用
*/
//注意Swift中的枚举默认并没有对应的整形值,case用来定义一行新的成员,也可以将多个值定义到同一行使用逗号分隔,例如:case Spring,Summer,Autumn,Winter
enum Season{
case Spring
case Summer
case Autumn
case Winter
}
func testSwitch() {
var s=Season.Spring
//一旦确定了枚举类型,赋值时可以去掉类型实现简写
s = .Summer
switch s {
case .Spring: //由于Swift的自动推断,这里仍然可以不指明类型
print("spring")
case .Summer:
print("summer")
case .Autumn:
print("autumn")
default:
print("winter")
}
}
/*
事实上Swift中也可以指定一个值和枚举成员对应,就像其他语言一样(通常其他语言的枚举默认就是整形),但是Swift又不局限于整形,它可以是整形、浮点型、字符串、字符,但是原始值必须是一种固定类型而不能存储多个不同的类型,同时如果原始值为整形则会像其他语言一样默认会自动递增。
*/
//指定原始值(这里定义成了整形)
enum Season1:Int{
case Spring=10 //其他值会默认递增,例如Summer默认为11,如果此处也不指定值会从0开始依次递增
case Summer
case Autumn
case Winter
}
func testSwitch1() {
var summer=Season1.Summer
//使用rawValue访问原始值
print("summer=\(summer),rawValue=\(summer.rawValue)")
//通过原始值创建枚举类型,但是注意它是一个可选类型
var autumn=Season1(rawValue: 12)
//可选类型绑定
if let newAutumn=autumn{
print("summer=\(newAutumn),rawValue=\(newAutumn.rawValue)")
}
}
/*
如果一个枚举类型能够和一些其他类型的数据一起存储起来往往会很有用,因为这可以让你存储枚举类型之外的信息(类似于其他语言中对象的tag属性,但是又多了灵活性),这在其他语言几乎是不可能实现的,但是在Swift中却可以做到,这在Swift中称为枚举类型相关值。要注意的是相关值并不是原始值,原始值需要事先存储并且只能是同一种类型,但是相关值只有创建一个基于枚举的变量或者常量时才会指定,并且类型可以不同(原始值更像其他语言的枚举类型)。
*/
//相关值
enum Color{
case RGB(String) //注意为了方便演示这里没有定义成三个Int类型(例如: RGB(Int,Int,Int))而使用16进制字符串形式
case CMYK(Float,Float,Float,Float)
case HSB(Int,Int,Int)
}
func testSwitch3() {
var red=Color.RGB("#FF0000")
var green=Color.CMYK(0.61, 0.0, 1.0, 0.0)
var blue=Color.HSB(240, 100, 100)
switch red {
case .RGB(let colorStr):
print("colorStr=\(colorStr)")
case let .CMYK(c,m,y,k):
print("c=\(c),m=\(m),y=\(y),k=\(k)")
case let .HSB(h,s,b):
print("h=\(h),s=\(s),b=\(b)")
}
}
/*
上面提到其实枚举也有一些类型和结构体的特性,例如计算属性(包括类型属性,枚举只能定义计算属性不能定义存储属性,存储属性只能应用于类和结构体)、构造方法(其实上面使用原始值创建枚举的例子就是一个构造方法)、方法(实例方法、类型方法)、下标脚本
*/
enum Season3:Int{
case Spring=0 ,Summer,Autumn,Winter
//定义计算属性
var tag:Int{
return self.rawValue
}
//类型属性
static var enumName:String{
return "Season"
}
// //定义构造方法,注意在枚举的构造函数中则必须保证self有值(正如类的构造方法必须保证其存储属性有值一样)
// init(prefix:String){
// switch prefix.lowercaseString {
// case "sp":
// self = .Spring
// case "su":
// self = .Summer
// case "au":
// self = .Autumn
// default:
// self = .Winter
// }
// }
//其实上面的构造器有些不合理,那就是default就是Winter,事实上这类构造器可能传任何参数,此时可以使用可失败构造函数来解决
//可失败构造函数返回nil(尽管Swift中构造函数是不返回值的,但是此时约定返回nil代表构造失败)
init?(prefix:String){
switch prefix.lowercased() {
case "sp":
self = .Spring
case "su":
self = .Summer
case "au":
self = .Autumn
case "wi":
self = .Winter
default:
return nil
}
}
//定义实例方法
func showMessage(){
print("rowValue=\(self.rawValue)")
}
//定义类型方法
static func showEnumName(){
print("Enum name is \"Season\"")
}
}
func testSwitch4() {
var summer=Season3.Summer
print(summer.tag) //结果:1
print(Season3.enumName) //结果:Season
Season3.showEnumName() //结果:Enum name is "Season"
summer.showMessage() //结果:rowValue=1
if let spring = Season3(prefix: "au") { //可选绑定,构造函数返回值可能为nil
print(spring.tag) //结果:2
}
}
// MARK : -泛型
/*
泛型可以让你根据需求使用一种抽象类型来完成代码定义,在使用时才真正知道其具体类型。这样一来就好像在定义时使用一个占位符做一个模板,实际调用时再进行模板套用,所以在C++中也称为“模板”。泛型在Swift中被广泛应用,上面介绍的Array<>、Dictionary<>事实上都是泛型的应用。通过下面的例子简单看一下泛型参数和泛型类型的使用。
*/
/*泛型参数*/
//添加了约束条件的泛型(此时T必须实现Equatable协议)
func isEqual<T:Equatable>(a:T,b:T)->Bool{
return a == b
}
protocol Stack1able{
//声明一个关联类型
associatedtype ItemType
mutating func push(item:ItemType)
mutating func pop()->ItemType;
}
struct Stack1:Stack1able{
typealias ItemType = String
var store:[ItemType]=[]
mutating func push(item:ItemType){
store.append(item)
}
mutating func pop()->ItemType{
return store.removeLast()
}
}
func tste() {
var a:Int=1,b:Int=2
print(isEqual(a: a,b: b)) //结果:false
var c:String="abc",d:String="abc"
print(isEqual(a: c,b: d)) //结果:true
/*泛型类型*/
struct Stack<T> {
var store:[T]=[]
//在结构体、枚举中修改其变量需要使用mutating修饰(注意类不需要)
mutating func push(item:T){
store.append(item)
}
mutating func pop()->T{
return store.removeLast()
}
}
var s = Stack<Int>()
s.push(item: 1)
let t = s.pop()
print("t=\(t)") //结果:t=1
// //扩展泛型类型
// extension Stack{
// var top:T?{
// return store.last
// }
// }
//
// s.push(item: 2)
// print(s.top!) //结果:2
var s1 = Stack1()
s1.push(item: "hello")
s1.push(item: "world")
let t1 = s1.pop()
print("t1=\(t1)") //结果:t=world
}
class JWSwiftBaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Swift"
// MARK: - 四·输出字符串
/*
Swift没有main函数,从top level code的上方开始往下执行(就是第一个非声明语句开始执行[表达式或者控制结构,类、结构体、枚举和方法等属于声明语句]),不能存在多个top level code文件(否则编译器无法确定执行入口,事实上swift隐含一个main函数,这个main函数会设置并调用全局 “C_ARGC C_ARGV”并调用由top level code构成的top_level_code()函数);
Swift通过import引入其他类库(和Java比较像);
Swift语句不需要双引号结尾(尽管加上也不报错),除非一行包含多条语句(和Python有点类似)
*/
print("Hello, World!")
// MARK: - 五·3.0改变
//Swift3.0对于可选类型控制更加严谨,隐式可选类型和其他类型的运算之后获得的是可选类型而不是隐式可选类型
let a1:Int! = 1
let b1 = a1 + 1 // 此时强制解包,b是Int型
let c1 = a1 // 注意此时c是Int? 在之前的Swift版本中c是Int!
// MARK: - 命名
// 1.去掉前缀
let url1 = URL(string: "www.cmjstudio.com")
let isFileURL = url1?.isFileURL //old:url1.fileURL ,现在更加注重语意
let data1 = Data() //NSData
// 2.方法名使用动词,其他名词、介词等作为参数或移除
var array1 = [1,2,3]
array1.append(contentsOf: [4,5,6]) // old:array1.appendContentsOf([4,5,6])
array1.remove(at: 0) // old:array1.removeAtIndex(0)
// 3.不引起歧义的情况下尽量消除重复
let color1 = UIColor.red // old:var color1 = UIColor.redColor()
// 4.枚举成员首字母变成小写
let label1 = UILabel()
label1.textAlignment = .center // old:label1.textAlignment = .Center
// 5.按钮的Normal状态去掉
let btn1 = UIButton()
btn1.setTitle("hello", for: UIControlState()) // 相当于Normal状态
// MARK: - 去C风格
let rect1 = CGRect(x: 0, y: 0, width: 100, height: 100)
// 下面的代码将要报错,3.0完全废除这种类C的风格
//let rect1 = CGRectMake(0, 0, 100, 100)
if let context1 = UIGraphicsGetCurrentContext() {
_ = CGContext.fillPath(context1) // old:CGContextFillPath(context1!)
}
// MARK: - GCD的改变
let queue = DispatchQueue(label: "myqueue")
queue.async {
debugPrint("hello world!")
}
// old:
//let queue = dispatch_queue_create("myqueue", nil)
//dispatch_async(queue) {
// debugPrint("hello world!")
//}
// MARK: - 相关常量定义被移到枚举内部
// NotificationCenter.default.addObserver(self, selector: #selector(print()), name: UserDefaults.didChangeNotification, object: nil)
//old:NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userDefaultChange()), name: NSUserDefaultsDidChangeNotification, object: nil)
// MARK: - 集合API的变化
//let array1 = [1,2,3]
let next = array1.index(after: 0) // old:let start = array1.startIndex let next = start.successor()
let first = array1.first { (element) -> Bool in // 增加新的方法
element > 1
}
let r = Range(0..<3) //old: let _ = NSRange(location: 0, length: 3)
// 下面的代码必须在控制器中执行,用于遍历当前view及其父视图
for subview in sequence(first: self.view, next: { $0?.superview }){
debugPrint(subview)
}
// MARK: - 新的浮点协议
let af = 2 * Float.pi // old: let a = 2 * M_PI
let bf = 2.0 * .pi // 注意前面是浮点型,后面可以省略Float
// MARK: - 六·数据类型
/*
Swift通过var进行变量定义,通过let进行常量定义(这和其他高级语言比较类似,例如F#);
Swift添加了类型推断,对于赋值的常量或者变量会自动推断其具体类型;
Swift是强类型语言(应该说它比C#、Java等强类型语言控制还要严格),不同的数据类型之间不能隐式转化,如果需要转化只能强制转化;
在Swift中类型转换直接通过其类型构造函数即可,降低了API的学习成本;
Swift包含了C和ObjC语言中的所有基础类型,Int整形,Float和Double浮点型,Bool布尔型,Character字符型,String字符串类型;当然还包括enum枚举、struct结构体构造类型;Array数组、Set集合、Dictionary字典集合类型;不仅如此还增加了高阶数据类型元组(Tuple),可选类型(Optinal)。
*/
var a:Int = 1 //通过var定义一个变量
var b = 2 //变量b虽然没有声明类型,但是会自动进行类型推断,这里b推断为Int类型
var c:UInt=3
let d = a+b //通过let定义一个变量
//下面通过"\()"实现了字符串和变量相加(字符串插值),等价于print("d="+String(d))
print("d=\(d)") //结果:d=3
//注意由于Swift是强类型语言,a是Int类型而c是UInt类型,二者不能运算,下面的语句报错;但是注意如果是类似于:let a=1+2.0是不会报错的,因为两个都是字面量,Swift会首先计算出结果再推断a的类型
//let e=a+c
//Int.max是Int类型的最大值,类似还有Int.min、Int32.max、Int32.min等
let e = Int.max //结果:9223372036854775807
var f:Float=1.0//浮点型
var g=2.0 //浮点型自动推断为Double类型
var h:String="hello "
//emoj表情也可以作为变量或者常量,事实上所有Unicode字符都是可以的
var 💖🍎="love and apple"
//两个字符串相加,但是注意不同类型不能相加
var i=h+💖🍎 //结果:hello love and apple
//布尔类型只有两个值true、false,类似于if语句中的条件只能是布尔类型不能像ObjC一样非0即真
var j:Bool=true
//字符类型,同样使用双引号,但是只能是一个字符,如果不指定类型则"c"默认会推断为字符串(var k:Character="c"是字符类型,但是var k="c"是字符串类型)
var k:Character="c"
var l=00100 //等于100,可以在前面添加额外的0
var m=10_000_000 //等于10000000,可以使用增加额外的下划线方便阅读而不改变值的大小
//Int转换Float或Double:
let intVar : Int = 3
let doubleVar : Double = Double(intVar)
//Int转换为String:
let intVar1 : Int = 3
let strVar1 : String = String(intVar1)
//String转换为Int:
let strVar2 : String = "123"
let intVar2 : Int? = Int(strVar2)
//Double转换为String:
let doubleVar3 : Double = 3.14
let strVar3 : String = String(doubleVar)
//Double保留两位小数,需要对Double进行扩展:
// extension Double {
// func format(f: String) -> String {
// return NSString(format: "%\(f)f", self)
// }
// }
let myDouble = 1.234567
print(myDouble.format(f: ".2"))
//String转换Double:
let strVar5 : String = "3.14"
var string5 = NSString(string: strVar5).doubleValue
// MARK: - 七·集合类型
/*
Swift提供了三种集合类型:数组Array、集合Set、字典Dictionary。和ObjC不同的是,由于Swift的强类型,集合中的元素必须是同一类型,而不能像ObjC一样可以存储任何对象类型,并且注意Swift中的集合是值类型而非引用类型(事实上包括String、结构体struct、枚举enum都是值类型)
*/
// MARK: - Array
//声明数组的时候必须确定其类型,下面使用[String]声明一个字符串数组([String]是Array<String>简单表达形式)
//var a:Array<String>=["hello","world"]
var arr:[String]=["hello","world"]
_ = arr[0] //访问数组元素
//下面创建一个Double类型的数组,这里没有使用字面量,当前是一个空数组,当然也可以写成var b:[Double]=[]
var arr_b=[Double]()
for i in arr{
print("arr i=\(i)")
}
//添加元素,Swift中可变类型不再由单独的一个类型来表示,统统使用Array,如果想声明为不可变数组只要使用let定义即可
arr.append("!")
arr+=["I" ,"am" ,"Kenshin"] //追加元素
print("arr.count=\(arr.count)") //结果:a.count=6
arr[3...5]=["I","Love","Swift"] //修改元素,但是注意无法用这种方式添加元素
//a[6]=["."]//这种方式是错误的
arr.insert("New", at: 5) //插入元素:hello world! I Love New Swift
arr.remove(at: 5) //删除指定元素
//使用全局enumerate函数遍历数据索引和元素
for (index,element) in arr.enumerated(){
print("index=\(index),element=\(element)")
}
//使用构造函数限制数组元素个数并且指定默认值,等价于var c=Array(count: 3, repeatedValue: 1),自动推断类型
var arrThreeValue = [Int](repeatElement(1, count: 3))
// MARK: - Set表示没有顺序的集合
//注意集合没有类似于数组的简化形式,例如不能写成var a:[String]=["hello","world"]
var set_a:Set<String>=["hello","world"]
var set_b:Set=[1,2] //类型推断:Set<Int>
set_a.insert("!") //注意这个插入不保证顺序
if !set_a.isEmpty { //判断是否为空
set_a.remove("!")
}
if !set_a.contains("!"){
set_a.insert("!")
}
// MARK: - Dictionary
/*
Dictionary字典同样是没有顺序的,并且在Swift中字典同样要在使用时明确具体的类型。和ObjC中一样,字典必须保证key是唯一的,而这一点就要求在Swift中key必须是可哈希的,不过幸运的是Swift中的基本类型(如Int、Float、Double、Bool、String)都是可哈希的,都可以作为key。
在Swift中集合的可变性不是像ObjC一样由单独的数据类型来控制的,而是通过变量和常量来控制,这一点和其他高级语言比较类似
*/
//通过字面量进行字典初始化,注意等价于var a:Dictionary<Int,String>=[200:"success",404:"not found"]
var dic_a:[Int:String]=[200:"success",404:"not found"]
var dic_b=[200:"success",404:"not found"] //不声明类型,根据值自动推断类型
_ = dic_a[200] //读取字典
dic_a[404]="can not found" //修改
dic_a[500]="internal server error" //添加
//a=[:] //设置为空字典,等价于:a=[Int:String]()
for code in dic_a.keys{
print("code=\(code)")
}
for description in dic_a.values{
print("description=\(description)")
}
for (code,description) in dic_a{
print("code=\(code),description=\(description)")
}
// MARK: - 元组(Tuple)
/*
在开发过程中有时候会希望临时组织一个数据类型,此时可以使用一个结构体或者类,但是由于这个类型并没有那么复杂,如果定义起来又比较麻烦,此时可以考虑使用元组
*/
var point=(x:50,y:100) //自动推断其类型:(Int,Int)
_ = point.x //可以用类似于结构体的方式直接访问元素,结果:50
_ = point.y //结果:100
_ = point.0 //也可以采用类似数组的方式使用下标访问,结果:50
_ = point.1 //结果:100
//元组也可以不指定元素名称,访问的时候只能使用下标
let frame:(Int,Int,Int,Float)=(0,0,100,100.0)
print(frame) //结果:(0, 0, 100, 100.0)
//注意下面的语句是错误的,如果指定了元组的类型则无法指定元素名称
//let frame:(Int,Int,Int,Int)=(x:0,y:0,width:100,height:100)
var size=(width:100,25) //仅仅给其中一个元素命名
_ = size.width //结果:100
_ = size.1 //结果:25
var httpStatus:(Int,String)=(200,"success") //元组的元素类型并不一定相同
var (status,description)=httpStatus //一次性赋值给多个变量,此时status=200,description="success"
//接收元组的其中一个值忽略另一个值使用"_"(注意在Swift中很多情况下使用_忽略某个值或变量)
var (sta,_)=httpStatus
print("sta=\(sta)") //结果:sta=200
/**
* 元组作为函数的参数或返回值,借助元组实现了函数的多个返回值
*/
func request()->(code:Int,description:String){
return (404,"not found")
}
var result=request()
_ = result.0 //结果:404
_ = result.1 //结果:not found
_ = result.code //结果:404
_ = result.description //结果:not found
// MARK: - 可选类型
/*
所谓可选类型就是一个变量或常量可能有值也可能没有值则设置为可选类型。在ObjC中如果一个对象类型没有赋值,则默认为nil,同时nil类型也只能作为对象类型的默认值,对于类似于Int等基本类型则对应0这样的默认值。由于Swift是强类型语言,如果在声明变量或常量时没有进行赋值,Swift并不会默认设置初值(这一点和其他高级语言不太一样,例如C#虽然也有可选类型,但是要求并没有那么严格)
*/
var x:Float? //使用?声明成一个可选类型,如果不赋值默认为nil
x=172.0
var y:Float=60.0
//var z=x+y //注意此句报错,因为Int和Int?根本就是两种不同的类型,在Swift中两种不同的类型不能运算(因为不会自动进行类型转化)
var z=x!+y //使用!进行强制解包
let age="29"
var ageInt = Int(age) //注意ageInt是Int可选类型而不是Int类型(因为String的toInt()方法并不能保证其一定能转化为Int类型)
/*
Swift中类似于Int和Int?并不是同一种类型,不能进行相关运算,如果要运算只能解包;
可选类型其本质就是此类型内部存储分为“Some”和“None”两个部分,如果有值则存储到“Some”中,没有值则为“None”(早期Playground中可以看到两个部分,如今已经取消显示Some等描述了),使用感叹号强制解包的过程就是取出“Some”部分;
既然可选类型有可能有值,也可能没有值那么往往有时候就需要判断。可以使用if直接判断一个可选类型是否为nil,这样一来就可以根据情况进行强制解包(从Some部分取出值的过程);另一个选择就是在判断的同时如果有值则将值赋值给一个临时变量或常量,否则不进入此条件语句,这个过程称之为“可选绑定”
*/
/*可选类型判断*/
var ageT="29"
var ageTInt = Int(ageT) //注意ageInt是Int可选类型而不是Int类型(因为String的toInt()方法并不能保证其一定能转化为Int类型)
if ageTInt==nil {
print("ageInt=nil")
}else{
print("ageInt=\(ageTInt!)") //注意这里使用感叹号!强制解析
}
/**
* 可选类型绑定
* 如果可选类型有值则将值赋值给一个临时变量或者常量(此时此变量或者常量接受的值已经不是可选类型),如果没有值则不执行此条件
*/
if let newAgeT=ageTInt{ //此时newAge可以定义成常量也可以定义成变量
print("newAge=\(newAgeT)") //注意这里并不需要对newAge强制解包
}else{
print("ageInt=nil")
}
/*
通过演示可以看出Swift中的可选绑定如果实际计算不得不进行强制解包,如果一个可选类型从第一次赋值之后就能保证有值那么使用时就不必进行强制解包了,这种情况下可以使用隐式可选解析类型(通过感叹号声明而不是问号)
*/
/*隐式解析可选类型
*/
var age1:Int!=0 //通过感叹号声明隐式解析可选类型,此后使用时虽然是可选类型但是不用强制解包
age1=29
var newAge1:Int=age1 //不用强制解包直接赋值给Int类型(程序会自动解包)
if var tempAge1=age1 {
print("tempAge=\(tempAge1)")
}else{
print("age=nil")
}
// MARK: - 八·运算符
/*
Swift中支持绝大多数C语言的运算符并改进以减少不必要的错误(例如等号赋值后不返回值),算术运算会检查溢出情况,必要时还能使用新增的溢出运算符。另外Swift中还可以对浮点数使用取余运算符,新增了区间运算符。对于基本的运算符这里不再一一介绍,简单看一下Swift中的区间运算符和溢出运算符
*/
/**
* 区间运算符,通常用于整形或者字符范围(例如"a"..."z")
*/
for i in 1...5 { //闭区间运算符...(从1到5,包含5)
print("i=\(i)")
}
for i in 1..<5{ //半开区间运算符..<(从1到4)
print("i=\(i)")
}
var strArr = "hello world."
var range = "a"..."z"
// for t in strArr {
// if range.contains(String(t)) {
// print(t) //结果:helloworld
// }
// }
/*溢出运算符
溢出运算符的原理其实很简单,例如对于UInt8,如果8位均为1则十进制表示是255,但是当加1之后则变成了9位“100000000”,出现了溢出但是UInt8本身值只能存储8位,所以取后面8位就变成了“00000000”,十进制表示就是0
*/
var a_Max=UInt8.max //a=255
//var b:UInt8=a+1 //注意b会出现溢出,此句报错
//下面使用溢出运算符,结果为:0,类似的还有&-、&*、&/
//使用溢出运算符可以在最大值和最小值之前循环而不会报错
var b_Max:UInt8 = a_Max &+ 1
// MARK: - 九·控制流
/*
Swift中的多数控制流和其他语言差别并不大,例如for、while、do while、if、switch等,而且有些前面已经使用过(例如for in循环),这里将着重介绍一些不同点
*/
var afor=["a","b","c","d","e","f","g"]
let bfor=afor[1]
/**
* switch支持一个case多个模式匹配,同时case后不用写break也会在匹配到种情况后自动跳出匹配,不存在隐式贯穿,如果想要贯穿在case之后添加"fallthrough"关键字
*/
switch bfor{
case "a","b":
print("b=a or b=b")
case "c","d","e","f":
print("b in (c,d,e,f)")
default:
print("b=g")
}
/**
* 匹配区间,同时注意switch必须匹配所有情况,否则必须加上default
*/
let cfor:Int=88
switch cfor{
case 1...60:
print("1-60")
case 61...90:
print("61-90")
case 91...100:
print("91-100")
default:
print("1>c>100")
}
/**
* 元组匹配、值绑定、where条件匹配
* 注意下面的匹配没有default,因为它包含了所有情况
*/
var dfor=(x:900,y:0)
switch dfor{
case (0,0):
print("d in (0,0)")
case (_,0): //忽略x值匹配
print("d in y")
case (0,let y)://值绑定
print("d in x,y=\(y)")
case (-100...100,-100...100): //注意这里有可能和第一、二、三个条件重合,但是Swift允许多个case匹配同一个条件,但是只会执行第一个匹配
print("x in(0-100),y in (0-100)")
case let (x,y) where x==y: //where条件匹配,注意这里的写法等同于:(let x,let y) where x==y
print("x=y=\(x)")
case let (x, y):
print("x=\(x),y=\(y)")
}
/*
在其他语言中通常可以使用break、continue、return(Swift中添加了fallthrough)等来终止或者跳出某个执行语句,但是对于其行为往往是具有固定性的,例如break只能终止其所在的内层循环,而return只能跳出它所在的函数。在Swift中这种控制转移功能得到了加强,那就是使用标签。利用标签你可以随意指定转移的位置
*/
var aBreak=5
whileLoop:
while aBreak > 0 {
for i in 0 ..< aBreak{
print("a=\(aBreak),i=\(i)")
break whileLoop
//如果此处直接使用break将跳出for循环,而由于这里使用标签直接跳出了while,结果只会打印一次,其结果为:a=4,i=0
}
aBreak -= 1
}
// MARK: - 十·函数和闭包
// MARK: - 函数和闭包——结构体
let ca = Caculator()
ca.sum(a: 1, b: 2) // 此处会警告,因为方法有返回值但是没有接收
let _ = ca.sum(a: 1, b: 2) // 使用"_"接收无用返回值
ca.func1(a: 1, b: 2) // 由于func1添加了@discardableResult声明,即使不接收返回值也不会警告
// MARK: - 函数和闭包——函数
/*函数是一个完成独立任务的代码块,Swift中的函数不仅可以像C语言中的函数一样作为函数的参数和返回值,而且还支持嵌套,并且有C#一样的函数参数默认值、可变参数等*/
//定义一个函数,注意参数和返回值,如果没有返回值可以不写返回值或者写成Void、空元组()(注意Void的本质就是空元组)
func sum(num1:Int,num2:Int)->Int{
return num1 + num2
}
sum(num1: 1, num2: 2)
/*
Swift中的函数仅仅表达形式有所区别(定义形式类似于Javascript,但是js不用书写返回值),但是本质并没有太大的区别。不过Swift中对函数参数强调两个概念就是局部参数名(又叫“形式参数”)和外部参数名,这极大的照顾到了ObjC开发者的开发体验。在上面的例子中调用sum函数并没有传递任何参数名,因为num1、num2仅仅作为局部参数名在函数内部使用,但是如果给函数指定一个外部参数名在调用时就必须指定参数名。另外前面也提到关于Swift中的默认参数、可变长度的参数,包括一些高级语言中的输入输出参数
*/
/**
* 函数参数名分为局部参数名和外部参数名
*/
/**
* 函数参数名分为局部参数名和外部参数名
*/
// func split(string a:String,seperator b:Character)->[String]{
// return split(a, maxSplit: Int.max, allowEmptySlices: false, isSeparator: {$0==b})
// }
//由于给split函数设置了外部参数名string和seperator,所以执行的时候必须带上外部参数名,此处可以看到一个有意义的外部参数名大大节省开发者使用成本
// split(string: "hello,world,!", seperator: ",") //结果:["hello", "world", "!"]
//下面通过在局部参数名前加上#来简写外部参数名(此时局部参数名和外部参数名相同)
// func split2(#string:String,#seperator:Character)->[String]{
// return split(string, maxSplit: Int.max, allowEmptySlices: false, isSeparator: {$0==seperator})
// }
// split2(string: "hello,world,!", seperator: ",")
//上面的split函数的最后一个参数默认设置为",",注意如果使用默认参数那么此参数名将默认作为外部参数名(此时局部参数名和外部参数名相同)
// func split3(#string:String,seperator:Character=",")->[String]{
// return split(string, maxSplit: Int.max, allowEmptySlices: false, isSeparator: {$0==seperator})
// }
// split3(string: "hello,world,!", seperator: ",") //结果:["hello", "world", "!"]
// split3(string: "hello world !", seperator: " ") //结果:["hello", "world", "!"]
//但是如果有默认值,又不想指定局部参数名可以使用“_”取消外部参数名
// func split4(string:String,_ seperator:Character=",")->[String]{
// return split(string, maxSplit: Int.max, allowEmptySlices: false, isSeparator: {$0==seperator})
// }
// split4("hello,world,!", ",") //结果:["hello", "world", "!"]
/**
* 可变参数,一个函数最多有一个可变参数并且作为最后一个参数
* 下面strings参数在内部是一个[String],对于外部是不定个数的String参数
*/
func joinStr(seperator:Character=",",strings:String...)->String{
var result:String=""
for i in 0 ..< strings.count{
if i != 0{
result.append(seperator)
}
result+=strings[i]
}
return result
}
joinStr(seperator:" ", strings: "hello","world","!") //结果:"hello world !"
/**
* 函数参数默认是常量,不能直接修改,通过声明var可以将其转化为变量(但是注意C语言参数默认是变量)
* 但是注意这个变量对于外部是无效的,函数执行完就消失了
*/
func sum2( num1:Int,num2:Int)->Int{
var num1 = num1
num1 = num1 + num2
return num1
}
sum2(num1: 1, num2: 2) //结果:3
/**
* 输入输出参数
* 通过输入输出参数可以在函数内部修改函数外部的变量(注意调用时不能是常量或字面量)
* 注意:下面的swap仅仅为了演示,实际使用时请用Swift的全局函数swap
*/
func swap( a:inout Int , b:inout Int){
a=a+b
b=a-b
a=a-b
}
var a233=1,b233=2
swap(a: &a233, b: &b233) //调用时参数加上“&”符号
print("a=\(a233),b=\(b233)") //结果:"a=2,b=1"
/*和很多语言一样,Swift中的函数本身也可以看做一种类型,既可以作为参数又可以作为返回值*/
/**
* 函数类型
*/
var sum3=sum //自动推断sum3的类型:(Int,Int)->Int,注意不同的函数类型之间不能直接赋值
sum3(1,2) //结果:3
//函数作为返回值
func fn()->(Int,Int)->Int{
//下面的函数是一个嵌套函数,作用于是在fn函数内部
func minus(a:Int,b:Int)->Int{
return a-b
}
return minus;
}
var minus=fn()
//函数作为参数
func caculate(num1:Int,num2:Int,fn:(Int,Int)->Int)->Int{
return fn(num1,num2)
}
caculate(num1: 1, num2: 2, fn: sum) //结果:3
caculate(num1: 1,num2: 2, fn: minus) //结果:-1
// MARK: - 函数和闭包——闭包
/*
Swift中的闭包其实就是一个函数代码块,它和ObjC中的Block及C#、Java中的lambda是类似的。闭包的特点就是可以捕获和存储上下文中的常量或者变量的引用,即使这些常量或者变量在原作用域已经被销毁了在代码块中仍然可以使用。事实上前面的全局函数和嵌套函数也是一种闭包,对于全局函数它不会捕获任何常量或者变量,而对于嵌套函数则可以捕获其所在函数的常量或者变量。通常我们说的闭包更多的指的是闭包表达式,也就是没有函数名称的代码块,因此也称为匿名闭包
在Swift中闭包表达式的定义形式如下:
{ ( parameters ) -> returnType in
statements
}
*/
func sum1(num1:Int,num2:Int)->Int{
return num1 + num2
}
func minus(num1:Int,num2:Int)->Int{
return num1 - num2
}
func caculate1(num1:Int,num2:Int,fn:(Int,Int)->Int)->Int{
return fn(num1,num2)
}
var (a11,b11)=(1,2)
caculate1(num1: a, num2: b, fn: sum) //结果:3
caculate1(num1: a, num2: b, fn: minus) //结果:-1
//利用闭包表达式简化闭包函数
caculate1(num1: a11, num2: b11, fn: {(num1:Int,num2:Int)->Int in
return num1 - num2
}) //结果:-1
//简化形式,根据上下文推断类型并且对于单表达式闭包(只有一个语句)可以隐藏return关键字
caculate1(num1: a11, num2: b11, fn: { num1,num2 in
num1 - num2
}) //结果:-1
//再次简化,使用参数名缩写,使用$0...$n代表第n个参数,并且此in关键字也省略了
caculate1(num1: a11, num2: b11, fn: {
$0 - $1
}) //结果:-1
/*考虑到闭包表达式的可读取性,Swift中如果一个函数的最后一个参数是一个函数类型的参数(或者说是闭包表达式),则可以将此参数写在函数括号之后,这种闭包称之为“尾随闭包”*/
func sum3(num1:Int,num2:Int)->Int{
return num1 + num2
}
func minus2(num1:Int,num2:Int)->Int{
return num1-num2
}
func caculate2(num1:Int,num2:Int,fn:(Int,Int)->Int)->Int{
return fn(num1,num2)
}
var (a22,b22)=(1,2)
//尾随闭包,最后一个参数是闭包表达式时可以卸载括号之后,同时注意如果这个函数只有一个闭包表达式参数时可以连通括号一块省略
//请注意和函数定义进行区分
caculate2(num1: a22, num2: b22){
$0 - $1
} //结果:-1
/*
前面说过闭包之所以称之为“闭包”就是因为其可以捕获一定作用域内的常量或者变量进而闭合并包裹着
*/
func add()->()->Int{
var total=0
var step=1
func fn()->Int{
total+=step
return total
}
return fn
}
//fn捕获了total和step,尽管下面的add()执行完后total和step被释放,但是由于fn捕获了二者的副本,所以fn会随着两个变量的副本一起被存储
var a_fun=add()
a_fun() //结果:1
a_fun() //结果:2,说明a中保存了total的副本(否则结果会是1)
var b_fun=add()
b_fun() //结果:1 ,说明a和b单独保存了total的副本(否则结果会是3)
var c_fun=b_fun
c_fun() //结果:2,说明闭包是引用类型,换句话说函数是引用类型(否则结果会是1)
/*
Swift会自动决定捕获变量或者常量副本的拷贝类型(值拷贝或者引用拷贝)而不需要开发者关心,另外被捕获的变量或者常量的内存管理同样是由Swift来管理,例如当上面的函数a不再使用了那么fn捕获的两个变量也就释放了
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 8ef8215f2c6657c02b192a4c4d5b6ccd | 26.912183 | 264 | 0.580782 | 2.963493 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/PartyService/View/CourseDetailReadingView.swift | 1 | 5195 | //
// CourseDetailReadingView.swift
// WePeiYang
//
// Created by Allen X on 8/17/16.
// Copyright © 2016 Qin Yubo. All rights reserved.
//
import UIKit
class CourseDetailReadingView: UIView, UIWebViewDelegate {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
func dismissAnimated() {
//log.word("haha")/
UIView.animateWithDuration(0.7, animations: {
self.frame = CGRect(x: 0, y: self.frame.height, width: self.frame.width, height: self.frame.height)
}) { (_: Bool) in
self.removeFromSuperview()
}
}
}
extension CourseDetailReadingView {
convenience init(detail: Courses.Study20.Detail) {
let blurEffect = UIBlurEffect(style: .Light)
let frostView = UIVisualEffectView(effect: blurEffect)
let downArrow = UIButton(backgroundImageName: "ic_arrow_down", desiredSize: CGSize(width: 88, height: 24))
downArrow?.alpha = 0.25
self.init()
//self.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
assignGestureRecognizerToView()
downArrow?.addTarget(self, action: #selector(self.dismissAnimated), forControlEvents: .TouchUpInside)
self.addSubview(frostView)
frostView.snp_makeConstraints {
make in
make.top.left.bottom.right.equalTo(self)
}
frostView.addSubview(downArrow!)
downArrow!.snp_makeConstraints {
make in
make.top.equalTo(frostView).offset(28)
make.centerX.equalTo(frostView)
}
if detail.articleIsHidden == "1" {
let bannedLabel = UILabel(text: "你暂时没有权限阅读这篇文章", fontSize: 24)
frostView.addSubview(bannedLabel)
bannedLabel.snp_makeConstraints {
make in
make.centerX.equalTo(frostView)
make.centerY.equalTo(frostView)
}
} else if detail.articleIsDeleted == "1"{
let deletedLabel = UILabel(text: "这篇文章好像被删除啦!", fontSize: 24)
frostView.addSubview(deletedLabel)
deletedLabel.snp_makeConstraints {
make in
make.centerX.equalTo(frostView)
make.centerY.equalTo(frostView)
}
} else {
let nameLabel = UILabel(text: detail.articleName!, fontSize: 30)
nameLabel.numberOfLines = 0
//let contentView = UIWebView(htmlString: "<p><object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\" height=\"600\" width=\"800\"><param name=\"quality\" value=\"high\" /><param name=\"movie\" value=\"http://www.tudou.com/a/Rcd1Bo1-qqw/&iid=132528954&rpid=849459437&resourceId=849459437_04_0_99/v.swf\" /><embed height=\"600\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" quality=\"high\" src=\"http://www.tudou.com/a/Rcd1Bo1-qqw/&iid=132528954&rpid=849459437&resourceId=849459437_04_0_99/v.swf\" type=\"application/x-shockwave-flash\" width=\"800\"></embed></object></p>")
let contentView = UIWebView(htmlString: detail.articleContent!)
contentView.delegate = self
let timeLabel = UILabel(text: detail.courseInsertTime!, fontSize:13)
timeLabel.textColor = .grayColor()
frostView.addSubview(nameLabel)
nameLabel.snp_makeConstraints {
make in
make.left.equalTo(frostView).offset(24)
make.top.equalTo(downArrow!).offset(26)
make.right.equalTo(frostView).offset(-28)
}
frostView.addSubview(timeLabel)
timeLabel.snp_makeConstraints {
make in
make.left.equalTo(nameLabel)
make.top.equalTo(nameLabel.snp_bottom).offset(14)
}
frostView.addSubview(contentView)
contentView.snp_makeConstraints {
make in
make.left.equalTo(frostView).offset(18)
make.top.equalTo(timeLabel.snp_bottom).offset(8)
make.right.equalTo(frostView).offset(-20)
make.bottom.equalTo(frostView)
}
}
}
}
//Gesture Recognizer
private extension CourseDetailReadingView {
func assignGestureRecognizerToView() {
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(self.dismissAnimated))
swipeDown.direction = .Down
addGestureRecognizer(swipeDown)
}
}
private extension UIWebView {
convenience init(htmlString: String) {
self.init()
backgroundColor = .clearColor()
opaque = false
userInteractionEnabled = true
scrollView.scrollEnabled = true
loadHTMLString(htmlString, baseURL: nil)
}
} | mit | 17224ebb89f964e01a09f1fb82ebdd47 | 36.569343 | 706 | 0.602993 | 4.328007 | false | false | false | false |
gbuela/kanjiryokucha | KanjiRyokucha/ReviewViewController.swift | 1 | 10351 | //
// ReviewViewController.swift
// KanjiRyokucha
//
// Created by German Buela on 2/9/17.
// Copyright © 2017 German Buela. All rights reserved.
//
import UIKit
import ReactiveSwift
import SwiftRater
fileprivate typealias ReviewStarter = ActionStarter<[ReviewEntry], Response, FetchError>
fileprivate typealias SubmitStarter = ActionStarter<[ReviewEntry], [SignalProducer<Response, FetchError>], FetchError>
struct Rating {
let fromPercent: Int
let emoji: String
}
extension PieChartItem {
init(value: Int, color: UIColor, text: String? = nil) {
self.init(value: Float(value), color: color, text: text ?? "\(value)")
}
}
class PerformanceChartDataSource: ARPieChartItemDataSource {
private var items: [PieChartItem] = []
var pieChartItems: [PieChartItem] {
return items
}
func set(yesCount: Int, noCount: Int, otherCount: Int, unansweredCount: Int) {
let yesItem = PieChartItem(value: yesCount, color: UIColor.pieYes)
let noItem = PieChartItem(value: noCount, color: UIColor.pieNo)
let otherItem = PieChartItem(value: otherCount, color: UIColor.pieOther)
let unansweredItem = PieChartItem(value: unansweredCount, color: UIColor.pieUnanswered)
items = [yesItem, noItem, otherItem, unansweredItem]
}
}
class SubmissionChartDataSource: ARPieChartItemDataSource {
private var items: [PieChartItem] = []
var pieChartItems: [PieChartItem] {
return items
}
func set(submitted: Int, total: Int) {
let unsubmitted = max(total - submitted, 0)
let item0 = PieChartItem(value: submitted, color: UIColor.pieSubmitted, text: "")
let item1 = PieChartItem(value: unsubmitted, color: UIColor.pieUnsubmitted, text: "")
items = [item0, item1]
}
}
class ReviewViewController: UIViewController {
private class func scoreFromState(_ state: ReviewState?) -> Int? {
guard let state = state,
state.totalAnswered > 0
else { return nil }
let answered = Double(state.totalAnswered)
let yesAnswers = Double(state.answeredYes)
let percent = (100.0 / answered) * yesAnswers
guard !percent.isNaN else { return nil }
let score = Int(percent)
if score < 0 {
return 0
} else if score > 100 {
return 100
}
return score
}
private static let ratings: [Rating] = [
Rating(fromPercent: 0, emoji: "😢"),
Rating(fromPercent: 10, emoji: "🙄"),
Rating(fromPercent: 60, emoji: "😐"),
Rating(fromPercent: 75, emoji: "🙂"),
Rating(fromPercent: 85, emoji: "😎"),
Rating(fromPercent: 97, emoji: "😜"),
]
private class func emojiRatingFromScore(_ percent: Int?) -> String {
guard let percent = percent else { return "😶" }
var emoji = ""
for rating in ratings {
if percent >= rating.fromPercent {
emoji = rating.emoji
} else {
break
}
}
return emoji
}
private class func cancelButtonFromPending(_ pending: Int) -> String {
if pending > 0 {
return "cancel"
} else {
return "done"
}
}
@IBOutlet weak var reviewButton: UIButton!
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var reviewContainer: UIView!
@IBOutlet weak var reviewTitle: UILabel!
@IBOutlet weak var reviewLabel: UILabel!
@IBOutlet weak var submitLabel: UILabel!
@IBOutlet weak var performanceChart: ARPieChart!
@IBOutlet weak var submissionChart: ARPieChart!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var performanceEmoji: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
public weak var reviewDelegate: ReviewDelegate!
public weak var reviewEngine: ReviewEngineProtocol!
private var reviewStarter: ReviewStarter?
private var submitStarter: SubmitStarter?
private let score: MutableProperty<Int?> = MutableProperty(nil)
private let performanceDataSource = PerformanceChartDataSource()
private let submissionDataSource = SubmissionChartDataSource()
var global: Global!
init(engine: ReviewEngineProtocol, delegate: ReviewDelegate) {
super.init(nibName: "ReviewViewController", bundle: nil)
reviewEngine = engine
reviewDelegate = delegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
reviewContainer.backgroundColor = .background
global = Database.getGlobal()
setUp()
wireUp()
refreshCharts(state: reviewEngine.reviewState.value)
}
func setUp() {
performanceChart.showDescriptionText = true
if UIScreen.main.bounds.maxY == 480 {
submissionChart.innerRadius = 25
performanceChart.innerRadius = 25
performanceChart.outerRadius = 60
submissionChart.outerRadius = 35
} else {
submissionChart.innerRadius = 35
performanceChart.innerRadius = 35
performanceChart.outerRadius = 80
submissionChart.outerRadius = 45
}
submissionChart.showDescriptionText = false
performanceChart.dataSource = performanceDataSource
submissionChart.dataSource = submissionDataSource
reviewLabel.textColor = .ryokuchaDark
submitLabel.textColor = .ryokuchaDark
view.layer.cornerRadius = 8.0
view.layer.borderColor = reviewEngine.reviewColor.value.cgColor
view.layer.borderWidth = 1.0
reviewTitle.backgroundColor = reviewEngine.reviewColor.value
reviewTitle.text = reviewEngine.reviewTitle.value
}
func wireUp() {
reviewLabel.reactive.text <~ reviewEngine.toReviewCount.map { "\($0)" }
submitLabel.reactive.text <~ reviewEngine.toSubmitCount.map { "\($0)" }
reviewStarter = ReviewStarter(control: reviewButton,
action: reviewEngine.reviewAction,
inputProperty: reviewEngine.reviewEntries)
cancelButton.reactive.isEnabled <~ reviewEngine.cancelAction.isEnabled
cancelButton.tapReact { [weak self] _ in
self?.cancelOrConfirm()
}
reviewStarter?.useHUD()
reviewStarter?.action.uiReact { [weak self] (response: Response) in
guard let model = response.model as? CardDataModel else { return }
self?.presentPagedReview(model: model)
}
reviewEngine.reviewState.uiReact { [weak self] state in
self?.refreshCharts(state: state)
}
score <~ reviewEngine.reviewState.map(ReviewViewController.scoreFromState)
scoreLabel.reactive.text <~ score.map { (pct:Int?) -> String in
guard let pct = pct else { return "-" }
return "\(pct)%"
}
performanceEmoji.reactive.text <~ score.map(ReviewViewController.emojiRatingFromScore)
let pendingCount = reviewEngine.toSubmitCount.zip(with: reviewEngine.toReviewCount).map({ (a,b) -> Int in
a + b
})
cancelButton.reactive.title(for: .normal) <~ pendingCount.map { ReviewViewController.cancelButtonFromPending($0) }
if let srsEngine = reviewEngine as? SRSEngineProtocol {
submitStarter = SubmitStarter(control: submitButton,
action: srsEngine.submitAction,
inputProperty: reviewEngine.reviewEntries)
performanceEmoji.reactive.isHidden <~ srsEngine.isSubmitting
srsEngine.isSubmitting.uiReact { [weak self] submitting in
if submitting {
self?.activityIndicator.startAnimating()
} else {
self?.activityIndicator.stopAnimating()
SwiftRater.check()
}
}
} else {
submitButton.isEnabled = false
}
}
private func presentPagedReview(model: CardDataModel) {
let pagedReviewVC = PagedReviewViewController()
pagedReviewVC.cards = model.cards
pagedReviewVC.delegate = reviewDelegate
pagedReviewVC.reviewEngine = reviewEngine
pagedReviewVC.modalPresentationStyle = .custom
pagedReviewVC.modalTransitionStyle = .crossDissolve
self.present(pagedReviewVC, animated: global.useAnimations, completion: nil)
}
private func cancelOrConfirm() {
let pending = reviewEngine.toSubmitCount.value
if pending > 0 {
confirm(title: "Cancel session",
message: "You have \(pending) unsubmitted answers!",
yesOption: "Cancel anyway",
noOption: "OMG stay!") {
[unowned self] _ in
self.reviewContainer.isHidden = true
self.reviewEngine.cancelAction.apply(true).start()
}
} else {
reviewContainer.isHidden = true
reviewEngine.cancelAction.apply(true).start()
}
}
// MARK: - charts
private func refreshCharts(state: ReviewState?) {
loadPerformanceData(state: state)
performanceChart.reloadData()
submissionChart.reloadData()
}
private func loadPerformanceData(state: ReviewState?) {
performanceDataSource.set(yesCount: state?.answeredYes ?? 0,
noCount: state?.answeredNo ?? 0,
otherCount: state?.answeredOther ?? 0,
unansweredCount: state?.totalUnanswered ?? 0)
let submitted = state?.totalSubmitted ?? 0
let total = state?.totalCards ?? 0
submissionDataSource.set(submitted: submitted, total: total)
}
}
| mit | 1f10e09eb3fdf5b64e1b675722896873 | 34.494845 | 122 | 0.610805 | 4.904558 | false | false | false | false |
lwg123/swift_LWGWB | LWGWB/LWGWB/classes/Home/PhotoBrowser/PhotoBrowserViewCell.swift | 1 | 3506 | //
// PhotoBrowserViewCell.swift
// LWGWB
//
// Created by weiguang on 2017/5/10.
// Copyright © 2017年 weiguang. All rights reserved.
//
import UIKit
import SDWebImage
protocol PhotoBrowserViewCellDelegate : NSObjectProtocol {
func imageViewClick()
}
class PhotoBrowserViewCell: UICollectionViewCell {
// MARK: - 定义属性
var picURL: URL? {
didSet {
setupURL(picURL: picURL)
}
}
// MARK: - 懒加载属性
lazy var scrollView: UIScrollView = UIScrollView()
lazy var imageView: UIImageView = UIImageView()
lazy var progressView: ProgressView = ProgressView()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var delegate: PhotoBrowserViewCellDelegate?
}
extension PhotoBrowserViewCell {
//
fileprivate func setupUI() {
contentView.addSubview(scrollView)
contentView.addSubview(progressView)
scrollView.addSubview(imageView)
// 设置子控件frame
scrollView.frame = contentView.bounds
// scrollView的frame设置为和屏幕一样大,因contentView.bounds加了20,此处减去20
scrollView.frame.size.width -= 20
progressView.bounds = CGRect(x: 0, y: 0, width: 50, height: 50)
progressView.center = CGPoint(x: SCREEN_WIDTH * 0.5, y: SCREEN_HEIGHT * 0.5)
// 设置控件属性
progressView.isHidden = true
// 设置背景颜色为透明
progressView.backgroundColor = UIColor.clear
// 给imageView添加手势
let tapGes = UITapGestureRecognizer(target: self, action: #selector(imageViewClick))
imageView.addGestureRecognizer(tapGes)
imageView.isUserInteractionEnabled = true
}
}
// 监听事件点击
extension PhotoBrowserViewCell {
@objc fileprivate func imageViewClick() {
delegate?.imageViewClick()
}
}
extension PhotoBrowserViewCell {
fileprivate func setupURL(picURL: URL?) {
guard let picURL = picURL else {
return
}
// 取出image对象
let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picURL.absoluteString)!
// 计算imageView的frame
let width = SCREEN_WIDTH
let height = width / image.size.width * image.size.height
var y: CGFloat = 0
if height > SCREEN_HEIGHT {
y = 0
} else {
y = (SCREEN_HEIGHT - height) * 0.5
}
imageView.frame = CGRect(x: 0, y: y, width: width, height: height)
// 设置大图
progressView.isHidden = false
imageView.sd_setImage( with: getBigURL(smallURL: picURL), placeholderImage: image, options: [], progress: {[weak self] (current, total) in
self?.progressView.progress = CGFloat(current) / CGFloat(total)
}) { [weak self](_, _, _, _) in
self?.progressView.isHidden = true
}
scrollView.contentSize = CGSize(width: 0, height: height)
}
fileprivate func getBigURL(smallURL: URL) -> URL {
let smallURLString = smallURL.absoluteString
let bigURLString = smallURLString.replacingOccurrences(of: "thumbnail", with: "bmiddle")
return URL(string: bigURLString)!
}
}
| mit | 596a93be371029e340561947575eef39 | 27.260504 | 146 | 0.615225 | 4.638621 | false | false | false | false |
alblue/swift | stdlib/public/SDK/Foundation/NSRange.swift | 5 | 7580 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSRange : Hashable {
public var hashValue: Int {
#if arch(i386) || arch(arm)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 16)))
#elseif arch(x86_64) || arch(arm64)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 32)))
#endif
}
public static func==(lhs: NSRange, rhs: NSRange) -> Bool {
return lhs.location == rhs.location && lhs.length == rhs.length
}
}
extension NSRange : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { return "{\(location), \(length)}" }
public var debugDescription: String {
guard location != NSNotFound else {
return "{NSNotFound, \(length)}"
}
return "{\(location), \(length)}"
}
}
extension NSRange {
public init?(_ string: __shared String) {
var savedLocation = 0
if string.isEmpty {
// fail early if the string is empty
return nil
}
let scanner = Scanner(string: string)
let digitSet = CharacterSet.decimalDigits
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// fail early if there are no decimal digits
return nil
}
var location = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&location) else {
return nil
}
if scanner.isAtEnd {
// return early if there are no more characters after the first int in the string
return nil
}
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
location = integral
}
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// return early if there are no integer characters after the first int in the string
return nil
}
var length = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&length) else {
return nil
}
if !scanner.isAtEnd {
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
length = integral
}
}
self.init(location: location, length: length)
}
}
extension NSRange {
public var lowerBound: Int { return location }
public var upperBound: Int { return location + length }
public func contains(_ index: Int) -> Bool { return (!(index < location) && (index - location) < length) }
public mutating func formUnion(_ other: NSRange) {
self = union(other)
}
public func union(_ other: NSRange) -> NSRange {
let max1 = location + length
let max2 = other.location + other.length
let maxend = (max1 < max2) ? max2 : max1
let minloc = location < other.location ? location : other.location
return NSRange(location: minloc, length: maxend - minloc)
}
public func intersection(_ other: NSRange) -> NSRange? {
let max1 = location + length
let max2 = other.location + other.length
let minend = (max1 < max2) ? max1 : max2
if other.location <= location && location < max2 {
return NSRange(location: location, length: minend - location)
} else if location <= other.location && other.location < max1 {
return NSRange(location: other.location, length: minend - other.location);
}
return nil
}
}
//===----------------------------------------------------------------------===//
// Ranges
//===----------------------------------------------------------------------===//
extension NSRange {
public init<R: RangeExpression>(_ region: R)
where R.Bound: FixedWidthInteger {
let r = region.relative(to: 0..<R.Bound.max)
self.init(location: numericCast(r.lowerBound), length: numericCast(r.count))
}
public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S)
where R.Bound == S.Index {
let r = region.relative(to: target)
self.init(target._toUTF16Offsets(r))
}
@available(swift, deprecated: 4, renamed: "Range.init(_:)")
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
}
extension Range where Bound: BinaryInteger {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound)))
}
}
// This additional overload will mean Range.init(_:) defaults to Range<Int> when
// no additional type context is provided:
extension Range where Bound == Int {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (range.lowerBound, range.upperBound))
}
}
extension Range where Bound == String.Index {
public init?(_ range: NSRange, in string: __shared String) {
let u = string.utf16
guard range.location != NSNotFound,
let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
let lowerBound = String.Index(start, within: string),
let upperBound = String.Index(end, within: string)
else { return nil }
self = lowerBound..<upperBound
}
}
extension NSRange : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["location": location, "length": length])
}
}
extension NSRange : _CustomPlaygroundQuickLookable {
@available(*, deprecated, message: "NSRange.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .range(Int64(location), Int64(length))
}
}
extension NSRange : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let location = try container.decode(Int.self)
let length = try container.decode(Int.self)
self.init(location: location, length: length)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.location)
try container.encode(self.length)
}
} | apache-2.0 | 9cca572fbcbc0d26cc01d7b748e2efd5 | 33.935484 | 117 | 0.593799 | 4.746399 | false | false | false | false |
mintrocket/MRKit | MRKit/Classes/Backend/Core/Network/NetworkService.swift | 1 | 6627 | //
// NetworkService.swift
// MRKit
//
// Created by Kirill Kunst on 05/08/16.
// Copyright © 2016 MintRocket LLC. All rights reserved.
//
import Foundation
import Alamofire
import RxSwift
open class NetworkService: Loggable {
public typealias MultiPartData = (item: Data, fileName: String, mimeType: String)
public typealias NetworkResponse = (Data, Int, HTTPURLResponse?, URLRequest?)
public var defaultLoggingTag: LogTag {
return .Service
}
fileprivate static let requestTimeout : Double = 10
fileprivate var task: URLSessionTask?
public var successCodes: CountableRange<Int> = 200..<299
public var failureCodes: CountableRange<Int> = 400..<499
fileprivate var manager: Alamofire.SessionManager!
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
init() {
self.manager = Alamofire.SessionManager(configuration: self.configuration())
}
fileprivate func configuration() -> URLSessionConfiguration {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = NetworkService.requestTimeout
configuration.timeoutIntervalForRequest = NetworkService.requestTimeout
return configuration
}
func request(url: URL, method: Method,
params: [String: AnyObject]? = nil,
headers: [String: String]? = nil) -> Observable<NetworkResponse> {
let request = self.createRequest(url: url,
method: method,
params: params,
headers: headers)
return Observable.create({ (observer) -> Disposable in
let request = self.manager.request(request)
self.log(.debug, "Request: \(request)")
self.task = request.task
request.response(completionHandler: { (response) in
if (response.error != nil) {
observer.on(.error(response.error!))
} else if (response.response != nil) {
observer.on(.next((response.data!,response.response!.statusCode, response.response, response.request)))
observer.on(.completed)
} else {
observer.on(.error(AppError.networkError(code: MRKitErrorCode.unknownNetworkError)))
}
})
return Disposables.create()
})
}
func upload(data: [String : MultiPartData],
url: URL,
method: Method,
params: [String: AnyObject]? = nil,
headers: [String: String]? = nil) -> Observable<NetworkResponse> {
let request = self.createRequest(url: url,
method: method,
params: params,
headers: headers)
return Observable.create({ (observer) -> Disposable in
let multiPartAction: (MultipartFormData) -> () = {
(multipartFormData) in
for (key, value) in data {
multipartFormData.append(value.item, withName: key, fileName: value.fileName, mimeType: value.mimeType)
}
if params != nil {
for (key, value) in params! {
multipartFormData.append("\(value)".data(using: .utf8)!, withName: key)
}
}
}
let encodingCompletion: (SessionManager.MultipartFormDataEncodingResult) -> () = {
(result) in
switch result {
case .success(let request, _, _):
self.log(.debug, "Request: \(request)")
self.task = request.task
request.response(completionHandler: { (response) in
if (response.error != nil) {
observer.on(.error(response.error!))
} else if (response.response != nil) {
observer.on(.next((response.data!,response.response!.statusCode, response.response, response.request)))
observer.on(.completed)
} else {
observer.on(.error(AppError.networkError(code: MRKitErrorCode.unknownNetworkError)))
}
})
break
case .failure(let error):
self.log(.error, "Request: \(error)")
observer.on(.error(error))
break
}
}
self.manager.upload(multipartFormData: multiPartAction,
with: request,
encodingCompletion: encodingCompletion)
return Disposables.create()
})
}
func addJSONContentType(request: inout URLRequest) {
if (request.allHTTPHeaderFields == nil) {
request.allHTTPHeaderFields = [:]
}
request.allHTTPHeaderFields!["Content-type"] = "application/json"
}
func createRequest(url: URL, method: Method,
params: [String: AnyObject]?,
headers: [String: String]?) -> URLRequest {
let requestURL: URL?
if (params != nil) {
let parameterString = params!.stringFromHttpParameters()
requestURL = URL(string:"\(url)?\(parameterString)")!
} else {
requestURL = url as URL
}
var request = URLRequest(url: requestURL!,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: NetworkService.requestTimeout)
request.allHTTPHeaderFields = headers
request.httpMethod = method.rawValue
if (method != .GET && params != nil) {
do {
let bodyData = try JSONSerialization.data(withJSONObject: params!, options: [])
request.httpBody = bodyData
self.addJSONContentType(request: &request)
} catch {
self.log(.error, "Body data serialisazion error: \(error)")
}
}
return request
}
func cancel() {
task?.cancel()
}
}
| mit | 2d7dc361f6dcf227948c16c5540d0fad | 37.748538 | 131 | 0.51811 | 5.751736 | false | true | false | false |
cacawai/Tap2Read | tap2read/Pods/SugarRecord/SugarRecord/Source/CoreData/Entities/CoreDataObservable.swift | 1 | 3234 | import Foundation
import CoreData
#if os(iOS) || os(tvOS) || os(watchOS)
public class CoreDataObservable<T: NSManagedObject>: RequestObservable<T>, NSFetchedResultsControllerDelegate where T:Equatable {
// MARK: - Attributes
internal let fetchRequest: NSFetchRequest<NSFetchRequestResult>
internal var observer: ((ObservableChange<T>) -> Void)?
internal let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>
private var batchChanges: [CoreDataChange<T>] = []
// MARK: - Init
internal init(request: FetchRequest<T>, context: NSManagedObjectContext) {
let fetchRequest: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: T.entityName)
if let predicate = request.predicate {
fetchRequest.predicate = predicate
}
if let sortDescriptor = request.sortDescriptor {
fetchRequest.sortDescriptors = [sortDescriptor]
}
fetchRequest.fetchBatchSize = 0
self.fetchRequest = fetchRequest
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
super.init(request: request)
self.fetchedResultsController.delegate = self
}
// MARK: - Observable
public override func observe(_ closure: @escaping (ObservableChange<T>) -> Void) {
assert(self.observer == nil, "Observable can be observed only once")
let initial = try! self.fetchedResultsController.managedObjectContext.fetch(self.fetchRequest) as! [T]
closure(ObservableChange.initial(initial))
self.observer = closure
_ = try? self.fetchedResultsController.performFetch()
}
// MARK: - Dipose Method
override func dispose() {
self.fetchedResultsController.delegate = nil
}
// MARK: - NSFetchedResultsControllerDelegate
@nonobjc public func controller(controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeObject anObject: AnyObject, atIndexPath indexPath: IndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .delete:
self.batchChanges.append(.delete(indexPath![0], anObject as! T))
case .insert:
self.batchChanges.append(.insert(newIndexPath![0], anObject as! T))
case .update:
self.batchChanges.append(.update(indexPath![0], anObject as! T))
default: break
}
}
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.batchChanges = []
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
let deleted = self.batchChanges.filter { $0.isDeletion }.map { $0.index() }
let inserted = self.batchChanges.filter { $0.isInsertion }.map { (index: $0.index(), element: $0.object()) }
let updated = self.batchChanges.filter { $0.isUpdate }.map { (index: $0.index(), element: $0.object()) }
self.observer?(ObservableChange.update(deletions: deleted, insertions: inserted, modifications: updated))
}
}
#endif
| mit | 5c89d0f25ddeb89ed628fd609e5ccd59 | 40.461538 | 245 | 0.700062 | 5.182692 | false | false | false | false |
swift-tweets/tweetup-kit | Sources/TweetupKit/Tweet.swift | 1 | 3391 | import Foundation
public struct Tweet {
internal static let urlPattern = try! NSRegularExpression(pattern: "(^|\\s)((http(s)?://)?[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)+(/[a-zA-Z0-9~!@#$%&*\\-_=+\\[\\]|:;',./?]*)?)($|\\s)")
internal static let urlLength = 23
internal static let maxLength = 140
public let body: String
public let attachment: Attachment?
public init(body: String, attachment: Attachment? = nil) throws {
guard !body.isEmpty || attachment != nil else { throw TweetInitializationError.empty }
self.body = body
self.attachment = attachment
let length = self.length
guard length <= Tweet.maxLength else { throw TweetInitializationError.tooLong(self.body, self.attachment, length) }
}
public var length: Int {
let replaced = NSMutableString(string: body)
let numberOfUrls = Tweet.urlPattern.replaceMatches(in: replaced, options: [], range: NSMakeRange(0, replaced.length), withTemplate: "$1$7")
let normalized = replaced.precomposedStringWithCanonicalMapping as NSString
var bodyLength = normalized.length + Tweet.urlLength * numberOfUrls
do {
let buffer = UnsafeMutablePointer<unichar>.allocate(capacity: normalized.length)
defer {
buffer.deallocate(capacity: normalized.length)
}
normalized.getCharacters(buffer)
var skip = false
let end = normalized.length - 1
if end > 1 {
for i in 0..<end { // lack of the last element for `i + 1`
guard !skip else {
skip = false
continue
}
if CFStringIsSurrogateHighCharacter(buffer[i])
&& CFStringIsSurrogateLowCharacter(buffer[i + 1]) {
bodyLength -= 1
skip = true
}
}
}
}
guard let attachment = attachment else { return bodyLength }
switch attachment {
case .code:
return bodyLength + 2 /* new lines */ + Tweet.urlLength
case .image:
return bodyLength
}
}
public enum Attachment {
case image(Image)
case code(Code)
}
}
extension Tweet: CustomStringConvertible {
public var description: String {
guard let attachment = attachment else { return body }
switch attachment {
case let .image(image):
return "\(body)\n\n\(image)"
case let .code(code):
return "\(body)\n\n\(code)"
}
}
}
extension Tweet: Equatable {
public static func ==(lhs: Tweet, rhs: Tweet) -> Bool {
return lhs.body == rhs.body && lhs.attachment == rhs.attachment
}
}
extension Tweet.Attachment: Equatable {
public static func ==(lhs: Tweet.Attachment, rhs: Tweet.Attachment) -> Bool {
switch (lhs, rhs) {
case let (.image(image1), .image(image2)):
return image1 == image2
case let (.code(code1), .code(code2)):
return code1 == code2
case (_, _):
return false
}
}
}
public enum TweetInitializationError: Error {
case empty
case tooLong(String, Tweet.Attachment?, Int)
}
| mit | b54981b5f97e27f0ee3b574f1ef9675b | 32.574257 | 184 | 0.552934 | 4.709722 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/URLRequest.swift | 1 | 10106 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public struct URLRequest : ReferenceConvertible, CustomStringConvertible, Equatable, Hashable {
public typealias ReferenceType = NSURLRequest
public typealias CachePolicy = NSURLRequest.CachePolicy
public typealias NetworkServiceType = NSURLRequest.NetworkServiceType
/*
NSURLRequest has a fragile ivar layout that prevents the swift subclass approach here, so instead we keep an always mutable copy
*/
internal var _handle: _MutableHandle<NSMutableURLRequest>
internal mutating func _applyMutation<ReturnType>(_ whatToDo : @noescape (NSMutableURLRequest) -> ReturnType) -> ReturnType {
if !isUniquelyReferencedNonObjC(&_handle) {
let ref = _handle._uncopiedReference()
_handle = _MutableHandle(reference: ref)
}
return whatToDo(_handle._uncopiedReference())
}
/// Creates and initializes a URLRequest with the given URL and cache policy.
/// - parameter: url The URL for the request.
/// - parameter: cachePolicy The cache policy for the request. Defaults to `.useProtocolCachePolicy`
/// - parameter: timeoutInterval The timeout interval for the request. See the commentary for the `timeoutInterval` for more information on timeout intervals. Defaults to 60.0
public init(url: URL, cachePolicy: CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 60.0) {
_handle = _MutableHandle(adoptingReference: NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval))
}
private init(_bridged request: NSURLRequest) {
_handle = _MutableHandle(reference: request.mutableCopy() as! NSMutableURLRequest)
}
/// The URL of the receiver.
public var url: URL? {
get {
return _handle.map { $0.url }
}
set {
_applyMutation { $0.url = newValue }
}
}
/// The cache policy of the receiver.
public var cachePolicy: CachePolicy {
get {
return _handle.map { $0.cachePolicy }
}
set {
_applyMutation { $0.cachePolicy = newValue }
}
}
/// Returns the timeout interval of the receiver.
/// - discussion: The timeout interval specifies the limit on the idle
/// interval alloted to a request in the process of loading. The "idle
/// interval" is defined as the period of time that has passed since the
/// last instance of load activity occurred for a request that is in the
/// process of loading. Hence, when an instance of load activity occurs
/// (e.g. bytes are received from the network for a request), the idle
/// interval for a request is reset to 0. If the idle interval ever
/// becomes greater than or equal to the timeout interval, the request
/// is considered to have timed out. This timeout interval is measured
/// in seconds.
public var timeoutInterval: TimeInterval {
get {
return _handle.map { $0.timeoutInterval }
}
set {
_applyMutation { $0.timeoutInterval = newValue }
}
}
/// The main document URL associated with this load.
/// - discussion: This URL is used for the cookie "same domain as main
/// document" policy.
public var mainDocumentURL: URL? {
get {
return _handle.map { $0.mainDocumentURL }
}
set {
_applyMutation { $0.mainDocumentURL = newValue }
}
}
/// The URLRequest.NetworkServiceType associated with this request.
/// - discussion: This will return URLRequest.NetworkServiceType.default for requests that have
/// not explicitly set a networkServiceType
public var networkServiceType: NetworkServiceType {
get {
return _handle.map { $0.networkServiceType }
}
set {
_applyMutation { $0.networkServiceType = newValue }
}
}
/// `true` if the receiver is allowed to use the built in cellular radios to
/// satify the request, `false` otherwise.
public var allowsCellularAccess: Bool {
get {
return _handle.map { $0.allowsCellularAccess }
}
set {
_applyMutation { $0.allowsCellularAccess = newValue }
}
}
/// The HTTP request method of the receiver.
public var httpMethod: String? {
get {
return _handle.map { $0.httpMethod }
}
set {
_applyMutation {
if let value = newValue {
$0.httpMethod = value
} else {
$0.httpMethod = "GET"
}
}
}
}
/// A dictionary containing all the HTTP header fields of the
/// receiver.
public var allHTTPHeaderFields: [String : String]? {
get {
return _handle.map { $0.allHTTPHeaderFields }
}
set {
_applyMutation { $0.allHTTPHeaderFields = newValue }
}
}
/// The value which corresponds to the given header
/// field. Note that, in keeping with the HTTP RFC, HTTP header field
/// names are case-insensitive.
/// - parameter: field the header field name to use for the lookup (case-insensitive).
public func value(forHTTPHeaderField field: String) -> String? {
return _handle.map { $0.value(forHTTPHeaderField: field) }
}
/// If a value was previously set for the given header
/// field, that value is replaced with the given value. Note that, in
/// keeping with the HTTP RFC, HTTP header field names are
/// case-insensitive.
public mutating func setValue(_ value: String?, forHTTPHeaderField field: String) {
_applyMutation {
$0.setValue(value, forHTTPHeaderField: field)
}
}
/// This method provides a way to add values to header
/// fields incrementally. If a value was previously set for the given
/// header field, the given value is appended to the previously-existing
/// value. The appropriate field delimiter, a comma in the case of HTTP,
/// is added by the implementation, and should not be added to the given
/// value by the caller. Note that, in keeping with the HTTP RFC, HTTP
/// header field names are case-insensitive.
public mutating func addValue(_ value: String, forHTTPHeaderField field: String) {
_applyMutation {
$0.addValue(value, forHTTPHeaderField: field)
}
}
/// This data is sent as the message body of the request, as
/// in done in an HTTP POST request.
public var httpBody: Data? {
get {
return _handle.map { $0.httpBody }
}
set {
_applyMutation { $0.httpBody = newValue }
}
}
/// The stream is returned for examination only; it is
/// not safe for the caller to manipulate the stream in any way. Also
/// note that the HTTPBodyStream and HTTPBody are mutually exclusive - only
/// one can be set on a given request. Also note that the body stream is
/// preserved across copies, but is LOST when the request is coded via the
/// NSCoding protocol
public var httpBodyStream: InputStream? {
get {
return _handle.map { $0.httpBodyStream }
}
set {
_applyMutation { $0.httpBodyStream = newValue }
}
}
/// `true` if cookies will be sent with and set for this request; otherwise `false`.
public var httpShouldHandleCookies: Bool {
get {
return _handle.map { $0.httpShouldHandleCookies }
}
set {
_applyMutation { $0.httpShouldHandleCookies = newValue }
}
}
/// `true` if the receiver should transmit before the previous response
/// is received. `false` if the receiver should wait for the previous response
/// before transmitting.
public var httpShouldUsePipelining: Bool {
get {
return _handle.map { $0.httpShouldUsePipelining }
}
set {
_applyMutation { $0.httpShouldUsePipelining = newValue }
}
}
public var hashValue: Int {
return _handle.map { $0.hashValue }
}
public var description: String {
return _handle.map { $0.description }
}
public var debugDescription: String {
return _handle.map { $0.debugDescription }
}
}
public func ==(lhs: URLRequest, rhs: URLRequest) -> Bool {
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
extension URLRequest {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSURLRequest.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLRequest {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) {
result = URLRequest(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) -> Bool {
result = URLRequest(_bridged: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLRequest?) -> URLRequest {
var result: URLRequest? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| apache-2.0 | 73c241f7e7ce358434e1f1018c4807fd | 36.42963 | 179 | 0.619137 | 5.114372 | false | false | false | false |
benlangmuir/swift | test/Generics/connected_components_concrete.swift | 6 | 1503 | // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s
protocol P {
associatedtype T
}
protocol Base {
associatedtype A
associatedtype B
associatedtype C
associatedtype D : P where B == D.T
}
// CHECK-LABEL: connected_components_concrete.(file).Derived1@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived1 : Base where A == B, A == C, A == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived2@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived2 : Base where A == D.T, A == C, B == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived3@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived3 : Base where A == B, B == C, A == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived4@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived4 : Base where A == Int, B == Int, C == Int {}
// CHECK-LABEL: connected_components_concrete.(file).Derived5@
// CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int>
protocol Derived5 : Base where A == Int, D.T == Int, C == Int {}
| apache-2.0 | 913b7fc613e32558b68eb42bfead96c8 | 45.96875 | 126 | 0.669328 | 3.310573 | false | false | false | false |
narikbi/LeetCode | source/252.swift | 1 | 827 | import UIKit
public class Interval {
public var start: Int
public var end: Int
public init(_ start: Int, _ end: Int) {
self.start = start
self.end = end
}
}
class Solution {
func canAttendMeetings(_ intervals: [Interval]) -> Bool {
if intervals.count < 2 {
return true
}
let sorted = intervals.sorted { (r, l) -> Bool in
return r.start < l.start || (r.start == l.start && r.end < l.end)
}
var cur = sorted[0]
for (i, element) in sorted.enumerated() {
cur = element
if i != sorted.count-1 {
let next = sorted[i+1]
if cur.end > next.start {
return false
}
}
}
return true
}
} | mit | 425df3c42f805791aa3da26edceb378b | 22 | 77 | 0.461911 | 4.155779 | false | false | false | false |
wattson12/Moya | Source/Moya.swift | 2 | 13189 | import Foundation
import Result
/// Closure to be executed when a request has completed.
public typealias Completion = (result: Result<Moya.Response, Moya.Error>) -> ()
/// Represents an HTTP method.
public enum Method: String {
case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT
}
public enum StubBehavior {
case Never
case Immediate
case Delayed(seconds: NSTimeInterval)
}
/// Protocol to define the base URL, path, method, parameters and sample data for a target.
public protocol TargetType {
var baseURL: NSURL { get }
var path: String { get }
var method: Moya.Method { get }
var parameters: [String: AnyObject]? { get }
var sampleData: NSData { get }
}
public enum StructTarget: TargetType {
case Struct(TargetType)
public init(_ target: TargetType) {
self = StructTarget.Struct(target)
}
public var path: String {
return target.path
}
public var baseURL: NSURL {
return target.baseURL
}
public var method: Moya.Method {
return target.method
}
public var parameters: [String: AnyObject]? {
return target.parameters
}
public var sampleData: NSData {
return target.sampleData
}
public var target: TargetType {
switch self {
case .Struct(let t): return t
}
}
}
/// Protocol to define the opaque type returned from a request
public protocol Cancellable {
func cancel()
}
/// Request provider class. Requests should be made through this class only.
public class MoyaProvider<Target: TargetType> {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = Target -> Endpoint<Target>
/// Closure that decides if and what request should be performed
public typealias RequestResultClosure = Result<NSURLRequest, Moya.Error> -> Void
/// Closure that resolves an Endpoint into an RequestResult.
public typealias RequestClosure = (Endpoint<Target>, RequestResultClosure) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = Target -> Moya.StubBehavior
public let endpointClosure: EndpointClosure
public let requestClosure: RequestClosure
public let stubClosure: StubClosure
public let manager: Manager
/// A list of plugins
/// e.g. for logging, network activity indicator or credentials
public let plugins: [PluginType]
public let trackInflights:Bool
public private(set) var inflightRequests = Dictionary<Endpoint<Target>, [Moya.Completion]>()
/// Initializes a provider.
public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = MoyaProvider<Target>.DefaultAlamofireManager(),
plugins: [PluginType] = [],
trackInflights:Bool = false) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.manager = manager
self.plugins = plugins
self.trackInflights = trackInflights
}
/// Returns an Endpoint based on the token, method, and parameters by invoking the endpointsClosure.
public func endpoint(token: Target) -> Endpoint<Target> {
return endpointClosure(token)
}
/// Designated request-making method with queue option. Returns a Cancellable token to cancel the request later.
public func request(target: Target, queue:dispatch_queue_t?, completion: Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
var cancellableToken = CancellableWrapper()
if trackInflights {
objc_sync_enter(self)
var inflightCompletionBlocks = self.inflightRequests[endpoint]
inflightCompletionBlocks?.append(completion)
self.inflightRequests[endpoint] = inflightCompletionBlocks
objc_sync_exit(self)
if inflightCompletionBlocks != nil {
return cancellableToken
} else {
objc_sync_enter(self)
self.inflightRequests[endpoint] = [completion]
objc_sync_exit(self)
}
}
let performNetworking = { (requestResult: Result<NSURLRequest, Moya.Error>) in
if cancellableToken.isCancelled { return }
var request: NSURLRequest!
switch requestResult {
case .Success(let urlRequest):
request = urlRequest
case .Failure(let error):
completion(result: .Failure(error))
return
}
switch stubBehavior {
case .Never:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, queue: queue, completion: { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
})
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
}, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
/// Designated request-making method. Returns a Cancellable token to cancel the request later.
public func request(target: Target, completion: Moya.Completion) -> Cancellable {
return self.request(target, queue:nil, completion:completion)
}
/// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method.
/// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override.
internal func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken {
let cancellableToken = CancellableToken { }
notifyPluginsOfImpendingStub(request, target: target)
let plugins = self.plugins
let stub: () -> () = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins)
switch stubBehavior {
case .Immediate:
stub()
case .Delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset)
dispatch_after(killTime, dispatch_get_main_queue()) {
stub()
}
case .Never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
}
/// Mark: Defaults
public extension MoyaProvider {
// These functions are default mappings to MoyaProvider's properties: endpoints, requests, manager, etc.
public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: RequestResultClosure) {
return closure(.Success(endpoint.urlRequest))
}
public final class func DefaultAlamofireManager() -> Manager {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
let manager = Manager(configuration: configuration)
manager.startRequestsImmediately = false
return manager
}
}
/// Mark: Stubbing
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
public final class func NeverStub(_: Target) -> Moya.StubBehavior {
return .Never
}
public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior {
return .Immediate
}
public final class func DelayedStub(seconds: NSTimeInterval) -> (Target) -> Moya.StubBehavior {
return { _ in return .Delayed(seconds: seconds) }
}
}
internal extension MoyaProvider {
func sendRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, completion: Moya.Completion) -> CancellableToken {
let alamoRequest = manager.request(request)
let plugins = self.plugins
// Give plugins the chance to alter the outgoing request
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
// Perform the actual request
alamoRequest.response(queue: queue) { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in
let result = convertResponseToResult(response, data: data, error: error)
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(result, target: target) }
completion(result: result)
}
alamoRequest.resume()
return CancellableToken(request: alamoRequest)
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
internal final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) {
return {
if (token.canceled) {
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
return
}
switch endpoint.sampleResponseClosure() {
case .NetworkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, response: nil)
plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) }
completion(result: .Success(response))
case .NetworkError(let error):
let error = Moya.Error.Underlying(error)
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
internal final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) {
let alamoRequest = manager.request(request)
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
}
}
public func convertResponseToResult(response: NSHTTPURLResponse?, data: NSData?, error: NSError?) ->
Result<Moya.Response, Moya.Error> {
switch (response, data, error) {
case let (.Some(response), .Some(data), .None):
let response = Moya.Response(statusCode: response.statusCode, data: data, response: response)
return .Success(response)
case let (_, _, .Some(error)):
let error = Moya.Error.Underlying(error)
return .Failure(error)
default:
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil))
return .Failure(error)
}
}
internal struct CancellableWrapper: Cancellable {
internal var innerCancellable: CancellableToken? = nil
private var isCancelled = false
internal func cancel() {
innerCancellable?.cancel()
}
}
| mit | 39134626487667127049360060e5adf4 | 38.488024 | 204 | 0.637728 | 5.378874 | false | false | false | false |
necolt/Swifton | Sources/Swifton/CookiesMiddleware.swift | 2 | 705 | import S4
public class CookiesMiddleware: Middleware {
public func respond(to request: Request, chainingTo next: Responder) throws -> Response {
var newRequest = request
if let rawCookie = newRequest.headers["Cookie"].values.first {
let cookiePairs = rawCookie.split(separator: ";")
for cookie in cookiePairs {
let keyValue = cookie.split(separator: "=")
newRequest.cookies[keyValue[0]] = keyValue[1]
}
}
var response = try next.respond(to: newRequest)
response.headers["Set-Cookie"] = Header(response.cookies.map { "\($0)=\($1)" }.joined(separator: ";"))
return response
}
}
| mit | a0d713f7936aac28188f63d09e73f346 | 32.571429 | 110 | 0.602837 | 4.607843 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCMarketGroupsViewController.swift | 2 | 3308 | //
// NCMarketGroupsViewController.swift
// Neocom
//
// Created by Artem Shimanski on 21.06.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCMarketGroupRow: NCFetchedResultsObjectNode<NCDBInvMarketGroup> {
required init(object: NCDBInvMarketGroup) {
super.init(object: object)
cellIdentifier = Prototype.NCDefaultTableViewCell.compact.reuseIdentifier
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = object.marketGroupName
cell.iconView?.image = object.icon?.image?.image ?? NCDBEveIcon.defaultGroup.image?.image
cell.accessoryType = .disclosureIndicator
}
}
class NCMarketGroupsViewController: NCTreeViewController, NCSearchableViewController {
var parentGroup: NCDBInvMarketGroup?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCHeaderTableViewCell.default,
Prototype.NCDefaultTableViewCell.compact])
setupSearchController(searchResultsController: self.storyboard!.instantiateViewController(withIdentifier: "NCDatabaseTypesViewController"))
title = parentGroup?.marketGroupName ?? NSLocalizedString("Browse", comment: "")
}
override func content() -> Future<TreeNode?> {
let request = NSFetchRequest<NCDBInvMarketGroup>(entityName: "InvMarketGroup")
request.sortDescriptors = [NSSortDescriptor(key: "marketGroupName", ascending: true)]
if let parent = parentGroup {
request.predicate = NSPredicate(format: "parentGroup == %@", parent)
}
else {
request.predicate = NSPredicate(format: "parentGroup == NULL")
}
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: NCDatabase.sharedDatabase!.viewContext, sectionNameKeyPath: nil, cacheName: nil)
try? results.performFetch()
return .init(FetchedResultsNode(resultsController: results, sectionNode: nil, objectNode: NCMarketGroupRow.self))
}
override func didReceiveMemoryWarning() {
if !isViewLoaded || view.window == nil {
treeController?.content = nil
}
}
//MARK: - TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
guard let row = node as? NCMarketGroupRow else {return}
if (row.object.types?.count ?? 0) > 0 {
Router.Database.Types(marketGroup: row.object).perform(source: self, sender: treeController.cell(for: node))
}
else {
Router.Database.MarketGroups(parentGroup: row.object).perform(source: self, sender: treeController.cell(for: node))
}
}
//MARK: - NCSearchableViewController
var searchController: UISearchController?
func updateSearchResults(for searchController: UISearchController) {
let predicate: NSPredicate
guard let controller = searchController.searchResultsController as? NCDatabaseTypesViewController else {return}
if let text = searchController.searchBar.text, text.count > 2 {
predicate = NSPredicate(format: "marketGroup != NULL AND typeName CONTAINS[C] %@", text)
}
else {
predicate = NSPredicate(value: false)
}
controller.predicate = predicate
controller.reloadData()
}
}
| lgpl-2.1 | 40464214cd9d52076a0944b5aa8d864e | 33.092784 | 168 | 0.762322 | 4.380132 | false | false | false | false |
DanielAsher/SwiftCheck | SwiftCheck/Test.swift | 2 | 37268 | //
// Test.swift
// SwiftCheck
//
// Created by Robert Widmann on 7/31/14.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
// MARK: - Property Testing with SwiftCheck
/// Property Testing is a more static and expressive form of Test-Driven Development that emphasizes
/// the testability of program properties - A statement or invariant that can be proven to hold when
/// fed any number of arguments of a particular kind. It is akin to Fuzz Testing but is made
/// significantly more powerful by the primitives in this framework.
///
/// A `Property` in SwiftCheck is more than just `true` and `false`, it is a value that is capable
/// of producing a framework type called `Prop`, which models individual test cases that themselves
/// are capable of passing or failing "in the small" with a `TestResult`. For those familiar with
/// Protocol-Oriented Programming, lying at the heart of all of these types is a protocol called
/// `Testable` that provides any type a means of converting itself to a `Property`. SwiftCheck
/// uses `Testable` early and often in functions and operators to enable a high level of nesting
/// of framework primitives and an even higher level of genericity in the interface. By default
/// SwiftCheck provides `Testable` instances for `Bool`, `Property`, `Prop`, and several other
/// internal framework types. Practically, this means any assertions you could make in `XCTest`
/// will work immediately with the framework.
// MARK: - Quantifiers
/// Below is the method all SwiftCheck properties are based on, `forAll`. `forAll` acts as a
/// "Quantifier", i.e. a contract that serves as a guarantee that a property holds when the given
/// testing block returns `true` or truthy values, and fails when the testing block returns `false`
/// or falsy values. The testing block is usually used with Swift's abbreviated block syntax and
/// requires type annotations for all value positions being requested. For example,
///
/// + This is "Property Notation". It allows you to give your properties a name and instructs SwiftCheck to test it.
/// | + This backwards arrow binds a property name and a property to each other.
/// | |
/// v v
/// property("The reverse of the reverse of an array is that array") <- forAll { (xs : [Int]) in
/// return
/// (xs.reverse().reverse() == xs) <?> "Reverse on the left"
/// ^&&^
/// (xs == xs.reverse().reverse()) <?> "Reverse on the right"
/// }
///
/// Why require types? For one, Swift cannot infer the types of local variables because SwiftCheck
/// uses highly polymorphic testing primitives. But, more importantly, types are required because
/// SwiftCheck uses them to select the appropriate `Gen`erators and shrinkers for each data type
/// automagically by default. Those `Gen`erators and shrinkers are then used to create 100 random
/// test cases that are evaluated lazily to produce a final result.
// MARK: - Going Further
/// As mentioned before, SwiftCheck types do not exist in a bubble. They are highly compositional
/// and flexible enough to express unique combinations and permutations of test types. Below is a
/// purely illustrative example utilizing a significant portion of SwiftCheck's testing functions:
///
/// /// This method comes out of SwiftCheck's test suite.
///
/// `SetOf` is called a "Modifier Type". To learn more about them see `Modifiers.swift`---+
/// |
/// v
/// property("Shrunken sets of integers don't always contain [] or [0]") <- forAll { (s : SetOf<Int>) in
///
/// /// This part of the property uses `==>`, or the "implication" combinator. Implication
/// /// only executes the following block if the preceding expression returns true. It can
/// /// be used to discard test cases that contain data you don't want to test with.
/// return (!s.getSet.isEmpty && s.getSet != Set([0])) ==> {
///
/// /// N.B. `shrinkArbitrary` is a internal method call that invokes the shrinker.
/// let ls = self.shrinkArbitrary(s).map { $0.getSet }
/// return (ls.filter({ $0 == [0] || $0 == [] }).count >= 1).whenFail {
/// print("Oh noe!")
/// }
/// }
/// }.expectFailure.verbose
/// ^ ^
/// | |
/// | +--- The property will print EVERY generated test case to the console.
/// + --- We expect this property not to hold.
///
/// Testing is not limited to just these listed functions. New users should check out our test
/// suite and the files `Gen.swift`, `Property.swift`, `Modifiers.swift`, and the top half of this
/// very file to learn more about the various parts of the SwiftCheck testing mechanism.
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for that type.
@warn_unused_result
public func forAll<A : Arbitrary>(pf : (A -> Testable)) -> Property {
return forAllShrink(A.arbitrary, shrinker: A.shrink, f: pf)
}
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for 2 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary>(pf : (A, B) -> Testable) -> Property {
return forAll({ t in forAll({ b in pf(t, b) }) })
}
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for 3 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary>(pf : (A, B, C) -> Testable) -> Property {
return forAll({ t in forAll({ b, c in pf(t, b, c) }) })
}
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for 4 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary>(pf : (A, B, C, D) -> Testable) -> Property {
return forAll({ t in forAll({ b, c, d in pf(t, b, c, d) }) })
}
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for 5 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary>(pf : (A, B, C, D, E) -> Testable) -> Property {
return forAll({ t in forAll({ b, c, d, e in pf(t, b, c, d, e) }) })
}
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for 6 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary, F : Arbitrary>(pf : (A, B, C, D, E, F) -> Testable) -> Property {
return forAll({ t in forAll({ b, c, d, e, f in pf(t, b, c, d, e, f) }) })
}
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for 7 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary, F : Arbitrary, G : Arbitrary>(pf : (A, B, C, D, E, F, G) -> Testable) -> Property {
return forAll({ t in forAll({ b, c, d, e, f, g in pf(t, b, c, d, e, f, g) }) })
}
/// Converts a function into a universally quantified property using the default shrinker and
/// generator for 8 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary, F : Arbitrary, G : Arbitrary, H : Arbitrary>(pf : (A, B, C, D, E, F, G, H) -> Testable) -> Property {
return forAll({ t in forAll({ b, c, d, e, f, g, h in pf(t, b, c, d, e, f, g, h) }) })
}
/// Given an explicit generator, converts a function to a universally quantified property using the
/// default shrinker for that type.
@warn_unused_result
public func forAll<A : Arbitrary>(gen : Gen<A>, pf : (A -> Testable)) -> Property {
return forAllShrink(gen, shrinker: A.shrink, f: pf)
}
/// Given 2 explicit generators, converts a function to a universally quantified property using the
/// default shrinkers for those 2 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary>(genA : Gen<A>, _ genB : Gen<B>, pf : (A, B) -> Testable) -> Property {
return forAll(genA, pf: { t in forAll(genB, pf: { b in pf(t, b) }) })
}
/// Given 3 explicit generators, converts a function to a universally quantified property using the
/// default shrinkers for those 3 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, pf : (A, B, C) -> Testable) -> Property {
return forAll(genA, pf: { t in forAll(genB, genC, pf: { b, c in pf(t, b, c) }) })
}
/// Given 4 explicit generators, converts a function to a universally quantified property using the
/// default shrinkers for those 4 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, pf : (A, B, C, D) -> Testable) -> Property {
return forAll(genA, pf: { t in forAll(genB, genC, genD, pf: { b, c, d in pf(t, b, c, d) }) })
}
/// Given 5 explicit generators, converts a function to a universally quantified property using the
/// default shrinkers for those 5 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, pf : (A, B, C, D, E) -> Testable) -> Property {
return forAll(genA, pf: { t in forAll(genB, genC, genD, genE, pf: { b, c, d, e in pf(t, b, c, d, e) }) })
}
/// Given 6 explicit generators, converts a function to a universally quantified property using the
/// default shrinkers for those 6 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary, F : Arbitrary>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, _ genF : Gen<F>, pf : (A, B, C, D, E, F) -> Testable) -> Property {
return forAll(genA, pf: { t in forAll(genB, genC, genD, genE, genF, pf: { b, c, d, e, f in pf(t, b, c, d, e, f) }) })
}
/// Given 7 explicit generators, converts a function to a universally quantified property using the
/// default shrinkers for those 7 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary, F : Arbitrary, G : Arbitrary>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, _ genF : Gen<F>, _ genG : Gen<G>, pf : (A, B, C, D, E, F, G) -> Testable) -> Property {
return forAll(genA, pf: { t in forAll(genB, genC, genD, genE, genF, genG, pf: { b, c, d, e, f, g in pf(t, b, c, d, e, f, g) }) })
}
/// Given 8 explicit generators, converts a function to a universally quantified property using the
/// default shrinkers for those 8 types.
@warn_unused_result
public func forAll<A : Arbitrary, B : Arbitrary, C : Arbitrary, D : Arbitrary, E : Arbitrary, F : Arbitrary, G : Arbitrary, H : Arbitrary>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, _ genF : Gen<F>, _ genG : Gen<G>, _ genH : Gen<H>, pf : (A, B, C, D, E, F, G, H) -> Testable) -> Property {
return forAll(genA, pf: { t in forAll(genB, genC, genD, genE, genF, genG, genH, pf: { b, c, d, e, f, g, h in pf(t, b, c, d, e, f, g, h) }) })
}
/// Given an explicit generator, converts a function to a universally quantified property for that
/// type.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A>(gen : Gen<A>, pf : (A -> Testable)) -> Property {
return forAllShrink(gen, shrinker: { _ in [A]() }, f: pf)
}
/// Given 2 explicit generators, converts a function to a universally quantified property for those
/// 2 types.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A, B>(genA : Gen<A>, _ genB : Gen<B>, pf : (A, B) -> Testable) -> Property {
return forAllNoShrink(genA, pf: { t in forAllNoShrink(genB, pf: { b in pf(t, b) }) })
}
/// Given 3 explicit generators, converts a function to a universally quantified property for those
/// 3 types.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A, B, C>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, pf : (A, B, C) -> Testable) -> Property {
return forAllNoShrink(genA, pf: { t in forAllNoShrink(genB, genC, pf: { b, c in pf(t, b, c) }) })
}
/// Given 4 explicit generators, converts a function to a universally quantified property
/// for those 4 types.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A, B, C, D>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, pf : (A, B, C, D) -> Testable) -> Property {
return forAllNoShrink(genA, pf: { t in forAllNoShrink(genB, genC, genD, pf: { b, c, d in pf(t, b, c, d) }) })
}
/// Given 5 explicit generators, converts a function to a universally quantified property for those
/// 5 types.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A, B, C, D, E>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, pf : (A, B, C, D, E) -> Testable) -> Property {
return forAllNoShrink(genA, pf: { t in forAllNoShrink(genB, genC, genD, genE, pf: { b, c, d, e in pf(t, b, c, d, e) }) })
}
/// Given 6 explicit generators, converts a function to a universally quantified property for those
/// 6 types.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A, B, C, D, E, F>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, _ genF : Gen<F>, pf : (A, B, C, D, E, F) -> Testable) -> Property {
return forAllNoShrink(genA, pf: { t in forAllNoShrink(genB, genC, genD, genE, genF, pf: { b, c, d, e, f in pf(t, b, c, d, e, f) }) })
}
/// Given 7 explicit generators, converts a function to a universally quantified property for those
/// 7 types.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A, B, C, D, E, F, G>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, _ genF : Gen<F>, _ genG : Gen<G>, pf : (A, B, C, D, E, F, G) -> Testable) -> Property {
return forAllNoShrink(genA, pf: { t in forAllNoShrink(genB, genC, genD, genE, genF, genG, pf: { b, c, d, e, f, g in pf(t, b, c, d, e, f, g) }) })
}
/// Given 8 explicit generators, converts a function to a universally quantified property for those
/// 8 types.
///
/// This variant of `forAll` does not shrink its argument but allows generators of any type, not
/// just those that conform to `Arbitrary`.
@warn_unused_result
public func forAllNoShrink<A, B, C, D, E, F, G, H>(genA : Gen<A>, _ genB : Gen<B>, _ genC : Gen<C>, _ genD : Gen<D>, _ genE : Gen<E>, _ genF : Gen<F>, _ genG : Gen<G>, _ genH : Gen<H>, pf : (A, B, C, D, E, F, G, H) -> Testable) -> Property {
return forAllNoShrink(genA, pf: { t in forAllNoShrink(genB, genC, genD, genE, genF, genG, genH, pf: { b, c, d, e, f, g, h in pf(t, b, c, d, e, f, g, h) }) })
}
/// Given an explicit generator and shrinker, converts a function to a universally quantified
/// property.
@warn_unused_result
public func forAllShrink<A>(gen : Gen<A>, shrinker : A -> [A], f : A -> Testable) -> Property {
return Property(gen.bind { x in
return shrinking(shrinker, initial: x, prop: { xs in
return f(xs).counterexample(String(xs))
}).unProperty
})
}
/// Converts a function into an existentially quantified property using the default shrinker and
/// generator for that type to search for a passing case. SwiftCheck only runs a limited number of
/// trials before giving up and failing.
///
/// The nature of Existential Quantification means SwiftCheck would have to enumerate over the
/// entire domain of the type `A` in order to return a proper value. Because such a traversal is
/// both impractical and leads to computationally questionable behavior (infinite loops and the
/// like), SwiftCheck instead interprets `exists` as a finite search over arbitrarily many values
/// (around 500). No shrinking is performed during the search.
///
/// Existential Quantification should rarely be used, and in practice is usually used for *negative*
/// statements "there does not exist `foo` such that `bar`". It is recommended that you avoid
/// `exists` and instead reduce your property to
/// [Skolem Normal Form](https://en.wikipedia.org/wiki/Skolem_normal_form). `SNF` involves turning
/// every `exists` into a function returning the existential value, taking any other parameters
/// being quantified over as needed.
public func exists<A : Arbitrary>(pf : A -> Testable) -> Property {
return exists(A.arbitrary, pf: pf)
}
/// Given an explicit generator, converts a function to an existentially quantified property using
/// the default shrinker for that type.
public func exists<A : Arbitrary>(gen : Gen<A>, pf : A -> Testable) -> Property {
return forAllNoShrink(A.arbitrary, pf: { pf($0).invert }).invert.mapResult { res in
return TestResult(ok: res.ok
, expect: res.expect
, reason: res.reason
, theException: res.theException
, labels: res.labels
, stamp: res.stamp
, callbacks: res.callbacks
, abort: res.abort
, quantifier: .Existential)
}
}
public func quickCheck(prop : Testable, name : String = "") {
quickCheckWithResult(stdArgs(name), p: prop)
}
/// MARK: - Implementation Details
internal func stdArgs(name : String = "") -> CheckerArguments {
return CheckerArguments(replay: .None, maxAllowableSuccessfulTests: 100, maxAllowableDiscardedTests: 500, maxTestCaseSize: 100, name: name)
}
internal enum Result {
case Success(numTests : Int
, labels : [(String, Int)]
, output : String
)
case GaveUp(numTests : Int
, labels : [(String,Int)]
, output : String
)
case Failure(numTests : Int
, numShrinks : Int
, usedSeed : StdGen
, usedSize : Int
, reason : String
, labels : [(String,Int)]
, output : String
)
case ExistentialFailure(numTests: Int
, usedSeed : StdGen
, usedSize : Int
, reason : String
, labels : [(String,Int)]
, output : String
, lastResult : TestResult
)
case NoExpectedFailure(numTests : Int
, labels : [(String,Int)]
, output : String
)
}
internal indirect enum Either<L, R> {
case Left(L)
case Right(R)
}
internal func quickCheckWithResult(args : CheckerArguments, p : Testable) -> Result {
func roundTo(n : Int)(m : Int) -> Int {
return (m / m) * m
}
func rnd() -> StdGen {
switch args.replay {
case Optional.None:
return newStdGen()
case Optional.Some(let (rnd, _)):
return rnd
}
}
func at0(f : Int -> Int -> Int)(s : Int)(n : Int)(d : Int) -> Int {
if n == 0 && d == 0 {
return s
} else {
return f(n)(d)
}
}
let computeSize : Int -> Int -> Int = { x in
let computeSize_ : Int -> Int -> Int = { x in
return { y in
if roundTo(x)(m: args.maxTestCaseSize) + args.maxTestCaseSize <= args.maxAllowableSuccessfulTests ||
x >= args.maxAllowableSuccessfulTests ||
args.maxAllowableSuccessfulTests % args.maxTestCaseSize == 0 {
return min(x % args.maxTestCaseSize + (y / 10), args.maxTestCaseSize)
} else {
return min((x % args.maxTestCaseSize) * args.maxTestCaseSize / (args.maxAllowableSuccessfulTests % args.maxTestCaseSize) + y / 10, args.maxTestCaseSize)
}
}
}
return { y in
if let (_, sz) = args.replay {
return at0(computeSize_)(s: sz)(n: x)(d: y)
}
return computeSize_(x)(y)
}
}
let istate = CheckerState(name: args.name
, maxAllowableSuccessfulTests: args.maxAllowableSuccessfulTests
, maxAllowableDiscardedTests: args.maxAllowableDiscardedTests
, computeSize: computeSize
, successfulTestCount: 0
, discardedTestCount: 0
, labels: [:]
, collected: []
, hasFulfilledExpectedFailure: false
, randomSeedGenerator: rnd()
, successfulShrinkCount: 0
, failedShrinkStepDistance: 0
, failedShrinkStepCount: 0
, shouldAbort: false
, quantifier: .Universal)
let modP : Property = (p.exhaustive ? p.property.once : p.property)
return test(istate, f: modP.unProperty.unGen)
}
// Main Testing Loop:
//
// Given an initial state and the inner function that runs the property begins turning a runloop
// that starts firing off individual test cases. Only 3 functions get dispatched from this loop:
//
// - runATest: Does what it says; .Left indicates failure, .Right indicates continuation.
// - doneTesting: Invoked when testing the property fails or succeeds once and for all.
// - giveUp: When the number of discarded tests exceeds the number given in the arguments we just
// give up turning the run loop to prevent excessive generation.
internal func test(st : CheckerState, f : (StdGen -> Int -> Prop)) -> Result {
var state = st
while true {
switch runATest(state)(f: f) {
case let .Left(fail):
switch (fail.0, doneTesting(fail.1)(f: f)) {
case (.Success(_, _, _), _):
return fail.0
case let (_, .NoExpectedFailure(numTests, labels, output)):
return .NoExpectedFailure(numTests: numTests, labels: labels, output: output)
// Existential Failures need explicit propagation. Existentials increment the
// discard count so we check if it has been surpassed. If it has with any kind
// of success we're done. If no successes are found we've failed checking the
// existential and report it as such. Otherwise turn the testing loop.
case (.ExistentialFailure(_, _, _, _, _, _, _), _):
if fail.1.discardedTestCount >= fail.1.maxAllowableDiscardedTests && fail.1.successfulTestCount == 0 {
return reportExistentialFailure(fail.1, res: fail.0)
} else if fail.1.discardedTestCount >= fail.1.maxAllowableDiscardedTests {
return doneTesting(fail.1)(f: f)
} else {
state = fail.1
break
}
default:
return fail.0
}
case let .Right(lsta):
if lsta.successfulTestCount >= lsta.maxAllowableSuccessfulTests || lsta.shouldAbort {
return doneTesting(lsta)(f: f)
}
if lsta.discardedTestCount >= lsta.maxAllowableDiscardedTests || lsta.shouldAbort {
return giveUp(lsta)(f: f)
}
state = lsta
}
}
}
// Executes a single test of the property given an initial state and the generator function.
//
// On success the next state is returned. On failure the final result and state are returned.
internal func runATest(st : CheckerState)(f : (StdGen -> Int -> Prop)) -> Either<(Result, CheckerState), CheckerState> {
let size = st.computeSize(st.successfulTestCount)(st.discardedTestCount)
let (rnd1, rnd2) = st.randomSeedGenerator.split
// Execute the Rose Tree for the test and reduce to .MkRose.
switch reduce(f(rnd1)(size).unProp) {
case .MkRose(let resC, let ts):
let res = resC() // Force the result only once.
dispatchAfterTestCallbacks(st, res: res) // Then invoke the post-test callbacks
switch res.match() {
// Success
case .MatchResult(.Some(true), let expect, _, _, let labels, let stamp, _, let abort, let quantifier):
let nstate = CheckerState(name: st.name
, maxAllowableSuccessfulTests: st.maxAllowableSuccessfulTests
, maxAllowableDiscardedTests: st.maxAllowableDiscardedTests
, computeSize: st.computeSize
, successfulTestCount: st.successfulTestCount.successor()
, discardedTestCount: st.discardedTestCount
, labels: unionWith(max, l: st.labels, r: labels)
, collected: [stamp] + st.collected
, hasFulfilledExpectedFailure: expect
, randomSeedGenerator: st.randomSeedGenerator
, successfulShrinkCount: st.successfulShrinkCount
, failedShrinkStepDistance: st.failedShrinkStepDistance
, failedShrinkStepCount: st.failedShrinkStepCount
, shouldAbort: abort
, quantifier: quantifier)
return .Right(nstate)
// Discard
case .MatchResult(.None, let expect, _, _, let labels, _, _, let abort, let quantifier):
let nstate = CheckerState(name: st.name
, maxAllowableSuccessfulTests: st.maxAllowableSuccessfulTests
, maxAllowableDiscardedTests: st.maxAllowableDiscardedTests
, computeSize: st.computeSize
, successfulTestCount: st.successfulTestCount
, discardedTestCount: st.discardedTestCount.successor()
, labels: unionWith(max, l: st.labels, r: labels)
, collected: st.collected
, hasFulfilledExpectedFailure: expect
, randomSeedGenerator: rnd2
, successfulShrinkCount: st.successfulShrinkCount
, failedShrinkStepDistance: st.failedShrinkStepDistance
, failedShrinkStepCount: st.failedShrinkStepCount
, shouldAbort: abort
, quantifier: quantifier)
return .Right(nstate)
// Fail
case .MatchResult(.Some(false), let expect, _, _, _, _, _, let abort, let quantifier):
if quantifier == .Existential {
print("")
} else if !expect {
print("+++ OK, failed as expected. ", terminator: "")
} else {
print("*** Failed! ", terminator: "")
}
// Failure of an existential is not necessarily failure of the whole test case,
// so treat this like a discard.
if quantifier == .Existential {
let nstate = CheckerState(name: st.name
, maxAllowableSuccessfulTests: st.maxAllowableSuccessfulTests
, maxAllowableDiscardedTests: st.maxAllowableDiscardedTests
, computeSize: st.computeSize
, successfulTestCount: st.successfulTestCount
, discardedTestCount: st.discardedTestCount.successor()
, labels: st.labels
, collected: st.collected
, hasFulfilledExpectedFailure: expect
, randomSeedGenerator: rnd2
, successfulShrinkCount: st.successfulShrinkCount
, failedShrinkStepDistance: st.failedShrinkStepDistance
, failedShrinkStepCount: st.failedShrinkStepCount
, shouldAbort: abort
, quantifier: quantifier)
let resul = Result.ExistentialFailure(numTests: st.successfulTestCount + 1
, usedSeed: st.randomSeedGenerator
, usedSize: st.computeSize(st.successfulTestCount)(st.discardedTestCount)
, reason: "Could not satisfy existential"
, labels: summary(st)
, output: "*** Failed! "
, lastResult: res)
return .Left((resul, nstate))
}
// Attempt a shrink.
let (numShrinks, _, _) = findMinimalFailingTestCase(st, res: res, ts: ts())
if !expect {
let s = Result.Success(numTests: st.successfulTestCount.successor(), labels: summary(st), output: "+++ OK, failed as expected. ")
return .Left((s, st))
}
let stat = Result.Failure(numTests: st.successfulTestCount.successor()
, numShrinks: numShrinks
, usedSeed: st.randomSeedGenerator
, usedSize: st.computeSize(st.successfulTestCount)(st.discardedTestCount)
, reason: res.reason
, labels: summary(st)
, output: "*** Failed! ")
let nstate = CheckerState(name: st.name
, maxAllowableSuccessfulTests: st.maxAllowableSuccessfulTests
, maxAllowableDiscardedTests: st.maxAllowableDiscardedTests
, computeSize: st.computeSize
, successfulTestCount: st.successfulTestCount
, discardedTestCount: st.discardedTestCount.successor()
, labels: st.labels
, collected: st.collected
, hasFulfilledExpectedFailure: res.expect
, randomSeedGenerator: rnd2
, successfulShrinkCount: st.successfulShrinkCount
, failedShrinkStepDistance: st.failedShrinkStepDistance
, failedShrinkStepCount: st.failedShrinkStepCount
, shouldAbort: abort
, quantifier: quantifier)
return .Left((stat, nstate))
}
default:
fatalError("Pattern Match Failed: Rose should have been reduced to MkRose, not IORose.")
break
}
}
internal func doneTesting(st : CheckerState)(f : (StdGen -> Int -> Prop)) -> Result {
if st.hasFulfilledExpectedFailure {
print("*** Passed " + "\(st.successfulTestCount)" + pluralize(" test", i: st.successfulTestCount))
printDistributionGraph(st)
return .Success(numTests: st.successfulTestCount, labels: summary(st), output: "")
} else {
printDistributionGraph(st)
return .NoExpectedFailure(numTests: st.successfulTestCount, labels: summary(st), output: "")
}
}
internal func giveUp(st: CheckerState)(f : (StdGen -> Int -> Prop)) -> Result {
printDistributionGraph(st)
return Result.GaveUp(numTests: st.successfulTestCount, labels: summary(st), output: "")
}
// Interface to shrinking loop. Returns (number of shrinks performed, number of failed shrinks,
// total number of shrinks performed).
//
// This ridiculously stateful looping nonsense is due to limitations of the Swift unroller and, more
// importantly, ARC. This has been written with recursion in the past, and it was fabulous and
// beautiful, but it generated useless objects that ARC couldn't release on the order of Gigabytes
// for complex shrinks (much like `split` in the Swift STL), and was slow as hell. This way we stay
// in one stack frame no matter what and give ARC a chance to cleanup after us. Plus we get to
// stay within a reasonable ~50-100 megabytes for truly horrendous tests that used to eat 8 gigs.
internal func findMinimalFailingTestCase(st : CheckerState, res : TestResult, ts : [Rose<TestResult>]) -> (Int, Int, Int) {
if let e = res.theException {
fatalError("Test failed due to exception: \(e)")
}
var lastResult = res
var branches = ts
var successfulShrinkCount = st.successfulShrinkCount
var failedShrinkStepDistance = st.failedShrinkStepDistance.successor()
var failedShrinkStepCount = st.failedShrinkStepCount
// cont is a sanity check so we don't fall into an infinite loop. It is set to false at each
// new iteration and true when we select a new set of branches to test. If the branch
// selection doesn't change then we have exhausted our possibilities and so must have reached a
// minimal case.
var cont = true
while cont {
/// If we're out of branches we're out of options.
if branches.isEmpty {
break;
}
cont = false
failedShrinkStepDistance = 0
// Try all possible courses of action in this Rose Tree
branches.forEach { r in
switch reduce(r) {
case .MkRose(let resC, let ts1):
let res1 = resC()
dispatchAfterTestCallbacks(st, res: res1)
// Did we fail? Good! Failure is healthy.
// Try the next set of branches.
if res1.ok == .Some(false) {
lastResult = res1
branches = ts1()
cont = true
break;
}
// Otherwise increment the tried shrink counter and the failed shrink counter.
failedShrinkStepDistance++
failedShrinkStepCount++
default:
fatalError("Rose should not have reduced to IO")
}
}
successfulShrinkCount++
}
let state = CheckerState(name: st.name
, maxAllowableSuccessfulTests: st.maxAllowableSuccessfulTests
, maxAllowableDiscardedTests: st.maxAllowableDiscardedTests
, computeSize: st.computeSize
, successfulTestCount: st.successfulTestCount
, discardedTestCount: st.discardedTestCount
, labels: st.labels
, collected: st.collected
, hasFulfilledExpectedFailure: st.hasFulfilledExpectedFailure
, randomSeedGenerator: st.randomSeedGenerator
, successfulShrinkCount: successfulShrinkCount
, failedShrinkStepDistance: failedShrinkStepDistance
, failedShrinkStepCount: failedShrinkStepCount
, shouldAbort: st.shouldAbort
, quantifier: st.quantifier)
return reportMinimumCaseFound(state, res: lastResult)
}
internal func reportMinimumCaseFound(st : CheckerState, res : TestResult) -> (Int, Int, Int) {
let testMsg = " (after \(st.successfulTestCount.successor()) test"
let shrinkMsg = st.successfulShrinkCount > 1 ? (" and \(st.successfulShrinkCount) shrink") : ""
print("Proposition: " + st.name)
print(res.reason + pluralize(testMsg, i: st.successfulTestCount.successor()) + (st.successfulShrinkCount > 1 ? pluralize(shrinkMsg, i: st.successfulShrinkCount) : "") + "):")
dispatchAfterFinalFailureCallbacks(st, res: res)
return (st.successfulShrinkCount, st.failedShrinkStepCount - st.failedShrinkStepDistance, st.failedShrinkStepDistance)
}
internal func reportExistentialFailure(st : CheckerState, res : Result) -> Result {
switch res {
case let .ExistentialFailure(_, _, _, reason, _, _, lastTest):
let testMsg = " (after \(st.discardedTestCount) test"
print("*** Failed! ", terminator: "")
print("Proposition: " + st.name)
print(reason + pluralize(testMsg, i: st.discardedTestCount) + "):")
dispatchAfterFinalFailureCallbacks(st, res: lastTest)
return res
default:
fatalError("Cannot report existential failure on non-failure type \(res)")
}
}
internal func dispatchAfterTestCallbacks(st : CheckerState, res : TestResult) {
res.callbacks.forEach { c in
switch c {
case let .AfterTest(_, f):
f(st, res)
default:
break
}
}
}
internal func dispatchAfterFinalFailureCallbacks(st : CheckerState, res : TestResult) {
res.callbacks.forEach { c in
switch c {
case let .AfterFinalFailure(_, f):
f(st, res)
default:
break
}
}
}
internal func summary(s : CheckerState) -> [(String, Int)] {
let l = s.collected
.flatMap({ l in l.map({ "," + $0 }).filter({ !$0.isEmpty }) })
.sort()
.groupBy(==)
return l.map { ss in (ss.first!, ss.count * 100 / s.successfulTestCount) }
}
internal func labelPercentage(l : String, st : CheckerState) -> Int {
let occur = st.collected.flatMap(Array.init).filter { $0 == l }
return (100 * occur.count) / st.maxAllowableSuccessfulTests
}
internal func printLabels(st : TestResult) {
if st.labels.isEmpty {
print("(.)")
} else if st.labels.count == 1, let pt = st.labels.first {
print("(\(pt.0))")
} else {
let gAllLabels = st.labels.map({ (l, _) in
return l + ", "
}).reduce("", combine: +)
print("(" + gAllLabels[gAllLabels.startIndex..<gAllLabels.endIndex.advancedBy(-2)] + ")")
}
}
internal func printDistributionGraph(st : CheckerState) {
func showP(n : Int) -> String {
return (n < 10 ? " " : "") + "\(n)" + "%"
}
let gAllLabels = st.collected.map({ (s : Set<String>) in
return Array(s).filter({ t in st.labels[t] == .Some(0) }).reduce("", combine: { (l : String, r : String) in l + ", " + r })
})
let gAll = gAllLabels.filter({ !$0.isEmpty }).sort().groupBy(==)
let gPrint = gAll.map({ ss in showP((ss.count * 100) / st.successfulTestCount) + ss.first! })
let allLabels = Array(gPrint.sort().reverse())
var covers = [String]()
st.labels.forEach { (l, reqP) in
let p = labelPercentage(l, st: st)
if p < reqP {
covers += ["only \(p)% " + l + ", not \(reqP)%"]
}
}
let all = covers + allLabels
if all.isEmpty {
print(".")
} else if all.count == 1, let pt = all.first {
print("(\(pt))")
} else {
print(":")
all.forEach { pt in
print(pt)
}
}
}
internal func cons<T>(lhs : T, var _ rhs : [T]) -> [T] {
rhs.insert(lhs, atIndex: 0)
return rhs
}
private func pluralize(s : String, i : Int) -> String {
if i == 1 {
return s
}
return s + "s"
}
extension Array {
internal func groupBy(p : (Element , Element) -> Bool) -> [[Element]] {
func span(list : [Element], p : (Element -> Bool)) -> ([Element], [Element]) {
if list.isEmpty {
return ([], [])
} else if let x = list.first {
if p (x) {
let (ys, zs) = span([Element](list[1..<list.endIndex]), p: p)
return (cons(x, ys), zs)
}
return ([], list)
}
fatalError("span reached a non-empty list that could not produce a first element")
}
if self.isEmpty {
return []
} else if let x = self.first {
let (ys, zs) = span([Element](self[1..<self.endIndex]), p: { p(x, $0) })
let l = cons(x, ys)
return cons(l, zs.groupBy(p))
}
fatalError("groupBy reached a non-empty list that could not produce a first element")
}
}
| mit | e45a87b9966def5d3779c7359d27e50c | 43 | 329 | 0.65952 | 3.388924 | false | true | false | false |
DannyvanSwieten/SwiftSignals | GameEngine/Vector.swift | 1 | 2237 | //
// Vector.swift
// SwiftEngine
//
// Created by Danny van Swieten on 1/28/16.
// Copyright © 2016 Danny van Swieten. All rights reserved.
//
import Darwin
struct Vector4
{
var x: Float32 = 0
var y: Float32 = 0
var z: Float32 = 0
var w: Float32 = 0
func length() -> Float32 {
return sqrt(x * x + y * y + z * z + w * w)
}
mutating func normalize() -> Vector4 {
let l = length()
let constant = 1.0 / l
x *= constant
y *= constant
z *= constant
w *= constant
return self
}
func normalized() -> Vector4 {
let l = length()
let constant = 1.0 / l
let dx = x * constant
let dy = y * constant
let dz = z * constant
let dw = w * constant
return Vector4(x: dx, y: dy, z: dz, w: dw)
}
}
struct Vector3{
var x: Float32 = 0
var y: Float32 = 0
var z: Float32 = 0
func length() -> Float32 {
return sqrt(x * x + y * y + z * z)
}
mutating func normalize() {
let l = length()
let constant = 1.0 / l
x *= constant
y *= constant
z *= constant
}
func normalized() -> Vector3 {
let l = length()
let constant = 1.0 / l
let dx = x * constant
let dy = y * constant
let dz = z * constant
return Vector3(x: dx, y: dy, z: dz)
}
static func cross(a: Vector3, b: Vector3) -> Vector3 {
let x = a.y * b.z - a.z * b.y
let y = a.z * b.x - a.x * b.z
let z = a.x * b.y - a.y * b.x
return Vector3(x: x, y: y, z: z)
}
}
struct Vector2
{
var x: Float32 = 0
var y: Float32 = 0
func length() -> Float32 {
return sqrt(x * x + y * y)
}
mutating func normalize() {
let l = length()
let constant = 1.0 / l
x *= constant
y *= constant
}
mutating func normalized() -> Vector2 {
let l = length()
let constant = 1.0 / l
let dx = x * constant
let dy = y * constant
return Vector2(x: dx, y: dy)
}
}
typealias TextureCoordinates = Vector2 | gpl-3.0 | 4e0deb42d90b8a1f8d54f9d437d49048 | 19.906542 | 60 | 0.470036 | 3.532385 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/ChatsControllers/InputContainerView.swift | 1 | 12054 | //
// InputContainerView.swift
// Avalon-print
//
// Created by Roman Mizin on 3/25/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
import AVFoundation
final class InputContainerView: UIControl {
var audioPlayer: AVAudioPlayer!
weak var mediaPickerController: MediaPickerControllerNew?
weak var trayDelegate: ImagePickerTrayControllerDelegate?
var attachedMedia = [MediaObject]()
fileprivate var tap = UITapGestureRecognizer()
static let commentOrSendPlaceholder = "Comment or Send"
static let messagePlaceholder = "Message"
weak var chatLogController: ChatLogViewController? {
didSet {
sendButton.addTarget(chatLogController, action: #selector(ChatLogViewController.sendMessage), for: .touchUpInside)
}
}
lazy var inputTextView: InputTextView = {
let textView = InputTextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
return textView
}()
lazy var attachCollectionView: AttachCollectionView = {
let attachCollectionView = AttachCollectionView()
return attachCollectionView
}()
let placeholderLabel: UILabel = {
let placeholderLabel = UILabel()
placeholderLabel.text = messagePlaceholder
placeholderLabel.sizeToFit()
placeholderLabel.textColor = ThemeManager.currentTheme().generalSubtitleColor
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
return placeholderLabel
}()
var attachButton: MediaPickerRespondingButton = {
var attachButton = MediaPickerRespondingButton()
attachButton.addTarget(self, action: #selector(togglePhoto), for: .touchDown)
return attachButton
}()
var recordVoiceButton: VoiceRecorderRespondingButton = {
var recordVoiceButton = VoiceRecorderRespondingButton()
recordVoiceButton.addTarget(self, action: #selector(toggleVoiceRecording), for: .touchDown)
return recordVoiceButton
}()
let sendButton: UIButton = {
let sendButton = UIButton(type: .custom)
sendButton.setImage(UIImage(named: "send"), for: .normal)
sendButton.translatesAutoresizingMaskIntoConstraints = false
sendButton.isEnabled = false
sendButton.backgroundColor = .white
return sendButton
}()
private var heightConstraint: NSLayoutConstraint!
private func addHeightConstraints() {
heightConstraint = heightAnchor.constraint(equalToConstant: InputTextViewLayout.minHeight)
heightConstraint.isActive = true
}
func confirugeHeightConstraint() {
let size = inputTextView.sizeThatFits(CGSize(width: inputTextView.bounds.size.width, height: .infinity))
let height = size.height + 12
heightConstraint.constant = height < InputTextViewLayout.maxHeight() ? height : InputTextViewLayout.maxHeight()
let maxHeight: CGFloat = InputTextViewLayout.maxHeight()
guard height >= maxHeight else { inputTextView.isScrollEnabled = false; return }
inputTextView.isScrollEnabled = true
}
func handleRotation() {
attachCollectionView.collectionViewLayout.invalidateLayout()
DispatchQueue.main.async { [weak self] in
guard let width = self?.inputTextView.frame.width else { return }
self?.attachCollectionView.frame.size.width = width//self?.inputTextView.frame.width
self?.attachCollectionView.reloadData()
self?.confirugeHeightConstraint()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
NotificationCenter.default.addObserver(self, selector: #selector(changeTheme),
name: .themeUpdated, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(inputViewResigned),
name: .inputViewResigned, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(inputViewResponded),
name: .inputViewResponded, object: nil)
addHeightConstraints()
backgroundColor = ThemeManager.currentTheme().barBackgroundColor
// sendButton.tintColor = ThemeManager.generalTintColor
addSubview(attachButton)
addSubview(recordVoiceButton)
addSubview(inputTextView)
addSubview(sendButton)
addSubview(placeholderLabel)
inputTextView.addSubview(attachCollectionView)
sendButton.layer.cornerRadius = 15
sendButton.clipsToBounds = true
tap = UITapGestureRecognizer(target: self, action: #selector(toggleTextView))
tap.delegate = self
if #available(iOS 11.0, *) {
attachButton.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 5).isActive = true
inputTextView.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true
} else {
attachButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
inputTextView.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true
}
attachButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
attachButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
attachButton.widthAnchor.constraint(equalToConstant: 35).isActive = true
recordVoiceButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
recordVoiceButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
recordVoiceButton.widthAnchor.constraint(equalToConstant: 35).isActive = true
recordVoiceButton.leftAnchor.constraint(equalTo: attachButton.rightAnchor, constant: 0).isActive = true
inputTextView.topAnchor.constraint(equalTo: topAnchor, constant: 6).isActive = true
inputTextView.leftAnchor.constraint(equalTo: recordVoiceButton.rightAnchor, constant: 3).isActive = true
inputTextView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6).isActive = true
placeholderLabel.font = UIFont.systemFont(ofSize: (inputTextView.font!.pointSize))
placeholderLabel.isHidden = !inputTextView.text.isEmpty
placeholderLabel.leftAnchor.constraint(equalTo: inputTextView.leftAnchor, constant: 12).isActive = true
placeholderLabel.rightAnchor.constraint(equalTo: inputTextView.rightAnchor).isActive = true
placeholderLabel.topAnchor.constraint(equalTo: attachCollectionView.bottomAnchor,
constant: inputTextView.font!.pointSize / 2.3).isActive = true
placeholderLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
sendButton.rightAnchor.constraint(equalTo: inputTextView.rightAnchor, constant: -4).isActive = true
sendButton.bottomAnchor.constraint(equalTo: inputTextView.bottomAnchor, constant: -4).isActive = true
sendButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
sendButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
configureAttachCollectionView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func changeTheme() {
backgroundColor = ThemeManager.currentTheme().barBackgroundColor
inputTextView.changeTheme()
attachButton.changeTheme()
recordVoiceButton.changeTheme()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
@objc func toggleTextView () {
print("toggling")
inputTextView.inputView = nil
inputTextView.reloadInputViews()
UIView.performWithoutAnimation {
inputTextView.resignFirstResponder()
inputTextView.becomeFirstResponder()
}
}
@objc fileprivate func inputViewResigned() {
inputTextView.removeGestureRecognizer(tap)
}
@objc fileprivate func inputViewResponded() {
guard let recognizers = inputTextView.gestureRecognizers else { return }
guard !recognizers.contains(tap) else { return }
inputTextView.addGestureRecognizer(tap)
}
@objc func togglePhoto () {
checkAuthorisationStatus()
UIView.performWithoutAnimation {
_ = recordVoiceButton.resignFirstResponder()
}
if attachButton.isFirstResponder {
_ = attachButton.resignFirstResponder()
} else {
if attachButton.controller == nil {
attachButton.controller = MediaPickerControllerNew()
mediaPickerController = attachButton.controller
mediaPickerController?.mediaPickerDelegate = self
}
_ = attachButton.becomeFirstResponder()
// inputTextView.addGestureRecognizer(tap)
}
}
@objc func toggleVoiceRecording () {
UIView.performWithoutAnimation {
_ = attachButton.resignFirstResponder()
}
if recordVoiceButton.isFirstResponder {
_ = recordVoiceButton.resignFirstResponder()
} else {
if recordVoiceButton.controller == nil {
recordVoiceButton.controller = VoiceRecordingViewController()
recordVoiceButton.controller?.mediaPickerDelegate = self
}
_ = recordVoiceButton.becomeFirstResponder()
// inputTextView.addGestureRecognizer(tap)
}
}
func resignAllResponders() {
inputTextView.resignFirstResponder()
_ = attachButton.resignFirstResponder()
_ = recordVoiceButton.resignFirstResponder()
}
}
extension InputContainerView {
func prepareForSend() {
inputTextView.text = ""
sendButton.isEnabled = false
placeholderLabel.isHidden = false
inputTextView.isScrollEnabled = false
attachedMedia.removeAll()
attachCollectionView.reloadData()
resetChatInputConntainerViewSettings()
}
func resetChatInputConntainerViewSettings() {
guard attachedMedia.isEmpty else { return }
attachCollectionView.frame = CGRect(x: 0, y: 0, width: inputTextView.frame.width, height: 0)
inputTextView.textContainerInset = InputTextViewLayout.defaultInsets
placeholderLabel.text = InputContainerView.messagePlaceholder
sendButton.isEnabled = !inputTextView.text.isEmpty
confirugeHeightConstraint()
}
func expandCollection() {
sendButton.isEnabled = (!inputTextView.text.isEmpty || !attachedMedia.isEmpty)
placeholderLabel.text = InputContainerView.commentOrSendPlaceholder
attachCollectionView.frame = CGRect(x: 0, y: 3,
width: inputTextView.frame.width, height: AttachCollectionView.height)
inputTextView.textContainerInset = InputTextViewLayout.extendedInsets
confirugeHeightConstraint()
}
}
extension InputContainerView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard attachCollectionView.bounds.contains(touch.location(in: attachCollectionView)) else { return true }
return false
}
}
extension InputContainerView: UITextViewDelegate {
private func handleSendButtonState() {
let whiteSpaceIsEmpty = inputTextView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty
if (attachedMedia.count > 0 && !whiteSpaceIsEmpty) || (inputTextView.text != "" && !whiteSpaceIsEmpty) {
sendButton.isEnabled = true
} else {
sendButton.isEnabled = false
}
}
func textViewDidChange(_ textView: UITextView) {
confirugeHeightConstraint()
placeholderLabel.isHidden = !textView.text.isEmpty
chatLogController?.isTyping = !textView.text.isEmpty
handleSendButtonState()
}
func textViewDidEndEditing(_ textView: UITextView) {
if chatLogController?.chatLogAudioPlayer != nil {
chatLogController?.chatLogAudioPlayer.stop()
chatLogController?.chatLogAudioPlayer = nil
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard text == "\n", let chatLogController = self.chatLogController else { return true }
if chatLogController.isScrollViewAtTheBottom() {
chatLogController.collectionView.scrollToBottom(animated: false)
}
return true
}
}
| gpl-3.0 | 9b53abe0b1b07909fd066557aaed5a11 | 36.548287 | 155 | 0.743466 | 5.190784 | false | false | false | false |
toohotz/IQKeyboardManager | Demo/Swift_Demo/ViewController/ViewController.swift | 1 | 2789 | //
// ViewController.swift
// swift test
//
// Created by Iftekhar on 22/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import UIKit
class ViewController: UITableViewController, UIPopoverPresentationControllerDelegate {
@IBAction func shareClicked (sender : UIBarButtonItem) {
let shareString : String = "IQKeyboardManager is really great control for iOS developer to manage keyboard-textField."
let shareImage : UIImage = UIImage(named: "IQKeyboardManagerScreenshot")!
let youtubeUrl : NSURL = NSURL(string: "http://youtu.be/6nhLw6hju2A")!
var activityItems = [NSObject]()
activityItems.append(shareString)
activityItems.append(shareImage)
activityItems.append(youtubeUrl)
let excludedActivities = [String]()
activityItems.append(UIActivityTypePrint)
activityItems.append(UIActivityTypeCopyToPasteboard)
activityItems.append(UIActivityTypeAssignToContact)
activityItems.append(UIActivityTypeSaveToCameraRoll)
let controller = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
controller.excludedActivityTypes = excludedActivities
presentViewController(controller, animated: true) { () -> Void in
}
}
override func viewDidLoad() {
super.viewDidLoad()
IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour.ByPosition
// Do any additional setup after loading the view, typically from a nib.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "SettingsNavigationController" {
let controller = segue.destinationViewController
controller.modalPresentationStyle = .Popover
controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
let heightWidth = max(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds));
controller.preferredContentSize = CGSizeMake(heightWidth, heightWidth)
controller.popoverPresentationController?.delegate = self
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) {
self.view.endEditing(true)
}
override func shouldAutorotate() -> Bool {
return true
}
}
| mit | 1af966af100f476deccd3abec517e1fe | 37.736111 | 131 | 0.682682 | 6.267416 | false | false | false | false |
muneebm/AsterockX | AsterockX/MasterTableViewController.swift | 1 | 7474 | //
// MasterTableViewController.swift
// AsterockX
//
// Created by Muneeb Rahim Abdul Majeed on 1/4/16.
// Copyright © 2016 beenum. All rights reserved.
//
import UIKit
import CoreData
import NEOWS
class MasterTableViewController: BaseTableViewController {
var selectedAsteroid: Asteroid!
var selectAsteroidForIndexPath: ((indexPath: NSIndexPath) -> Void)!
struct CommonConstants {
static let ShowDetailSegueID = "ShowDetails"
static let AsteroidCell = "AsteroidCell"
static let HazardText = "Hazard"
static let NoHazardText = "No Hazard"
static let NeoReferenceID = "neoReferenceId"
static let NonFavoriteTitle = "★"
static let FavoriteTitle = "⭐"
}
lazy var fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: Utility.Constants.AsteroidEntityName)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: CommonConstants.NeoReferenceID, ascending: true)]
fetchRequest.predicate = NSPredicate(format: "isFavorite.boolValue == %@", true);
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}()
override func viewDidLoad() {
super.viewDidLoad()
do {
try fetchedResultsController.performFetch()
}
catch {}
tableView.registerNib(UINib(nibName: CommonConstants.AsteroidCell, bundle: nil), forCellReuseIdentifier: CommonConstants.AsteroidCell)
if traitCollection.forceTouchCapability == .Available {
registerForPreviewingWithDelegate(self, sourceView: view)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == CommonConstants.ShowDetailSegueID {
let dvc = segue.destinationViewController as! DetailViewController
dvc.selectedAsteroid = selectedAsteroid
dvc.navigationItem.title = selectedAsteroid?.name
let title = selectedAsteroid.isFavorite?.boolValue ?? false ? CommonConstants.FavoriteTitle : CommonConstants.NonFavoriteTitle
dvc.navigationItem.rightBarButtonItem = UIBarButtonItem(title: title, style: .Plain, target: self, action: Selector("favoriteButtonClicked:"))
}
}
func favoriteButtonClicked(sender: UIBarButtonItem) {
if sender.title == CommonConstants.NonFavoriteTitle {
sender.title = CommonConstants.FavoriteTitle
selectedAsteroid?.isFavorite = true
}
else {
sender.title = CommonConstants.NonFavoriteTitle
selectedAsteroid?.isFavorite = false
}
dispatch_async(dispatch_get_main_queue()) {
() -> Void in
self.coreDataStack.saveContext()
}
}
func configureAsteroidCell(cell: AsteroidCell, withNeo neo: Neo) {
cell.nameLabel.text = neo.name
cell.hazardLabel.textColor = neo.isPotentiallyHazardous! ? UIColor.brownColor() : Utility.Constants.Accent
cell.hazardLabel.text = neo.isPotentiallyHazardous! ? CommonConstants.HazardText : CommonConstants.NoHazardText
cell.neoReferenceIdLabel.text = neo.neoReferenceId!
cell.absoluteMagnitudeLabel.text = "\(neo.absoluteMagnitudeH!)"
var estimatedDiameter: MinMaxPair!
let diameterUnit = Settings.diameterUnit()
switch diameterUnit {
case Settings.Constants.Kilometers:
estimatedDiameter = neo.estimatedDiameter?.kilometers
case Settings.Constants.Meters:
estimatedDiameter = neo.estimatedDiameter?.meters
case Settings.Constants.Miles:
estimatedDiameter = neo.estimatedDiameter?.miles
case Settings.Constants.Feet:
estimatedDiameter = neo.estimatedDiameter?.feet
default:
break
}
cell.estimatedDiameterLabel.text = "\(estimatedDiameter.minimum!.roundToDecimals()) - \(estimatedDiameter.maximum!.roundToDecimals()) \(diameterUnit)"
}
func configureAsteroidCell(cell: AsteroidCell, withAsteroid asteroid: Asteroid) {
cell.nameLabel.text = asteroid.name
cell.hazardLabel.textColor = asteroid.isPotentiallyHazardous!.boolValue ? UIColor.brownColor() : Utility.Constants.Accent
cell.hazardLabel.text = asteroid.isPotentiallyHazardous!.boolValue ? CommonConstants.HazardText : CommonConstants.NoHazardText
cell.neoReferenceIdLabel.text = asteroid.neoReferenceId!
cell.absoluteMagnitudeLabel.text = "\(asteroid.absoluteMagnitudeH!)"
let diameterUnit = Settings.diameterUnit()
if let estimatedDiameter = asteroid.estimatedDiameter.filter( { $0.unitName == diameterUnit } ).first {
cell.estimatedDiameterLabel.text = "\(estimatedDiameter.minimum!.doubleValue.roundToDecimals()) - \(estimatedDiameter.maximum!.doubleValue.roundToDecimals()) \(diameterUnit)"
}
}
func navigateToDetailView(neo: Neo) {
selectAsteroidForNeo(neo)
navigateToDetailView()
}
func navigateToDetailView() {
if selectedAsteroid != nil {
performSegueWithIdentifier(CommonConstants.ShowDetailSegueID, sender: self)
}
}
func selectAsteroidForNeo(neo: Neo) {
let fetchRequest = NSFetchRequest(entityName: Utility.Constants.AsteroidEntityName)
fetchRequest.predicate = NSPredicate(format: "neoReferenceId == %@", neo.neoReferenceId!)
var data: [Asteroid]? = nil
do {
data = try sharedContext.executeFetchRequest(fetchRequest) as? [Asteroid]
}
catch {}
if let asteroid = data?.first {
selectedAsteroid = asteroid
}
else {
selectedAsteroid = Asteroid(neo: neo, context: sharedContext)
}
}
}
extension MasterTableViewController : UIViewControllerPreviewingDelegate {
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRowAtPoint(location),
cell = tableView.cellForRowAtIndexPath(indexPath) else { return nil }
guard let detailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController else { return nil }
selectAsteroidForIndexPath(indexPath: indexPath)
detailViewController.selectedAsteroid = selectedAsteroid
previewingContext.sourceRect = cell.frame
return detailViewController
}
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
showViewController(viewControllerToCommit, sender: self)
}
}
| mit | a19d0b499e928cf04a3e69385b5ce2e7 | 36.913706 | 186 | 0.663141 | 5.24877 | false | false | false | false |
LinShiwei/HealthyDay | HealthyDay/StepEverydayView.swift | 1 | 2127 | //
// StepEverydayView.swift
// HealthyDay
//
// Created by Sun Haoting on 16/10/14.
// Copyright © 2016年 Linsw. All rights reserved.
//
import UIKit
class StepEverydayView: UIView {
let stepLabel = UILabel()
private var isToday = false
private let dot = CALayer()
private var dotRadius = CGFloat()
private var proportion = CGFloat()
private var stepCount = Int()
init(frame: CGRect,proportion: CGFloat,stepCount: Int, isToday: Bool) {
super.init(frame: frame)
self.proportion = proportion
self.stepCount = stepCount
self.isToday = isToday
initDotLayer()
initStepLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func initDotLayer() {
guard superview == nil else{return}
let lineChartHeight = frame.height * 2.5 / 3.5
if isToday {
dotRadius = 3
dot.borderWidth = 1.5
dot.borderColor = UIColor.green.cgColor
dot.backgroundColor = UIColor.white.cgColor
} else {
dotRadius = 6
dot.borderWidth = 2
dot.borderColor = UIColor.white.cgColor
dot.backgroundColor = UIColor.green.cgColor
}
let dotY = frame.height - lineChartHeight * proportion - dotRadius
dot.position = CGPoint(x: frame.width / 2 - dotRadius, y: dotY)
dot.frame.size = CGSize(width: dotRadius * 2, height: dotRadius * 2)
dot.cornerRadius = CGFloat(dotRadius)
layer.addSublayer(dot)
}
internal func dotPosition() -> CGPoint {
return dot.position
}
private func initStepLabel() {
stepLabel.frame = CGRect(x: frame.width * 0.1, y: dotPosition().y - frame.height / 3.5, width: frame.width * 0.8, height: frame.height / 4)
stepLabel.text = "\(stepCount)"
stepLabel.textAlignment = .center
stepLabel.textColor = UIColor.black
stepLabel.adjustsFontSizeToFitWidth = true
stepLabel.alpha = isToday ? 1 : 0
addSubview(stepLabel)
}
}
| mit | 784d408a6c2d27bf4476cfa5e53c3135 | 29.782609 | 147 | 0.608286 | 4.282258 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.